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

+1139 -231
View File
File diff suppressed because it is too large. Load diff
+219
View File
@@ -0,0 +1,219 @@
#include <math.h>
#include <stdint.h>
#include <stddef.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/* Unpack 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into 4x4 supercell BGR16 (0..4092). */
void quad_csi2p_to_bgr16_4x4(
const uint8_t *raw,
int width,
int height,
int stride,
uint16_t *out_bgr16
) {
if (!raw || !out_bgr16 || width < 4 || height < 4 || stride <= 0) {
return;
}
const int out_w = width / 4;
const int out_h = height / 4;
#ifdef _OPENMP
#pragma omp parallel for schedule(static) num_threads(4) if (out_h >= 64)
#endif
for (int cy = 0; cy < out_h; cy++) {
const uint8_t *r0 = raw + (size_t)(cy * 4 + 0) * (size_t)stride;
const uint8_t *r1 = raw + (size_t)(cy * 4 + 1) * (size_t)stride;
const uint8_t *r2 = raw + (size_t)(cy * 4 + 2) * (size_t)stride;
const uint8_t *r3 = raw + (size_t)(cy * 4 + 3) * (size_t)stride;
uint16_t *dst = out_bgr16 + (size_t)cy * (size_t)out_w * 3;
for (int cx = 0; cx < out_w; cx++) {
const size_t off = (size_t)cx * 5;
const uint8_t lo0 = r0[off + 4];
const uint8_t lo1 = r1[off + 4];
const uint8_t lo2 = r2[off + 4];
const uint8_t lo3 = r3[off + 4];
/* Rows 4y, 4y+1: (p0, p1) = R, (p2, p3) = Gr */
uint32_t r_sum = ((uint32_t)r0[off + 0] + r0[off + 1] + r1[off + 0] + r1[off + 1]) << 2;
r_sum += (uint32_t)(lo0 & 3U) + ((lo0 >> 2) & 3U) + (lo1 & 3U) + ((lo1 >> 2) & 3U);
uint32_t gr_sum = ((uint32_t)r0[off + 2] + r0[off + 3] + r1[off + 2] + r1[off + 3]) << 2;
gr_sum += (uint32_t)((lo0 >> 4) & 3U) + ((lo0 >> 6) & 3U) + ((lo1 >> 4) & 3U) + ((lo1 >> 6) & 3U);
/* Rows 4y+2, 4y+3: (p0, p1) = Gb, (p2, p3) = B */
uint32_t gb_sum = ((uint32_t)r2[off + 0] + r2[off + 1] + r3[off + 0] + r3[off + 1]) << 2;
gb_sum += (uint32_t)(lo2 & 3U) + ((lo2 >> 2) & 3U) + (lo3 & 3U) + ((lo3 >> 2) & 3U);
uint32_t b_sum = ((uint32_t)r2[off + 2] + r2[off + 3] + r3[off + 2] + r3[off + 3]) << 2;
b_sum += (uint32_t)((lo2 >> 4) & 3U) + ((lo2 >> 6) & 3U) + ((lo3 >> 4) & 3U) + ((lo3 >> 6) & 3U);
uint32_t g_avg = (gr_sum + gb_sum + 1U) >> 1;
dst[0] = (uint16_t)b_sum;
dst[1] = (uint16_t)g_avg;
dst[2] = (uint16_t)r_sum;
dst += 3;
}
}
}
/* Unpack 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into 16-bit Bayer (0..4092). */
void quad_csi2p_to_bayer16_2x2(
const uint8_t *raw,
int width,
int height,
int stride,
uint16_t *out_bayer16
) {
if (!raw || !out_bayer16 || width < 4 || height < 2 || stride <= 0) {
return;
}
const int nblk = width / 4;
const int out_w = nblk * 2;
const int out_h = height / 2;
#ifdef _OPENMP
#pragma omp parallel for schedule(static) num_threads(4) if (out_h >= 64)
#endif
for (int by = 0; by < out_h; by++) {
const uint8_t *r0 = raw + (size_t)(by * 2 + 0) * (size_t)stride;
const uint8_t *r1 = raw + (size_t)(by * 2 + 1) * (size_t)stride;
uint16_t *dst = out_bayer16 + (size_t)by * (size_t)out_w;
for (int bx = 0; bx < nblk; bx++) {
const size_t off = (size_t)bx * 5;
const uint8_t lo0 = r0[off + 4];
const uint8_t lo1 = r1[off + 4];
uint32_t c0 = ((uint32_t)r0[off + 0] + r0[off + 1] + r1[off + 0] + r1[off + 1]) << 2;
c0 += (uint32_t)(lo0 & 3U) + ((lo0 >> 2) & 3U) + (lo1 & 3U) + ((lo1 >> 2) & 3U);
uint32_t c1 = ((uint32_t)r0[off + 2] + r0[off + 3] + r1[off + 2] + r1[off + 3]) << 2;
c1 += (uint32_t)((lo0 >> 4) & 3U) + ((lo0 >> 6) & 3U) + ((lo1 >> 4) & 3U) + ((lo1 >> 6) & 3U);
dst[0] = (uint16_t)c0;
dst[1] = (uint16_t)c1;
dst += 2;
}
}
}
/* Fused black-level subtraction, AWB + exposure scaling, 3x3 linear RGB CCM, and LUT tone-map. */
void isp_ccm_tone_bgr16_to_bgr8(
const uint16_t *in_bgr16,
uint8_t *out_bgr8,
int pixels,
float black,
float scale_norm,
float gain_b,
float gain_g,
float gain_r,
const float ccm_rgb[9],
const uint8_t lut[4096],
float lut_max
) {
if (!in_bgr16 || !out_bgr8 || !ccm_rgb || !lut || pixels <= 0) {
return;
}
const float m00 = ccm_rgb[0], m01 = ccm_rgb[1], m02 = ccm_rgb[2];
const float m10 = ccm_rgb[3], m11 = ccm_rgb[4], m12 = ccm_rgb[5];
const float m20 = ccm_rgb[6], m21 = ccm_rgb[7], m22 = ccm_rgb[8];
const float sb = scale_norm * gain_b;
const float sg = scale_norm * gain_g;
const float sr = scale_norm * gain_r;
const float inv_lut = 4095.0f / (lut_max > 1e-6f ? lut_max : 1.0f);
#ifdef _OPENMP
#pragma omp parallel for schedule(static) num_threads(4) if (pixels >= 16384)
#endif
for (int i = 0; i < pixels; i++) {
const size_t idx = (size_t)i * 3;
float b = (float)in_bgr16[idx + 0] - black;
float g = (float)in_bgr16[idx + 1] - black;
float r = (float)in_bgr16[idx + 2] - black;
if (b < 0.0f) b = 0.0f;
if (g < 0.0f) g = 0.0f;
if (r < 0.0f) r = 0.0f;
b *= sb;
g *= sg;
r *= sr;
float rc = m00 * r + m01 * g + m02 * b;
float gc = m10 * r + m11 * g + m12 * b;
float bc = m20 * r + m21 * g + m22 * b;
int ir = (int)(rc * inv_lut + 0.5f);
int ig = (int)(gc * inv_lut + 0.5f);
int ib = (int)(bc * inv_lut + 0.5f);
if (ir < 0) ir = 0; else if (ir > 4095) ir = 4095;
if (ig < 0) ig = 0; else if (ig > 4095) ig = 4095;
if (ib < 0) ib = 0; else if (ib > 4095) ib = 4095;
out_bgr8[idx + 0] = lut[ib];
out_bgr8[idx + 1] = lut[ig];
out_bgr8[idx + 2] = lut[ir];
}
}
/* Motion-guarded multi-frame temporal merge in linear 16-bit BGR space. */
void burst_merge_bgr16(
const uint16_t *base,
const uint16_t *const *others,
int num_others,
uint16_t *out,
int pixels,
float noise_thresh
) {
if (!base || !out || pixels <= 0) {
return;
}
const float inv_nt = 1.0f / (noise_thresh > 1.0f ? noise_thresh : 1.0f);
#ifdef _OPENMP
#pragma omp parallel for schedule(static) num_threads(4) if (pixels >= 16384)
#endif
for (int i = 0; i < pixels; i++) {
const size_t idx = (size_t)i * 3;
const float b0 = (float)base[idx + 0];
const float g0 = (float)base[idx + 1];
const float r0 = (float)base[idx + 2];
const float l0 = 0.114f * b0 + 0.587f * g0 + 0.299f * r0;
float acc_b = b0;
float acc_g = g0;
float acc_r = r0;
float w_sum = 1.0f;
for (int k = 0; k < num_others; k++) {
const uint16_t *oth = others[k];
if (!oth) continue;
const float bk = (float)oth[idx + 0];
const float gk = (float)oth[idx + 1];
const float rk = (float)oth[idx + 2];
const float lk = 0.114f * bk + 0.587f * gk + 0.299f * rk;
const float d = fabsf(lk - l0) * inv_nt;
const float d2 = d * d;
const float w = 1.0f / (1.0f + d2 * d2);
acc_b += w * bk;
acc_g += w * gk;
acc_r += w * rk;
w_sum += w;
}
const float inv_w = 1.0f / w_sum;
int ob = (int)(acc_b * inv_w + 0.5f);
int og = (int)(acc_g * inv_w + 0.5f);
int or_v = (int)(acc_r * inv_w + 0.5f);
if (ob < 0) ob = 0; else if (ob > 65535) ob = 65535;
if (og < 0) og = 0; else if (og > 65535) og = 65535;
if (or_v < 0) or_v = 0; else if (or_v > 65535) or_v = 65535;
out[idx + 0] = (uint16_t)ob;
out[idx + 1] = (uint16_t)og;
out[idx + 2] = (uint16_t)or_v;
}
}
+147 -22
View File
@@ -63,19 +63,36 @@ typedef struct {
/* Shared latest frame from worker (CAIRO_FORMAT_RGB24 BGRA32) */
GMutex frame_mutex;
uint8_t *frame_buf;
size_t frame_cap;
int frame_w;
int frame_h;
size_t frame_len;
uint64_t frame_seq;
gboolean draw_pending;
/* Paint copy owned exclusively by GTK main thread */
/* Paint & reader buffers swapped under frame_mutex (zero per-frame alloc/memcpy) */
uint8_t *paint_buf;
size_t paint_cap;
int paint_w;
int paint_h;
size_t paint_len;
uint64_t paint_seq;
uint8_t *read_buf;
size_t read_cap;
/* Viewfinder draw rect & tap-to-focus reticle */
double view_rx;
double view_ry;
double view_rw;
double view_rh;
gboolean has_af;
gboolean af_active;
gboolean af_locked;
double af_nx;
double af_ny;
int64_t af_until_us;
/* Camera & UI state */
int cam_count;
gboolean has_flash;
@@ -366,18 +383,19 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) {
cairo_set_source_rgb(cr, 0.043, 0.051, 0.078);
cairo_paint(cr);
/* Copy latest frame buffer without holding frame_mutex during Cairo paint. */
/* Swap latest frame pointer without holding frame_mutex during Cairo paint. */
g_mutex_lock(&app->frame_mutex);
if (app->frame_buf && app->frame_seq != app->paint_seq) {
uint8_t *nb = (uint8_t *)realloc(app->paint_buf, app->frame_len);
if (nb) {
app->paint_buf = nb;
memcpy(app->paint_buf, app->frame_buf, app->frame_len);
app->paint_w = app->frame_w;
app->paint_h = app->frame_h;
app->paint_len = app->frame_len;
app->paint_seq = app->frame_seq;
}
uint8_t *tmp_buf = app->paint_buf;
size_t tmp_cap = app->paint_cap;
app->paint_buf = app->frame_buf;
app->paint_cap = app->frame_cap;
app->paint_w = app->frame_w;
app->paint_h = app->frame_h;
app->paint_len = app->frame_len;
app->paint_seq = app->frame_seq;
app->frame_buf = tmp_buf;
app->frame_cap = tmp_cap;
}
g_mutex_unlock(&app->frame_mutex);
@@ -399,6 +417,10 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) {
ry = y;
rw = dw;
rh = dh;
app->view_rx = rx;
app->view_ry = ry;
app->view_rw = rw;
app->view_rh = rh;
cairo_surface_t *surf = cairo_image_surface_create_for_data(
app->paint_buf, CAIRO_FORMAT_RGB24, iw, ih, iw * 4);
@@ -441,6 +463,20 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) {
cairo_stroke(cr);
}
if (app->af_active && g_get_monotonic_time() <= app->af_until_us) {
double fx = rx + app->af_nx * rw;
double fy = ry + app->af_ny * rh;
double sz = app->af_locked ? 46.0 : 54.0;
rounded_rect_path(cr, fx - sz / 2.0, fy - sz / 2.0, sz, sz, 10.0);
if (app->af_locked) {
cairo_set_source_rgba(cr, 0.20, 0.83, 0.60, 0.92);
} else {
cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.88);
}
cairo_set_line_width(cr, 2.0);
cairo_stroke(cr);
}
if (app->countdown_left > 0) {
char buf[16];
snprintf(buf, sizeof(buf), "%d", app->countdown_left);
@@ -685,6 +721,27 @@ static gboolean handle_worker_line_idle(gpointer data) {
gtk_label_set_text(GTK_LABEL(app->rec_label), "● 00:00");
}
sync_ui_labels(app);
} else if (strncmp(line, "af_caps ", 8) == 0) {
app->has_af = (atoi(line + 8) != 0);
if (!app->has_af) {
app->af_active = FALSE;
gtk_widget_queue_draw(app->view_area);
}
} else if (strncmp(line, "af_state ", 9) == 0) {
char st[32] = "";
double nx = 0.5, ny = 0.5;
if (sscanf(line + 9, "%31s %lf %lf", st, &nx, &ny) >= 1) {
if (strcmp(st, "idle") == 0) {
app->af_active = FALSE;
} else {
app->af_nx = fmax(0.05, fmin(0.95, nx));
app->af_ny = fmax(0.05, fmin(0.95, ny));
app->af_locked = (strcmp(st, "locked") == 0);
app->af_active = TRUE;
app->af_until_us = g_get_monotonic_time() + (app->af_locked ? 1200000LL : 4000000LL);
}
gtk_widget_queue_draw(app->view_area);
}
} else if (strncmp(line, "saved_photo ", 12) == 0) {
gchar *base = g_path_get_basename(line + 12);
gchar *msg = g_strdup_printf("Saved %s", base);
@@ -694,15 +751,41 @@ static gboolean handle_worker_line_idle(gpointer data) {
refresh_thumbnail(app);
} else if (strncmp(line, "saved_video ", 12) == 0) {
int frames = 0;
int dur_ms = 0;
const char *p = line + 12;
const char *sp = strchr(p, ' ');
if (sp) {
frames = atoi(p);
gchar *base = g_path_get_basename(sp + 1);
gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames);
show_toast(app, msg, 2.8);
g_free(base);
g_free(msg);
const char *rest = sp + 1;
const char *sp2 = strchr(rest, ' ');
gboolean has_dur = FALSE;
if (sp2 && isdigit((unsigned char)rest[0])) {
has_dur = TRUE;
for (const char *c = rest; c < sp2; c++) {
if (!isdigit((unsigned char)*c)) {
has_dur = FALSE;
break;
}
}
}
if (has_dur) {
dur_ms = atoi(rest);
gchar *base = g_path_get_basename(sp2 + 1);
double secs = dur_ms > 0 ? (dur_ms / 1000.0) : 0.0;
double fps = (secs > 0.05 && frames > 0) ? (frames / secs) : 0.0;
gchar *msg = (fps > 0.5)
? g_strdup_printf("Saved %s (%.1fs · %.0f fps)", base, secs, fps)
: g_strdup_printf("Saved %s (%d frames)", base, frames);
show_toast(app, msg, 2.8);
g_free(base);
g_free(msg);
} else {
gchar *base = g_path_get_basename(rest);
gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames);
show_toast(app, msg, 2.8);
g_free(base);
g_free(msg);
}
}
} else if (strncmp(line, "toast ", 6) == 0) {
show_toast(app, line + 6, 3.0);
@@ -723,25 +806,32 @@ static gpointer worker_reader_func(gpointer data) {
if (sscanf(line + 6, "%d %d %lu", &w, &h, &len) == 3 &&
w > 0 && h > 0 && len == (unsigned long)w * (unsigned long)h * 4UL &&
len <= 16UL * 1024UL * 1024UL) {
uint8_t *buf = (uint8_t *)malloc((size_t)len);
if (!buf) break;
if ((size_t)len > app->read_cap) {
uint8_t *nb = (uint8_t *)realloc(app->read_buf, (size_t)len);
if (!nb) break;
app->read_buf = nb;
app->read_cap = (size_t)len;
}
size_t got = 0;
while (got < (size_t)len) {
size_t n = fread(buf + got, 1, (size_t)len - got, app->from_worker);
size_t n = fread(app->read_buf + got, 1, (size_t)len - got, app->from_worker);
if (n == 0) break;
got += n;
}
if (got != (size_t)len) {
free(buf);
break;
}
g_mutex_lock(&app->frame_mutex);
free(app->frame_buf);
app->frame_buf = buf;
uint8_t *tmp_buf = app->frame_buf;
size_t tmp_cap = app->frame_cap;
app->frame_buf = app->read_buf;
app->frame_cap = app->read_cap;
app->frame_w = w;
app->frame_h = h;
app->frame_len = (size_t)len;
app->frame_seq++;
app->read_buf = tmp_buf;
app->read_cap = tmp_cap;
gboolean need_schedule = !app->draw_pending;
if (need_schedule) app->draw_pending = TRUE;
g_mutex_unlock(&app->frame_mutex);
@@ -774,6 +864,10 @@ static gboolean tick_ui(gpointer data) {
app->toast_text = NULL;
dirty = TRUE;
}
if (app->af_active && now > app->af_until_us) {
app->af_active = FALSE;
dirty = TRUE;
}
if (app->is_recording) {
int secs = (int)((now - app->rec_start_us) / 1000000LL);
if (secs < 0) secs = 0;
@@ -1100,10 +1194,38 @@ static gboolean start_worker_process(CameraApp *app) {
if (!app->to_worker || !app->from_worker) {
return FALSE;
}
setvbuf(app->from_worker, NULL, _IOFBF, 256 * 1024);
app->reader_thread = g_thread_new("cam-reader", worker_reader_func, app);
return TRUE;
}
static gboolean on_view_button_press(GtkWidget *w, GdkEventButton *ev, gpointer data) {
(void)w;
CameraApp *app = (CameraApp *)data;
if (ev->type != GDK_BUTTON_PRESS || ev->button != 1) return FALSE;
if (!app->has_af || app->view_rw <= 20.0 || app->view_rh <= 20.0) return FALSE;
if (ev->x < app->view_rx || ev->x > app->view_rx + app->view_rw ||
ev->y < app->view_ry || ev->y > app->view_ry + app->view_rh) {
return FALSE;
}
double nx = (ev->x - app->view_rx) / app->view_rw;
double ny = (ev->y - app->view_ry) / app->view_rh;
if (app->active_is_front) nx = 1.0 - nx;
nx = fmax(0.1, fmin(0.9, nx));
ny = fmax(0.1, fmin(0.9, ny));
char cmd[64];
snprintf(cmd, sizeof(cmd), "focus %.3f %.3f", nx, ny);
send_worker(app, cmd);
app->af_nx = app->active_is_front ? (1.0 - nx) : nx;
app->af_ny = ny;
app->af_locked = FALSE;
app->af_active = TRUE;
app->af_until_us = g_get_monotonic_time() + 4000000LL;
gtk_widget_queue_draw(app->view_area);
return TRUE;
}
static void build_ui(CameraApp *app) {
GtkSettings *settings = gtk_settings_get_default();
if (settings) {
@@ -1165,7 +1287,9 @@ static void build_ui(CameraApp *app) {
app->view_area = gtk_drawing_area_new();
gtk_widget_set_hexpand(app->view_area, TRUE);
gtk_widget_set_vexpand(app->view_area, TRUE);
gtk_widget_add_events(app->view_area, GDK_BUTTON_PRESS_MASK);
g_signal_connect(app->view_area, "draw", G_CALLBACK(draw_viewfinder), app);
g_signal_connect(app->view_area, "button-press-event", G_CALLBACK(on_view_button_press), app);
gtk_container_add(GTK_CONTAINER(overlay), app->view_area);
GtkWidget *top_bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);
@@ -1409,6 +1533,7 @@ int main(int argc, char **argv) {
free(app.frame_buf);
free(app.paint_buf);
free(app.read_buf);
g_free(app.worker_exe);
g_free(app.initial_camera);
g_free(app.active_label);
+24
View File
@@ -0,0 +1,24 @@
# SPDX-License-Identifier: CC0-1.0
%YAML 1.1
---
version: 1
algorithms:
- BlackLevel:
- Awb:
- Ccm:
ccms:
- ct: 3000
ccm: [ 1.38, -0.22, -0.16,
-0.28, 1.42, -0.14,
-0.03, -0.56, 1.59 ]
- ct: 4500
ccm: [ 1.40, -0.24, -0.16,
-0.24, 1.44, -0.20,
-0.03, -0.46, 1.49 ]
- ct: 6500
ccm: [ 1.44, -0.28, -0.16,
-0.21, 1.43, -0.22,
-0.05, -0.42, 1.47 ]
- Adjust:
- Agc:
...
+32
View File
@@ -0,0 +1,32 @@
# SPDX-License-Identifier: CC0-1.0
%YAML 1.1
---
version: 1
algorithms:
- BlackLevel:
- Awb:
- Ccm:
ccms:
- ct: 2890
ccm: [ 1.36754, -0.18448, -0.18306,
-0.32356, 1.44826, -0.12471,
-0.00412, -0.69936, 1.70348 ]
- ct: 3550
ccm: [ 1.42836, -0.27235, -0.15601,
-0.28751, 1.41075, -0.12325,
-0.01812, -0.54849, 1.56661 ]
- ct: 4500
ccm: [ 1.36328, -0.19569, -0.16759,
-0.25254, 1.52248, -0.26994,
-0.01575, -0.53155, 1.54729 ]
- ct: 5700
ccm: [ 1.49207, -0.37245, -0.11963,
-0.21493, 1.40005, -0.18512,
-0.03781, -0.38779, 1.42561 ]
- ct: 7900
ccm: [ 1.34849, -0.05425, -0.29424,
-0.22182, 1.77684, -0.55502,
-0.07403, -0.55336, 1.62739 ]
- Adjust:
- Agc:
...
+10
View File
@@ -0,0 +1,10 @@
# SPDX-License-Identifier: CC0-1.0
%YAML 1.1
---
version: 1
algorithms:
- BlackLevel:
- Awb:
- Adjust:
- Agc:
...
+241 -36
View File
@@ -1,10 +1,15 @@
#!/usr/bin/env python3
"""Host-side unit tests for chandra-camera frame/camera helpers (no hardware required)."""
"""Host-side unit tests for chandra-camera frame/camera/AE/AF/VFR-mux helpers (no hardware required)."""
import ctypes
import importlib.machinery
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
try:
@@ -24,6 +29,65 @@ sys.modules["chandra_camera_mod"] = cam_mod
_loader.exec_module(cam_mod)
class _FakeSubdevIO:
"""In-memory mock for _V4L2SubdevIO supporting query/get/set/close."""
def __init__(self, ctrls):
# ctrls: cid -> (mn, mx, step, df, val)
self.ctrls = {k: list(v) for k, v in ctrls.items()}
self.history = []
self.closed = False
def query(self, cid):
if cid not in self.ctrls:
raise OSError("unsupported ctrl 0x%x" % cid)
mn, mx, step, df, _ = self.ctrls[cid]
return mn, mx, step, df
def get(self, cid):
if cid not in self.ctrls:
raise OSError("unsupported ctrl 0x%x" % cid)
return self.ctrls[cid][4]
def set(self, cid, val):
if cid not in self.ctrls:
raise OSError("unsupported ctrl 0x%x" % cid)
mn, mx, _step, _df, _ = self.ctrls[cid]
v = max(mn, min(int(val), mx))
self.ctrls[cid][4] = v
self.history.append((cid, v))
return v
def close(self):
self.closed = True
def _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96):
"""Build a 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB frame preserving all 10 bits."""
stride = (w // 4) * 5
arr = np.zeros((h, stride), dtype=np.uint8)
def pack4(p0, p1, p2, p3):
b0 = (p0 >> 2) & 0xFF
b1 = (p1 >> 2) & 0xFF
b2 = (p2 >> 2) & 0xFF
b3 = (p3 >> 2) & 0xFF
b4 = (p0 & 3) | ((p1 & 3) << 2) | ((p2 & 3) << 4) | ((p3 & 3) << 6)
return b0, b1, b2, b3, b4
for y in range(h):
top = y < (h // 2)
for x_blk in range(w // 4):
if (y % 4) < 2:
c0 = top_val if top else bg_val # R
c1 = bg_val # Gr
else:
c0 = bg_val # Gb
c1 = bg_val if top else bot_val # B
arr[y, x_blk * 5:x_blk * 5 + 5] = pack4(c0, c0, c1, c1)
return arr.tobytes(), stride
class TestCameraHelpers(unittest.TestCase):
def test_sort_and_label_cameras(self):
raw = [
@@ -41,12 +105,9 @@ class TestCameraHelpers(unittest.TestCase):
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_convert_abgr8888_with_stride_and_rotations(self):
# 2x3 image with stride padding (row = 2*4 + 4 padding bytes = 12)
h, w, stride = 3, 2, 12
buf = bytearray(h * stride)
# Pixel (x=0, y=0): ABGR8888 in LE memory is [R, G, B, A] = [10, 20, 200, 255] -> BGR [200, 20, 10]
buf[0:4] = bytes([10, 20, 200, 255])
# Pixel (x=1, y=0): R=40, G=50, B=60 -> BGR [60, 50, 40]
buf[4:8] = bytes([40, 50, 60, 255])
bgr0 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=0, cv2_mod=cv2, np_mod=np)
@@ -56,24 +117,20 @@ class TestCameraHelpers(unittest.TestCase):
bgr90 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=90, cv2_mod=cv2, np_mod=np)
self.assertEqual(bgr90.shape, (2, 3, 3))
# Libcamera Rotation=90 (CCW mounting) rotates CCW: (row=0, col=0) -> (row=w-1=1, col=0)
self.assertEqual(tuple(bgr90[1, 0]), (200, 20, 10))
bgr270 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=270, cv2_mod=cv2, np_mod=np)
self.assertEqual(bgr270.shape, (2, 3, 3))
# Libcamera Rotation=270 rotates CW: (row=0, col=0) -> (row=0, col=h-1=2)
self.assertEqual(tuple(bgr270[0, 2]), (200, 20, 10))
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_convert_argb_rgb_and_cairo_bgra(self):
# ARGB8888 in LE memory is [B, G, R, A]
buf = bytes([210, 110, 30, 255, 10, 20, 30, 255])
bgr = cam_mod.convert_frame(buf, 2, 1, 8, "ARGB8888", rot=0, cv2_mod=cv2, np_mod=np)
self.assertEqual(tuple(bgr[0, 0]), (210, 110, 30))
rgb_buf = bytes([11, 22, 33, 44, 55, 66])
bgr2 = cam_mod.convert_frame(rgb_buf, 2, 1, 6, "RGB888", rot=180, cv2_mod=cv2, np_mod=np)
# Inverted horizontally+vertically and channel-flipped -> [66, 55, 44] then [33, 22, 11]
self.assertEqual(tuple(bgr2[0, 0]), (66, 55, 44))
self.assertEqual(tuple(bgr2[0, 1]), (33, 22, 11))
@@ -89,41 +146,189 @@ class TestCameraHelpers(unittest.TestCase):
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_debayer_quad_csi2p(self):
# Construct an 8x8 CSI-2 10-bit packed 4x4 Quad-Bayer SRGGB image:
# Top half (rows 0..3): strong red (R=200, G=24, B=24)
# Bottom half (rows 4..7): strong blue (R=24, G=24, B=200)
w, h, stride = 8, 8, 10
arr = np.zeros((h, stride), dtype=np.uint8)
for y in range(h):
top = y < 4
for x_blk in range(2): # 4 pixels per block, 5 bytes per block
# Row phase inside 4x4 Quad-Bayer: y%4 in {0,1} -> R,R,G,G; {2,3} -> G,G,B,B
if (y % 4) < 2:
c0 = 200 if top else 24 # R
c1 = 24 # G
else:
c0 = 24 # G
c1 = 24 if top else 200 # B
base = x_blk * 5
arr[y, base + 0] = c0
arr[y, base + 1] = c0
arr[y, base + 2] = c1
arr[y, base + 3] = c1
arr[y, base + 4] = 0
raw = arr.tobytes()
raw, stride = _make_quad_csi2p_image(w=8, h=8, top_val=800, bot_val=800, bg_val=96)
out_live = cam_mod.debayer_quad_csi2p(
raw, w, h, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np
raw, 8, 8, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np
)
out_hq = cam_mod.debayer_quad_csi2p(
raw, w, h, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np
raw, 8, 8, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np
)
self.assertEqual(out_live.shape, (4, 4, 3)) # 8x8 -> 4x4, rot=90 keeps 4x4
self.assertEqual(out_hq.shape, (4, 6, 3)) # resized to WxH = 6x4
# Top row in rot=0 should have R > B; bottom row should have B > R.
self.assertEqual(out_live.shape, (4, 4, 3))
self.assertEqual(out_hq.shape, (4, 6, 3))
self.assertGreater(float(out_hq[0, :, 2].mean()), float(out_hq[0, :, 0].mean()) + 30.0)
self.assertGreater(float(out_hq[3, :, 0].mean()), float(out_hq[3, :, 2].mean()) + 30.0)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_c_isp_vs_numpy_fallback_and_10bit_lsbs(self):
lib = cam_mod.load_isp_lib()
self.assertIsNotNone(lib, "expected compiled build/libchandra-camera-isp.so")
raw_a, stride = _make_quad_csi2p_image(w=16, h=16, top_val=803, bot_val=803, bg_val=99)
raw_b, _ = _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96)
# Verify 10-bit LSBs change raw_a vs raw_b in C 4x4 unpacking.
arr_a = np.frombuffer(raw_a, dtype=np.uint8).reshape((16, stride))
arr_b = np.frombuffer(raw_b, dtype=np.uint8).reshape((16, stride))
out_a = np.empty((4, 4, 3), dtype=np.uint16)
out_b = np.empty((4, 4, 3), dtype=np.uint16)
lib.quad_csi2p_to_bgr16_4x4(arr_a.ctypes.data, 16, 16, stride, out_a.ctypes.data)
lib.quad_csi2p_to_bgr16_4x4(arr_b.ctypes.data, 16, 16, stride, out_b.ctypes.data)
self.assertEqual(int(out_a[0, 0, 2]) - int(out_b[0, 0, 2]), 12) # 4 pixels * 3 LSB = 12
# Compare full C ISP vs NumPy fallback on both 4x4 live and 2x2 HQ paths.
c_live = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np
)
c_hq = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np
)
saved_lib, saved_tried = cam_mod._ISP_LIB, cam_mod._ISP_LIB_TRIED
try:
cam_mod._ISP_LIB = None
cam_mod._ISP_LIB_TRIED = True
np_live = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np
)
np_hq = cam_mod.debayer_quad_csi2p(
raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np
)
finally:
cam_mod._ISP_LIB = saved_lib
cam_mod._ISP_LIB_TRIED = saved_tried
self.assertEqual(c_live.shape, (4, 4, 3))
self.assertEqual(c_hq.shape, (8, 8, 3))
self.assertLessEqual(int(np.abs(c_live.astype(np.int32) - np_live.astype(np.int32)).max()), 1)
self.assertLessEqual(int(np.abs(c_hq.astype(np.int32) - np_hq.astype(np.int32)).max()), 1)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_burst_merge_bgr16(self):
lib = cam_mod.load_isp_lib()
self.assertIsNotNone(lib)
rng = np.random.default_rng(42)
h, w = 32, 32
base_clean = np.full((h, w, 3), 1000, dtype=np.int32)
frames = []
for _ in range(4):
noise = rng.normal(0.0, 25.0, size=(h, w, 3))
f = np.clip(base_clean + noise, 0, 4092).astype(np.uint16)
frames.append(np.ascontiguousarray(f))
# Inject strong motion artifact in frame 2 on top-left 8x8 block.
frames[2][:8, :8, :] = 3500
base = frames[0]
others = frames[1:]
ptrs = (ctypes.c_void_p * len(others))(*[x.ctypes.data for x in others])
out = np.empty_like(base)
lib.burst_merge_bgr16(base.ctypes.data, ptrs, len(others), out.ctypes.data, int(h * w), 120.0)
static_std_before = float(base[12:, 12:, :].std())
static_std_after = float(out[12:, 12:, :].std())
self.assertLess(static_std_after, static_std_before * 0.7)
# Moving patch from frame 2 must not ghost into merged static base.
self.assertLess(float(out[:8, :8, :].mean()), 1200.0)
def test_quad_sensor_ae_gain_priority_and_video_mode(self):
io = _FakeSubdevIO({
cam_mod.V4L2_CID_VBLANK: (56, 62029, 1, 56, 56),
cam_mod.V4L2_CID_EXPOSURE: (4, 3542, 1, 1000, 1000),
cam_mod.V4L2_CID_ANALOGUE_GAIN: (0, 480, 1, 0, 0),
cam_mod.V4L2_CID_DIGITAL_GAIN: (0, 4096, 1, 1024, 1024),
})
ae = cam_mod.QuadSensorAE("/dev/null", io=io)
# Mid-high EV (e.g. 10x base exposure): should stay at vb_min and raise analogue gain up to 16x first.
vb, exp, ag, dg = ae.plan(3542.0 * 10.0)
self.assertEqual(vb, 56)
self.assertEqual(exp, 3542)
self.assertGreater(ag, 400)
self.assertEqual(dg, 1024)
# Very low light: photo mode extends vblank up to vb_cap_photo, video mode tightens to vb_cap_video.
vb_photo, _, _, _ = ae.plan(ae.e_max)
self.assertEqual(vb_photo, ae.vb_cap_photo)
ae.cur_vblank = vb_photo
ae.ev_total = ae.e_max
ae.set_video_mode(True)
self.assertLessEqual(ae.cur_vblank, ae.vb_cap_video)
ae.close()
self.assertTrue(io.closed)
self.assertEqual(io.get(cam_mod.V4L2_CID_VBLANK), 56)
self.assertEqual(io.get(cam_mod.V4L2_CID_EXPOSURE), 1000)
self.assertEqual(io.get(cam_mod.V4L2_CID_ANALOGUE_GAIN), 0)
self.assertEqual(io.get(cam_mod.V4L2_CID_DIGITAL_GAIN), 1024)
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
def test_contrast_af_sweep_finds_sharp_peak(self):
io = _FakeSubdevIO({
cam_mod.V4L2_CID_FOCUS_ABSOLUTE: (0, 1023, 1, 0, 120),
})
af = cam_mod.ContrastAF("/dev/null", io=io)
# Build crisp high-contrast checkerboard target.
sharp_img = np.zeros((160, 160, 3), dtype=np.uint8)
for y in range(0, 160, 8):
for x in range(0, 160, 8):
if ((x // 8) + (y // 8)) % 2 == 0:
sharp_img[y:y + 8, x:x + 8] = 220
af.trigger(0.5, 0.5)
steps = 0
while af.state != "locked" and steps < 100:
dist = abs(af.cur_pos - 600)
sigma = 0.2 + dist / 90.0
if sigma > 0.6:
frame = cv2.GaussianBlur(sharp_img, (0, 0), sigma)
else:
frame = sharp_img.copy()
af.step(frame, cv2_mod=cv2, np_mod=np)
steps += 1
self.assertEqual(af.state, "locked")
self.assertLess(abs(af.best_pos - 600), 60)
af.close()
self.assertTrue(io.closed)
self.assertEqual(io.get(cam_mod.V4L2_CID_FOCUS_ABSOLUTE), 120)
@unittest.skipUnless(HAS_CV2_NUMPY and shutil.which("ffmpeg") and shutil.which("ffprobe"), "requires cv2, numpy, ffmpeg, ffprobe")
def test_matroska_i420_muxer_vfr_and_cluster_rollover(self):
w, h = 64, 48
muxer = cam_mod.MatroskaI420Muxer(w, h)
timestamps = [0, 33, 67, 100, 145, 200, 31000, 31040]
bgr = np.full((h, w, 3), 120, dtype=np.uint8)
i420 = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV_I420).tobytes()
with tempfile.TemporaryDirectory() as td:
out_mp4 = os.path.join(td, "vfr.mp4")
cmd = [
"ffmpeg", "-y", "-loglevel", "error",
"-f", "matroska", "-i", "-",
"-fps_mode", "passthrough",
"-video_track_timescale", "1000",
"-c:v", "libx264", "-preset", "superfast", "-crf", "22", "-bf", "0",
"-pix_fmt", "yuv420p",
"-movflags", "+faststart", out_mp4,
]
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
for ts in timestamps:
proc.stdin.write(muxer.encode_frame(i420, ts))
proc.stdin.close()
rc = proc.wait(timeout=15)
err = proc.stderr.read().decode("utf-8", "replace")
self.assertEqual(rc, 0, msg="ffmpeg failed: " + err)
info = json.loads(subprocess.check_output([
"ffprobe", "-v", "error", "-show_streams", "-show_frames", "-of", "json", out_mp4
], text=True))
stream = info["streams"][0]
frames = info["frames"]
self.assertEqual(stream["codec_name"], "h264")
self.assertEqual(stream["pix_fmt"], "yuv420p")
self.assertEqual(len(frames), len(timestamps))
pts_ms = [round(float(f["pts_time"]) * 1000.0) for f in frames]
self.assertAlmostEqual(pts_ms[-1], 31040.0, delta=5.0)
self.assertAlmostEqual(pts_ms[4], 145.0, delta=5.0)
if __name__ == "__main__":
unittest.main()
@@ -207,17 +207,57 @@ fn status_line(s : @net.NetStatus) -> String {
}
}
///| Display-cell width of one Unicode scalar value in `fit` (0 for emoji modifiers/tags,
/// 2 for supplementary emoji, 1 otherwise).
fn fit_cells(cp : Int) -> Int {
if cp == 0xFE0E ||
cp == 0xFE0F ||
cp == 0x200D ||
cp == 0x20E3 ||
(cp >= 0x1F3FB && cp <= 0x1F3FF) ||
(cp >= 0xE0020 && cp <= 0xE007F) {
0
} else if cp >= 0x1F000 {
2
} else {
1
}
}
///| `s` cut to fit `w` pixels at font size `fs`.
fn fit(s : String, w : Int, fs : Int) -> String {
let cw = (fs * 6 + 9) / 10
let n = if cw > 0 { w / cw } else { s.length() }
if s.length() <= n {
s
} else if n <= 1 {
""
} else {
s[:n - 1].to_string() + "…"
let chars = s.to_array()
let mut total = 0
for ch in chars {
total = total + fit_cells(ch.to_int())
}
let cw = (fs * 6 + 9) / 10
let n = if cw > 0 { w / cw } else { total }
if total <= n {
return s
}
if n <= 1 {
return ""
}
let kept : Array[Char] = []
let mut used = 0
for ch in chars {
let c = fit_cells(ch.to_int())
if used + c > n - 1 {
break
}
kept.push(ch)
used = used + c
}
while kept.length() > 0 && kept[kept.length() - 1].to_int() == 0x200D {
ignore(kept.pop())
}
let sb = StringBuilder::new()
for ch in kept {
sb.write_char(ch)
}
sb.write_char('…')
sb.to_string()
}
///|
+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)); }
+2 -2
View File
@@ -48,8 +48,8 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux
## Camera App (`chandra-camera`)
- [`camera/chandra-camera`](../camera/chandra-camera) and [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c) provide a native GTK3/Cairo Wayland camera app (no extra Python GI packages required) installed via [`session/install.py`](../session/install.py) with its desktop launcher and icon (`Camera`).
- Supports multi-sensor `libcamera` discovery and live switching (`Back · imx519`, `Front · imx371`, `Back 2 · imx376` on OnePlus 6T, with automatic V4L2 fallback on desktops), sensor orientation transform + front-camera mirror preview, Photo mode (`HD` instant / `Full` high-resolution `StillCapture`, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording H.264 MP4s via `ffmpeg` to `~/Videos/Camera`, an in-app photo gallery viewer, rear flash/torch LED control (`/sys/class/leds/white:flash`) through `org.freedesktop.login1.Session.SetBrightness`, and hardware volume-button or `Space`/`Return` shutter control.
- [`camera/chandra-camera`](../camera/chandra-camera), [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c), and [`camera/chandra-camera-isp.c`](../camera/chandra-camera-isp.c) provide a native GTK3/Cairo Wayland camera app with a C/OpenMP Quad-Bayer ISP library (`libchandra-camera-isp.so`) installed via [`session/install.py`](../session/install.py) with its desktop launcher and icon (`Camera`).
- Supports multi-sensor `libcamera` discovery and live switching (`Back · imx519`, `Front · imx371`, `Back 2 · imx376` on OnePlus 6T, with automatic V4L2 fallback on desktops), sensor orientation transform + front-camera mirror preview, `libcamera` SoftISP CCM tuning (`camera/ipa/simple/*.yaml`), VCM contrast autofocus with tap-to-focus (`lc898217xc`), Photo mode (`HD` instant / `Full` high-resolution `StillCapture` or 3-frame raw burst merge on Quad-Bayer, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording exact-PTS VFR H.264 MP4s (`MatroskaI420Muxer` + `ffmpeg`) to `~/Videos/Camera`, an in-app photo gallery viewer, rear flash/torch LED control (`/sys/class/leds/white:flash`) through `org.freedesktop.login1.Session.SetBrightness`, and hardware volume-button or `Space`/`Return` shutter control.
## Remote Control Over Tailscale (`chandra-remote`)
+74 -17
View File
@@ -42,9 +42,6 @@ fn nat(s : String, dflt : Int) -> Int {
///| Space kept free around the grid, in pixels.
let margin : Int = 20
///| A drag starts once the pointer has moved this far from the press.
let drag_threshold : Int = 5
///| What the module asks of the host after an event.
#derive(Eq, Debug)
pub(all) enum Action {
@@ -58,6 +55,9 @@ pub(all) struct Desk {
mut size : String
/// Where icons were put: app id -> (column, row).
places : Map[String, (Int, Int)]
/// First-seen order of shown app ids, so recents reordering never shuffles unplaced icons.
seen : Map[String, Int]
mut next_seen : Int
mut w : Int
mut h : Int
/// Kept free at the bottom (the panel).
@@ -82,6 +82,8 @@ pub fn Desk::new() -> Desk {
count: "12",
size: "Medium",
places: {},
seen: {},
next_seen: 0,
w: 0,
h: 0,
bottom: 40,
@@ -106,6 +108,13 @@ pub fn Desk::cell(self : Desk) -> (Int, Int, Int) {
}
}
///| A drag starts once the pointer has moved this far from the press.
fn Desk::drag_threshold(self : Desk) -> Int {
let (cw, _, _) = self.cell()
let t = cw / 3
if t < 24 { 24 } else { t }
}
///| Columns and rows that fit on the desktop (at least one of each).
pub fn Desk::grid(self : Desk) -> (Int, Int) {
let (cw, ch, _) = self.cell()
@@ -129,9 +138,15 @@ pub fn Desk::shown(self : Desk, apps : Array[@types.AppEntry]) -> Array[@types.A
}
///| Each shown app's cell, in `shown` order: its saved place when that is on the grid and free,
/// else the first free cell, a column at a time. (-1, -1) when the grid is full.
/// else the first free cell, a column at a time, in first-seen order. (-1, -1) when full.
pub fn Desk::layout(self : Desk, apps : Array[@types.AppEntry]) -> Array[(Int, Int)] {
let shown = self.shown(apps)
for a in shown {
if !self.seen.contains(a.id) {
self.seen.set(a.id, self.next_seen)
self.next_seen = self.next_seen + 1
}
}
let (cols, rows) = self.grid()
let taken : Map[(Int, Int), Bool] = {}
let out : Array[(Int, Int)] = Array::make(shown.length(), (-1, -1))
@@ -144,11 +159,19 @@ pub fn Desk::layout(self : Desk, apps : Array[@types.AppEntry]) -> Array[(Int, I
_ => ()
}
}
let mut next = 0
let unplaced : Array[Int] = []
for i = 0; i < shown.length(); i = i + 1 {
if out[i] != (-1, -1) {
continue
if out[i] == (-1, -1) {
unplaced.push(i)
}
}
unplaced.sort_by(fn(a, b) {
let sa = self.seen.get(shown[a].id).unwrap_or(a)
let sb = self.seen.get(shown[b].id).unwrap_or(b)
if sa != sb { sa - sb } else { a - b }
})
let mut next = 0
for i in unplaced {
while next < cols * rows && taken.contains((next / rows, next % rows)) {
next = next + 1
}
@@ -192,6 +215,20 @@ pub fn Desk::app_at(self : Desk, apps : Array[@types.AppEntry], x : Int, y : Int
""
}
///| Pin every unplaced shown icon at its current grid cell without overwriting existing places.
fn Desk::pin_unplaced(self : Desk, apps : Array[@types.AppEntry]) -> Unit {
if self.w <= 0 || self.h <= 0 {
return
}
let shown = self.shown(apps)
let cells = self.layout(apps)
for i, a in shown {
if cells[i] != (-1, -1) && !self.places.contains(a.id) {
self.places.set(a.id, cells[i])
}
}
}
///| Remember every shown icon where it is now, then put `id` at `to`, swapping with the icon
/// there (which takes `id`'s old cell).
fn Desk::move_to(self : Desk, apps : Array[@types.AppEntry], id : String, to : (Int, Int)) -> Unit {
@@ -199,13 +236,18 @@ fn Desk::move_to(self : Desk, apps : Array[@types.AppEntry], id : String, to : (
let cells = self.layout(apps)
let mut from = (-1, -1)
for i, a in shown {
if cells[i] != (-1, -1) {
self.places.set(a.id, cells[i])
}
if a.id == id {
from = cells[i]
}
}
if from == (-1, -1) || from == to {
return
}
for i, a in shown {
if cells[i] != (-1, -1) {
self.places.set(a.id, cells[i])
}
}
for i, a in shown {
if a.id != id && cells[i] == to {
self.places.set(a.id, from)
@@ -315,9 +357,13 @@ pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.Inpu
PointerMove(p) => {
self.ptr_x = p.x
self.ptr_y = p.y
if self.press_id != "" && !self.dragging &&
((p.x - self.press_x).abs() > drag_threshold || (p.y - self.press_y).abs() > drag_threshold) {
self.dragging = true
if self.press_id != "" && !self.dragging {
let dx = p.x - self.press_x
let dy = p.y - self.press_y
let t = self.drag_threshold()
if dx * dx + dy * dy > t * t {
self.dragging = true
}
}
if self.dragging {
return (true, NoAction)
@@ -355,10 +401,16 @@ pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.Inpu
self.move_to(apps, id, self.cell_at(p.x, p.y))
self.hover = self.app_at(apps, p.x, p.y)
(true, NoAction)
} else if self.app_at(apps, p.x, p.y) == id {
(true, Launch(id))
} else {
(true, NoAction)
let dx = p.x - self.press_x
let dy = p.y - self.press_y
let t = self.drag_threshold()
if self.app_at(apps, p.x, p.y) == id || dx * dx + dy * dy <= t * t {
self.pin_unplaced(apps)
(true, Launch(id))
} else {
(true, NoAction)
}
}
}
FocusLost => {
@@ -375,7 +427,12 @@ pub fn Desk::handle(self : Desk, apps : Array[@types.AppEntry], ev : @types.Inpu
"ArrowUp" | "Up" => self.step_selection(apps, 0, -1)
"ArrowDown" | "Down" => self.step_selection(apps, 0, 1)
"Enter" | " " =>
return (false, if self.selected != "" { Launch(self.selected) } else { NoAction })
if self.selected != "" {
self.pin_unplaced(apps)
return (false, Launch(self.selected))
} else {
return (false, NoAction)
}
"Escape" => self.selected = ""
_ => if k.length() == 1 { ignore(self.jump_to(apps, k)) } else { return (false, NoAction) }
}
+83
View File
@@ -85,3 +85,86 @@ test "keyboard moves the selection and launches" {
ignore(d.handle(a, FocusLost))
assert_false(d.focused)
}
///|
test "tapping with finger-roll drift launches without dragging or moving icons" {
let d = desk()
let a = apps(12)
let before = d.layout(a)
// 20 px drift inside cell (0,0): stays below the 32 px medium-cell drag threshold.
ignore(d.handle(a, PointerDown({ x: 60, y: 60 })))
ignore(d.handle(a, PointerMove({ x: 80, y: 64 })))
assert_false(d.dragging)
assert_eq(d.handle(a, PointerUp({ x: 80, y: 64 })), (true, Launch("app0")))
assert_eq(d.layout(a), before)
// 15 px drift starting near the right edge of cell (0,0) and crossing into cell (1,0) still
// launches app0 without moving any icon.
ignore(d.handle(a, PointerDown({ x: 110, y: 60 })))
ignore(d.handle(a, PointerMove({ x: 125, y: 60 })))
assert_false(d.dragging)
assert_eq(d.handle(a, PointerUp({ x: 125, y: 60 })), (true, Launch("app0")))
assert_eq(d.layout(a), before)
}
///|
test "launching and reordering apps by recency keeps every icon in its cell" {
let a = apps(12)
// Simulate an app launched from elsewhere (places empty): first-seen order keeps cells stable.
let d_unpinned = desk()
let expected_by_id : Map[String, (Int, Int)] = {}
let initial = d_unpinned.layout(a)
for i, app in a {
expected_by_id.set(app.id, initial[i])
}
let reordered = [a[0], a[1], a[2], a[3], a[4], a[7], a[5], a[6], a[8], a[9], a[10], a[11]]
let after_unpinned = d_unpinned.layout(reordered)
for i, app in reordered {
assert_eq(after_unpinned[i], expected_by_id.get(app.id).unwrap())
}
// Launching app7 on the desktop pins existing cells and keeps stability across recents reorder,
// off-grid rotation/resize fallback, and reload into a fresh Desk.
let d = desk()
ignore(d.layout(a))
// app7 is at cell (1, 2): x = 20 + 96 + 40 = 156, y = 20 + 2 * 96 + 40 = 252.
ignore(d.handle(a, PointerDown({ x: 156, y: 252 })))
assert_eq(d.handle(a, PointerUp({ x: 156, y: 252 })), (true, Launch("app7")))
let after_launch = d.layout(reordered)
for i, app in reordered {
assert_eq(after_launch[i], expected_by_id.get(app.id).unwrap())
}
// Portrait resize where column >= 1 falls off-grid: off-grid apps fall back in seen order,
// not recents order (app5 before app6 before app7).
d.w = 220
d.h = 1200
let portrait = d.layout(reordered)
let p_by_id : Map[String, (Int, Int)] = {}
for i, app in reordered {
p_by_id.set(app.id, portrait[i])
}
assert_true(p_by_id.get("app5").unwrap().1 < p_by_id.get("app6").unwrap().1)
assert_true(p_by_id.get("app6").unwrap().1 < p_by_id.get("app7").unwrap().1)
// Saved places round-trip into a fresh Desk with the reordered catalog.
let saved = d.config_items().filter(c => c.key == "places")[0]
let d2 = desk()
ignore(d2.set_config("places", saved.value))
let reloaded = d2.layout(reordered)
for i, app in reordered {
assert_eq(reloaded[i], expected_by_id.get(app.id).unwrap())
}
}
///|
test "dragging past threshold and dropping on the same cell cancels cleanly" {
let d = desk()
let a = apps(12)
let before = d.layout(a)
let places_val = fn(x : @icondesk.Desk) { x.config_items().filter(c => c.key == "places")[0].value }
assert_eq(places_val(d), "")
// Move 45 px (> 32 px threshold) while staying inside cell (0,0) (20..116).
ignore(d.handle(a, PointerDown({ x: 60, y: 60 })))
ignore(d.handle(a, PointerMove({ x: 105, y: 60 })))
assert_true(d.dragging)
assert_eq(d.handle(a, PointerUp({ x: 105, y: 60 })), (true, NoAction))
assert_eq(d.layout(a), before)
assert_eq(places_val(d), "")
}
+8 -6
View File
@@ -389,13 +389,14 @@
mode: 'one',
sx: e.clientX, sy: e.clientY,
lx: e.clientX, ly: e.clientY,
sfx: fx, sfy: fy,
fx, fy, moved: false, dragging: false, longFired: false,
longTimer: setTimeout(() => {
if (!gesture || gesture.mode !== 'one' || gesture.moved) return;
gesture.longFired = true;
if (navigator.vibrate) navigator.vibrate(25);
const rx = trackpadMode ? cursorX : gesture.fx;
const ry = trackpadMode ? cursorY : gesture.fy;
const rx = trackpadMode ? cursorX : gesture.sfx;
const ry = trackpadMode ? cursorY : gesture.sfy;
sendJson({ t: 'tap', x: rx, y: ry, b: 3 });
}, 450)
};
@@ -435,13 +436,14 @@
}
const [fx, fy] = clientToFb(e.clientX, e.clientY);
gesture.fx = fx; gesture.fy = fy;
if (!gesture.moved && dist > 10) {
if (!gesture.moved && dist > 14) {
gesture.moved = true;
clearLongTimer();
if (!gesture.longFired) {
gesture.dragging = true;
sendJson({ t: 'ptr', x: fx, y: fy });
sendJson({ t: 'ptr', x: gesture.sfx, y: gesture.sfy });
sendJson({ t: 'btn', b: 1, d: 1 });
sendJson({ t: 'ptr', x: fx, y: fy });
}
} else if (gesture.dragging) {
const now = performance.now();
@@ -477,8 +479,8 @@
sendJson({ t: 'ptr', x: fx, y: fy });
sendJson({ t: 'btn', b: 1, d: 0 });
} else if (!gesture.moved && !gesture.longFired) {
const tx = trackpadMode ? cursorX : gesture.fx;
const ty = trackpadMode ? cursorY : gesture.fy;
const tx = trackpadMode ? cursorX : gesture.sfx;
const ty = trackpadMode ? cursorY : gesture.sfy;
sendJson({ t: 'tap', x: tx, y: ty, b: 1 });
}
gesture = null;
+25
View File
@@ -75,6 +75,7 @@ targets = [
"/usr/local/bin/chandra-kde-colors",
"/usr/local/bin/chandra-camera",
"/usr/local/lib/chandra/chandra-camera-ui",
"/usr/local/lib/chandra/libchandra-camera-isp.so",
"/usr/share/applications/chandra-camera.desktop",
"/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg",
"/usr/local/bin/chandra-remote",
@@ -200,6 +201,30 @@ subprocess.check_call([cc, "-O2", "-Wall", "-Wextra", "-o", cam_ui_dst + ".new",
os.chmod(cam_ui_dst + ".new", 0o755)
os.replace(cam_ui_dst + ".new", cam_ui_dst)
print("installed", cam_ui_dst)
cam_isp_src = os.path.join(root, "camera/chandra-camera-isp.c")
cam_isp_dst = "/usr/local/lib/chandra/libchandra-camera-isp.so"
if os.path.exists(cam_isp_src):
rc = subprocess.call([
cc, "-O3", "-fopenmp", "-shared", "-fPIC", "-Wall", "-Wextra",
"-o", cam_isp_dst + ".new", cam_isp_src, "-lm",
])
if rc != 0:
subprocess.check_call([
cc, "-O3", "-shared", "-fPIC", "-Wall", "-Wextra",
"-o", cam_isp_dst + ".new", cam_isp_src, "-lm",
])
os.chmod(cam_isp_dst + ".new", 0o755)
os.replace(cam_isp_dst + ".new", cam_isp_dst)
print("installed", cam_isp_dst)
cam_ipa_src = os.path.join(root, "camera/ipa/simple")
cam_ipa_dst = os.path.join(share, "ipa", "simple")
if os.path.isdir(cam_ipa_src):
os.makedirs(cam_ipa_dst, exist_ok=True)
os.chmod(os.path.join(share, "ipa"), 0o755)
os.chmod(cam_ipa_dst, 0o755)
for fn in sorted(os.listdir(cam_ipa_src)):
if fn.endswith(".yaml"):
put(os.path.join(cam_ipa_src, fn), os.path.join(cam_ipa_dst, fn), 0o644)
put(os.path.join(root, "camera/chandra-camera.desktop"), "/usr/share/applications/chandra-camera.desktop", 0o644)
put(os.path.join(root, "camera/chandra-camera.svg"), "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", 0o644)
remote_srcs = [
+59 -13
View File
@@ -85,6 +85,9 @@ fn font_load(slot : Int, path : String) -> Bool {
///|
extern "C" fn rs_font_has(slot : Int) -> Int = "rs_font_has"
///|
extern "C" fn rs_font_has_glyph(slot : Int, cp : Int) -> Int = "rs_font_has_glyph"
///|
#borrow(info)
extern "C" fn rs_glyph_info(
@@ -361,6 +364,12 @@ fn advance(slot : Int, cp : Int, size : Int) -> Int {
glyph_info[4]
}
///|
priv enum WasmTextPiece {
WasmGlyph(Int)
WasmEmoji(String)
}
///|
fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit {
let text = l.field("text").to_string()
@@ -376,13 +385,40 @@ fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit {
Some(f) => f
None => return // no face loaded: nothing to draw with
}
let (cap_slot, _) = match pick_face(false, mono) {
Some(f) => f
None => return
}
let extra = if embolden { 1 } else { 0 }
let cps : Array[Int] = []
let epx = @renderer.inline_emoji_px(size)
let pieces : Array[WasmTextPiece] = []
let mut total_w = 0
for ch in text {
let cp = ch.to_int()
cps.push(cp)
total_w += advance(slot, cp, size) + extra
if !@emoji.text_may_have_emoji(text) {
for ch in text {
let cp = ch.to_int()
pieces.push(WasmGlyph(cp))
total_w += advance(slot, cp, size) + extra
}
} else {
let chars = text.to_array()
let mut i = 0
while i < chars.length() {
match emoji_source.match_at(chars, i, cp => rs_font_has_glyph(slot, cp) != 0) {
Some((next, seq)) => {
pieces.push(WasmEmoji(seq))
total_w += epx
i = next
}
None => {
let cp = chars[i].to_int()
if !@emoji.is_ignorable_emoji_mod(cp) {
pieces.push(WasmGlyph(cp))
total_w += advance(slot, cp, size) + extra
}
i = i + 1
}
}
}
}
let x = l.field("x").to_int() + ox
let start_x = match l.field("align").to_int() {
@@ -391,19 +427,29 @@ fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit {
_ => x
}
// `y` is the vertical centre of the text; centre the capital height ('H') on it.
let (cap_slot, _) = match pick_face(false, mono) {
Some(f) => f
None => return
}
rs_glyph_info(cap_slot, 72, size, glyph_info)
let baseline = l.field("y").to_int() + oy + -glyph_info[3] / 2
let cy = l.field("y").to_int() + oy
let baseline = cy + -glyph_info[3] / 2
let r = col.field("r").to_int()
let g = col.field("g").to_int()
let b = col.field("b").to_int()
let mut pen = start_x
for cp in cps {
rs_draw_glyph(slot, cp, size, pen, baseline, r, g, b, ca, extra)
pen += advance(slot, cp, size) + extra
for piece in pieces {
match piece {
WasmGlyph(cp) => {
rs_draw_glyph(slot, cp, size, pen, baseline, r, g, b, ca, extra)
pen += advance(slot, cp, size) + extra
}
WasmEmoji(seq) => {
if epx > 0 {
let h = emoji_image(seq, epx)
if h != 0U {
rs_draw_image(h.reinterpret_as_int(), pen, cy - epx / 2, epx, epx)
}
}
pen += epx
}
}
}
}
+6
View File
@@ -33,6 +33,7 @@
int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes);
void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info);
void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf);
int32_t mp_font_has_glyph(int32_t slot, int32_t cp);
/* ------------------------------------------------------------------ canvas */
@@ -315,6 +316,11 @@ void rs_font_loaded(int32_t slot) {
int32_t rs_font_has(int32_t slot) { return slot >= 0 && slot < 4 && font_loaded[slot]; }
int32_t rs_font_has_glyph(int32_t slot, int32_t cp) {
if (slot < 0 || slot >= 4 || !font_loaded[slot]) return 0;
return mp_font_has_glyph(slot, cp);
}
/* Metrics into info: width, height, xoff, yoff, advance. */
void rs_glyph_info(int32_t slot, int32_t cp, int32_t size, int32_t *info) {
Glyph *g = glyph(slot, cp, size);