use super::option_wheel_sound::TickPlayer;
use arc_motion::{ExponentialSmoother, is_reduced_motion, motion_now};
use arc_tokens::ActiveArcTheme as _;
use gpui_kit::{
App, ElementId, Entity, FocusHandle, FontWeight, Hsla, IntoElement, MouseButton,
MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, RenderOnce, Role, SharedString,
Styled, TestSupportExt as _, TextRun, TransformationMatrix, Window, bounds, canvas, div, point,
prelude::*, px, size,
};
use std::{
collections::{HashMap, HashSet},
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OptionWheelSide {
#[default]
Left,
Right,
}
#[derive(Clone, Debug)]
pub struct OptionWheelConfig {
pub default_selected: usize,
pub text_color: Option<Hsla>,
pub active_color: Option<Hsla>,
pub side: OptionWheelSide,
pub font_size: f32,
pub spacing: f32,
pub curve: f32,
pub tilt: f32,
pub blur: f32,
pub fade: f32,
pub min_opacity: f32,
pub smoothing: f32,
pub inset: f32,
pub looping: bool,
pub draggable: bool,
pub sound_url: SharedString,
pub sound_volume: f32,
pub height: f32,
}
impl Default for OptionWheelConfig {
fn default() -> Self {
Self {
default_selected: 3,
text_color: None,
active_color: None,
side: OptionWheelSide::Left,
font_size: 3.0,
spacing: 1.4,
curve: 1.0,
tilt: 6.0,
blur: 2.0,
fade: 0.25,
min_opacity: 0.05,
smoothing: 200.0,
inset: 80.0,
looping: false,
draggable: true,
sound_url: "".into(),
sound_volume: 0.5,
height: 420.0,
}
}
}
fn finite(v: f32, default: f32, lo: f32, hi: f32) -> f32 {
if v.is_finite() {
v.clamp(lo, hi)
} else {
default
}
}
impl OptionWheelConfig {
fn normalized(mut self) -> Self {
self.font_size = finite(self.font_size, 3.0, 0.5, 12.0);
self.spacing = finite(self.spacing, 1.4, 0.5, 4.0);
self.curve = finite(self.curve, 1.0, 0.0, 4.0);
self.tilt = finite(self.tilt, 6.0, 0.0, 45.0);
self.blur = finite(self.blur, 2.0, 0.0, 16.0);
self.fade = finite(self.fade, 0.25, 0.0, 1.0);
self.min_opacity = finite(self.min_opacity, 0.05, 0.0, 1.0);
self.smoothing = finite(self.smoothing, 200.0, 1.0, 3000.0);
self.inset = finite(self.inset, 80.0, 0.0, 1200.0);
self.sound_volume = finite(self.sound_volume, 0.5, 0.0, 1.0);
self.height = finite(self.height, 420.0, 80.0, 1600.0);
self
}
}
#[derive(Clone, Debug)]
pub struct OptionWheelChange {
pub index: usize,
pub item: SharedString,
}
type Change = Rc<dyn Fn(&OptionWheelChange, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct OptionWheel {
id: ElementId,
items: Vec<SharedString>,
config: OptionWheelConfig,
on_change: Option<Change>,
label: SharedString,
#[cfg(test)]
probe: Option<Rc<std::cell::RefCell<Option<Entity<State>>>>>,
}
impl OptionWheel {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: default_items(),
config: Default::default(),
on_change: None,
label: "Option wheel".into(),
#[cfg(test)]
probe: None,
}
}
pub fn items(mut self, items: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.items = items.into_iter().map(Into::into).collect();
self
}
pub fn config(mut self, config: OptionWheelConfig) -> Self {
self.config = config;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn on_change(
mut self,
callback: impl Fn(&OptionWheelChange, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(callback));
self
}
}
pub fn default_items() -> Vec<SharedString> {
[
"Ambient",
"House",
"Techno",
"Jazz",
"Lo-Fi",
"Synthwave",
"Trance",
"Funk",
"Disco",
"Hip-Hop",
"Chillwave",
"Drum & Bass",
]
.into_iter()
.map(Into::into)
.collect()
}
fn selected(value: f64, count: usize) -> usize {
if count == 0 {
0
} else {
js_round(value).rem_euclid(count as f64) as usize
}
}
fn js_round(value: f64) -> f64 {
(value + 0.5).floor()
}
fn target(value: f64, count: usize, looping: bool, snap: bool) -> f64 {
let value = if value.is_finite() { value } else { 0.0 };
let value = if looping && count > 1 {
value
} else {
value.clamp(0.0, count.saturating_sub(1) as f64)
};
if snap { js_round(value) } else { value }
}
fn distance(index: usize, pos: f64, count: usize, looping: bool) -> f32 {
let mut d = index as f64 - pos;
if looping && count > 1 {
d = d.rem_euclid(count as f64);
if d > count as f64 / 2.0 {
d -= count as f64;
}
}
d as f32
}
#[derive(Clone, Copy, Debug)]
struct Pose {
x: f32,
y: f32,
angle: f32,
opacity: f32,
blend: f32,
blur: f32,
}
fn pose(d: f32, row: f32, c: &OptionWheelConfig) -> Pose {
let mirror = if c.side == OptionWheelSide::Right {
-1.0
} else {
1.0
};
let tilt = c.tilt.to_radians();
let (x, y, angle) = if tilt > 0.0005 {
let radius = row / tilt;
let angle = (d * tilt).clamp(-std::f32::consts::FRAC_PI_2, std::f32::consts::FRAC_PI_2);
(
-mirror * radius * (1.0 - angle.cos()) * c.curve,
radius * angle.sin(),
mirror * angle,
)
} else {
(0.0, d * row, 0.0)
};
Pose {
x,
y,
angle,
opacity: (1.0 - d.abs() * c.fade).max(c.min_opacity),
blend: (1.0 - d.abs()).clamp(0.0, 1.0),
blur: (d.abs() * c.blur).min(32.0),
}
}
struct Hit {
index: usize,
anchor: Point<Pixels>,
width: f32,
font: f32,
angle: f32,
right: bool,
}
impl Hit {
fn contains(&self, p: Point<Pixels>) -> bool {
let x = (p.x - self.anchor.x).as_f32();
let y = (p.y - self.anchor.y).as_f32();
let u = x * self.angle.cos() + y * self.angle.sin();
let v = -x * self.angle.sin() + y * self.angle.cos();
let u = if self.right { -u } else { u };
u >= 0.0 && u <= self.width && v.abs() <= self.font * 0.5
}
}
type LabelKey = (SharedString, SharedString, u32, bool);
type RasterKey = LabelKey;
type RasterEntry = Arc<Vec<arc_motion::alpha_mask::MaskLayer>>;
#[cfg(debug_assertions)]
struct WheelPerf {
cold_start: Instant,
warm_start: Option<Instant>,
last_frame: Option<Instant>,
intervals_ms: Vec<f64>,
paint_ms: Vec<f64>,
finished: bool,
}
#[cfg(debug_assertions)]
impl WheelPerf {
fn new() -> Self {
Self {
cold_start: Instant::now(),
warm_start: None,
last_frame: None,
intervals_ms: Vec::new(),
paint_ms: Vec::new(),
finished: false,
}
}
fn sample(&mut self, ready: bool, count: usize) -> Option<f64> {
if self.finished || !ready || count < 2 {
return None;
}
let now = Instant::now();
let start = *self.warm_start.get_or_insert_with(|| {
eprintln!(
"OptionWheel native diagnostic cold_prepare_ms={:.2}",
self.cold_start.elapsed().as_secs_f64() * 1000.0
);
now
});
if let Some(last) = self.last_frame.replace(now) {
self.intervals_ms
.push(now.duration_since(last).as_secs_f64() * 1000.0);
}
let elapsed = now.duration_since(start).as_secs_f64();
if elapsed >= 10.0 {
self.finished = true;
self.intervals_ms.sort_by(f64::total_cmp);
self.paint_ms.sort_by(f64::total_cmp);
let percentile = |data: &[f64], p: f64| {
data.get(((data.len().saturating_sub(1) as f64) * p).round() as usize)
.copied()
.unwrap_or(0.0)
};
eprintln!(
"OptionWheel native diagnostic frames={} seconds={elapsed:.2} render_interval_ms_p50={:.3} p95={:.3} p99={:.3} max={:.3} canvas_cpu_ms_p95={:.3}; NOT_GPU_PRESENT_FPS",
self.intervals_ms.len(),
percentile(&self.intervals_ms, 0.5),
percentile(&self.intervals_ms, 0.95),
percentile(&self.intervals_ms, 0.99),
percentile(&self.intervals_ms, 1.0),
percentile(&self.paint_ms, 0.95)
);
None
} else {
Some((count - 1) as f64 * (0.5 + 0.45 * (elapsed * std::f64::consts::PI).sin()))
}
}
}
struct State {
focus: FocusHandle,
config: OptionWheelConfig,
items: Vec<SharedString>,
callback: Option<Change>,
target: f64,
motion: ExponentialSmoother,
index: usize,
row: f32,
drag: Option<(f32, f64)>,
moved: bool,
wheel_revision: u64,
hits: Vec<Hit>,
dimensions: HashMap<LabelKey, f32>,
masks: HashMap<RasterKey, RasterEntry>,
shapes: HashMap<LabelKey, gpui_kit::ShapedLine>,
pending: HashSet<RasterKey>,
failed: HashSet<RasterKey>,
raster_busy: bool,
raster_generation: u64,
raster_font: Option<(SharedString, u32, u32)>,
release_hook: bool,
#[cfg(debug_assertions)]
perf: Option<WheelPerf>,
sound_source: SharedString,
sound_bytes: Option<Arc<[u8]>>,
sound_ready: bool,
player: Option<TickPlayer>,
last_tick: Option<Instant>,
}
fn apply(state: &Entity<State>, value: f64, snap: bool, window: &mut Window, cx: &mut App) {
let now = motion_now(cx);
let event = state.update(cx, |s, _| {
if s.items.is_empty() {
return None;
}
let value = target(value, s.items.len(), s.config.looping, snap);
s.target = value;
if !snap && s.drag.is_some() && s.moved {
s.motion = ExponentialSmoother::new(value, now);
}
let index = selected(value, s.items.len());
if index == s.index {
return None;
}
s.index = index;
let tick = !s.config.sound_url.is_empty()
&& s.last_tick
.is_none_or(|t| t.elapsed() >= Duration::from_millis(70));
if tick && s.sound_ready {
s.last_tick = Some(Instant::now());
if s.player.is_none() {
s.player = TickPlayer::new();
}
if let Some(player) = &s.player {
player.play(s.sound_bytes.clone(), s.config.sound_volume);
}
}
Some((
OptionWheelChange {
index,
item: s.items[index].clone(),
},
s.callback.clone(),
))
});
if let Some((event, Some(callback))) = event {
callback(&event, window, cx);
}
window.refresh();
}
fn prepare_sound(state: &Entity<State>, window: &mut Window, cx: &mut App) {
let url = state.read(cx).config.sound_url.clone();
if state.read(cx).sound_source == url {
return;
}
state.update(cx, |s, _| {
s.sound_source = url.clone();
s.sound_bytes = None;
s.sound_ready = url == "builtin:soft";
s.last_tick = None;
s.player = None;
});
if url.is_empty() || url == "builtin:soft" {
return;
}
let client = cx.http_client();
let assets = cx.asset_source().clone();
let weak = state.downgrade();
window
.spawn(cx, async move |cx| {
let source = url.clone();
let result = cx
.background_executor()
.spawn(async move {
const LIMIT: u64 = 4 * 1024 * 1024;
if source.starts_with("https://") || source.starts_with("http://") {
use futures_lite::AsyncReadExt;
let mut response =
client.get(source.as_ref(), ().into(), true).await.ok()?;
if !response.status().is_success() {
return None;
}
let mut bytes = Vec::new();
response
.body_mut()
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.await
.ok()?;
if bytes.len() as u64 > LIMIT {
return None;
}
Some(Arc::<[u8]>::from(bytes))
} else {
if let Ok(Some(bytes)) = assets.load(&source) {
return (bytes.len() as u64 <= LIMIT)
.then(|| Arc::<[u8]>::from(bytes.to_vec()));
}
let path = std::path::Path::new(source.as_ref());
if std::fs::metadata(path).ok()?.len() > LIMIT {
return None;
}
let bytes = std::fs::read(path).ok()?;
(bytes.len() as u64 <= LIMIT).then(|| Arc::<[u8]>::from(bytes))
}
})
.await;
let _ = cx.update(|_, cx| {
let Some(st) = weak.upgrade() else {
return;
};
st.update(cx, |s, _| {
if s.sound_source == url {
s.sound_ready = result.is_some();
s.sound_bytes = result;
}
});
});
})
.detach();
}
#[cfg(test)]
use std::hash::{Hash, Hasher};
#[cfg(test)]
fn xml(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
#[cfg(test)]
fn text_svg(
label: &str,
family: &str,
font: f32,
width: f32,
bold: bool,
blur: f32,
) -> (SharedString, Arc<[u8]>, f32) {
let blur = (blur * 2.0).round() * 0.5;
let pad = (blur * 3.0 + 2.0).ceil();
let h = font * 1.8;
let w = width.max(1.0) + pad * 2.0;
let height = h + pad * 2.0;
let baseline = pad + font * 1.2;
let weight = if bold { 500 } else { 200 };
let filter = if blur > 0.0 {
r#"filter="url(#b)""#.to_string()
} else {
String::new()
};
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{height}" viewBox="0 0 {w} {height}"><defs><filter id="b" x="-100%" y="-100%" width="300%" height="300%"><feGaussianBlur stdDeviation="{blur}"/></filter></defs><text x="{pad}" y="{baseline}" font-family="{}" font-size="{font}" font-weight="{weight}" fill="white" {filter}>{}</text></svg>"#,
xml(family),
xml(label)
);
let mut hasher = std::collections::hash_map::DefaultHasher::new();
svg.hash(&mut hasher);
(
format!("arc-option-text-{:016x}", hasher.finish()).into(),
Arc::from(svg.into_bytes()),
pad,
)
}
#[cfg(test)]
fn label_paths(label: &str, family: &str, font: f32, width: f32, bold: bool) -> String {
let families = format!("{family}, Segoe UI, Helvetica Neue, DejaVu Sans, sans-serif");
let (_, data, _) = text_svg(label, &families, font, width, bold, 0.0);
let converted = crate::text::glyph_outline::svg_font_database()
.ok()
.and_then(|fontdb| {
let options = usvg::Options {
fontdb,
..Default::default()
};
usvg::Tree::from_data(&data, &options)
.ok()
.map(|tree| tree.to_string(&usvg::WriteOptions::default()))
});
let svg = converted.unwrap_or_else(|| String::from_utf8_lossy(&data).into_owned());
let start = svg
.find("<svg")
.and_then(|i| svg[i..].find('>').map(|j| i + j + 1))
.unwrap_or(0);
let end = svg.rfind("</svg>").unwrap_or(svg.len());
svg[start..end].to_string()
}
#[cfg(test)]
fn blurred_paths(paths: &str, font: f32, width: f32, blur: f32) -> (SharedString, Arc<[u8]>, f32) {
let pad = (blur * 3.0 + 2.0).ceil();
let w = width.max(1.0) + pad * 2.0;
let h = font * 1.8 + pad * 2.0;
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}"><defs><filter id="blur" filterUnits="userSpaceOnUse" x="0" y="0" width="{w}" height="{h}"><feGaussianBlur stdDeviation="{blur}"/></filter></defs><g filter="url(#blur)"><g transform="translate({offset} {offset})">{paths}</g></g></svg>"#,
offset = pad - 2.0
);
let mut hasher = std::collections::hash_map::DefaultHasher::new();
svg.hash(&mut hasher);
(
format!("arc-option-path-{:016x}", hasher.finish()).into(),
Arc::from(svg.into_bytes()),
pad,
)
}
fn queue_raster(state: &Entity<State>, key: RasterKey, window: &mut Window, cx: &mut App) {
if state.read(cx).raster_busy
|| state.read(cx).pending.contains(&key)
|| state.read(cx).failed.contains(&key)
{
return;
}
let Some(line) = state.read(cx).shapes.get(&key).cloned() else {
return;
};
let font = f32::from_bits(key.2);
let generation = state.read(cx).raster_generation;
state.update(cx, |s, _| {
s.raster_busy = true;
s.pending.insert(key.clone());
});
let system = cx.text_system().clone();
let scale = window.scale_factor().max(1.0) * 2.0;
let weak = state.downgrade();
window
.spawn(cx, async move |cx| {
let result = cx
.background_executor()
.spawn(async move {
arc_motion::alpha_mask::native_mask_pyramid(
&system,
&line,
px(font * 1.8),
scale,
)
.map(Arc::new)
})
.await;
let _ = cx.update(|window, cx| {
if let Some(state) = weak.upgrade() {
state.update(cx, |s, _| {
s.raster_busy = false;
if generation == s.raster_generation {
s.pending.remove(&key);
if let Ok(entry) = result {
s.masks.insert(key, entry);
} else {
s.failed.insert(key);
}
}
});
window.refresh();
}
});
})
.detach();
}
fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla {
let a = a.to_rgb();
let b = b.to_rgb();
gpui_kit::Rgba {
r: a.r + (b.r - a.r) * t,
g: a.g + (b.g - a.g) * t,
b: a.b + (b.b - a.b) * t,
a: a.a + (b.a - a.a) * t,
}
.into()
}
impl RenderOnce for OptionWheel {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let c = self.config.normalized();
let now = motion_now(cx);
let reduced = is_reduced_motion(cx);
let count = self.items.len();
let initial = c.default_selected.min(count.saturating_sub(1));
let state =
window.use_keyed_state((self.id.clone(), "option-wheel-state"), cx, |_, cx| State {
focus: cx.focus_handle().tab_index(0).tab_stop(true),
config: c.clone(),
items: self.items.clone(),
callback: None,
target: initial as f64,
motion: ExponentialSmoother::new(initial as f64, now),
index: initial,
row: 1.0,
drag: None,
moved: false,
wheel_revision: 0,
hits: Vec::new(),
dimensions: HashMap::new(),
masks: HashMap::new(),
shapes: HashMap::new(),
pending: HashSet::new(),
failed: HashSet::new(),
raster_busy: false,
raster_generation: 0,
raster_font: None,
release_hook: false,
#[cfg(debug_assertions)]
perf: std::env::var_os("ARC_OPTION_WHEEL_DIAGNOSTIC").map(|_| WheelPerf::new()),
sound_source: "".into(),
sound_bytes: None,
sound_ready: false,
player: None,
last_tick: None,
});
#[cfg(test)]
if let Some(probe) = &self.probe {
*probe.borrow_mut() = Some(state.clone());
}
if !state.read(cx).release_hook {
state.update(cx, |s, cx| {
s.release_hook = true;
cx.on_release_in(window, |s, window, _| {
for layers in s.masks.values() {
for layer in layers.iter() {
window.drop_alpha_mask(&layer.mask);
}
}
})
.detach();
});
}
let rem = window.rem_size().as_f32();
let family = window.text_style().font_family;
state.update(cx, |s, _| {
let changed = s.items != self.items;
let raster_font = (
family.clone(),
(c.font_size * rem).to_bits(),
window.scale_factor().to_bits(),
);
let font_changed = s.raster_font.as_ref() != Some(&raster_font);
s.raster_font = Some(raster_font);
s.config = c.clone();
s.items = self.items;
s.callback = self.on_change;
s.row = (c.font_size * c.spacing * rem).max(1.0);
if changed {
s.wheel_revision = s.wheel_revision.wrapping_add(1);
s.drag = None;
s.moved = false;
}
if changed || font_changed {
s.dimensions.clear();
for pyramid in s.masks.values() {
for layer in pyramid.iter() {
window.drop_alpha_mask(&layer.mask);
}
}
s.masks.clear();
s.shapes.clear();
s.pending.clear();
s.failed.clear();
s.raster_generation = s.raster_generation.wrapping_add(1);
}
if !c.draggable {
s.drag = None;
}
s.target = target(s.target, count, c.looping, false);
if changed || !c.looping {
s.index = selected(s.target, count);
}
if count <= 1 {
s.target = 0.0;
s.motion = ExponentialSmoother::new(0.0, now);
}
if c.looping && count > 1 && s.target.abs() > count as f64 * 1024.0 {
let shift = (s.target / count as f64).floor() * count as f64;
s.target -= shift;
s.motion.shift(shift);
if let Some((_, start)) = &mut s.drag {
*start -= shift;
}
}
if s.drag.is_some() {
let position = if s.moved { s.target } else { s.motion.value() };
s.motion = ExponentialSmoother::new(position, now);
} else {
s.motion.advance(s.target, now, c.smoothing, reduced);
}
});
prepare_sound(&state, window, cx);
let s = state.read(cx);
let pos = s.motion.value();
#[cfg(debug_assertions)]
let pos = {
let diagnostic = state.update(cx, |s, _| {
let ready = s.masks.len() == s.items.len() * 2 && !s.raster_busy;
s.perf.as_mut().and_then(|perf| perf.sample(ready, count))
});
if diagnostic.is_some() {
window.request_animation_frame();
}
diagnostic.unwrap_or(pos)
};
let s = state.read(cx);
let index = s.index;
let focus = s.focus.clone();
let dragging = s.drag.is_some();
if (pos - s.target).abs() >= 0.001 {
window.request_animation_frame();
}
let colors = cx.arc_theme().colors;
let ink = c.text_color.unwrap_or(colors.text_muted);
let active = c.active_color.unwrap_or(colors.foreground);
let draw_state = state.clone();
let draw_c = c.clone();
let measure = state.clone();
let drawing = canvas(
move |rect, _, cx| {
measure.update(cx, |s, _| s.hits.clear());
rect
},
move |_, rect, window, cx| {
#[cfg(debug_assertions)]
let paint_start = Instant::now();
if draw_state.read(cx).drag.is_some() {
let st = draw_state.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let Some((y, from)) = st.read(cx).drag else {
return;
};
if event.pressed_button != Some(MouseButton::Left) {
st.update(cx, |s, _| s.drag = None);
let value = st.read(cx).target;
apply(&st, value, true, window, cx);
return;
}
let dy = event.position.y.as_f32() - y;
if dy.abs() > 4.0 {
st.update(cx, |s, _| s.moved = true);
}
if st.read(cx).moved {
let value = from - f64::from(dy / st.read(cx).row);
apply(&st, value, false, window, cx);
cx.stop_propagation();
}
});
let st = draw_state.clone();
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
if !phase.bubble()
|| event.button != MouseButton::Left
|| st.read(cx).drag.is_none()
{
return;
}
st.update(cx, |s, _| s.drag = None);
if st.read(cx).moved {
let value = st.read(cx).target;
apply(&st, value, true, window, cx);
}
window.refresh();
});
}
let (labels, row) = {
let s = draw_state.read(cx);
(s.items.clone(), s.row)
};
let font = draw_c.font_size * rem;
let right = draw_c.side == OptionWheelSide::Right;
let inset = draw_c.inset.min((rect.size.width.as_f32() - font).max(0.0));
let anchor_x = if right {
rect.right() - px(inset)
} else {
rect.left() + px(inset)
};
let mut order: Vec<_> = (0..labels.len()).collect();
order.sort_by(|&a, &b| {
distance(a, pos, labels.len(), draw_c.looping)
.abs()
.total_cmp(&distance(b, pos, labels.len(), draw_c.looping).abs())
});
for i in order {
let label = &labels[i];
let p = pose(distance(i, pos, labels.len(), draw_c.looping), row, &draw_c);
for bold in [false, true] {
let key = (label.clone(), family.clone(), font.to_bits(), bold);
if !draw_state.read(cx).shapes.contains_key(&key) {
let mut text_font = window.text_style().font();
text_font.weight = if bold {
FontWeight::MEDIUM
} else {
FontWeight::EXTRA_LIGHT
};
let line = window.text_system().shape_line(
label.clone(),
px(font),
&[TextRun {
len: label.len(),
font: text_font,
color: active,
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
draw_state.update(cx, |s, _| {
s.dimensions.insert(key.clone(), line.width().as_f32());
s.shapes.insert(key.clone(), line);
});
}
if !draw_state.read(cx).masks.contains_key(&key) {
queue_raster(&draw_state, key, window, cx);
}
}
let normal_key = (label.clone(), family.clone(), font.to_bits(), false);
let bold_key = (label.clone(), family.clone(), font.to_bits(), true);
let width = draw_state.read(cx).dimensions[&normal_key] * (1.0 - p.blend)
+ draw_state.read(cx).dimensions[&bold_key] * p.blend;
let anchor = point(anchor_x + px(p.x), rect.center().y + px(p.y));
if (anchor.y - rect.center().y).abs()
> rect.size.height * 0.5 + px(width + font)
{
continue;
}
draw_state.update(cx, |s, _| {
s.hits.push(Hit {
index: i,
anchor,
width,
font,
angle: p.angle,
right,
})
});
let (lo, hi, t) = arc_motion::alpha_mask::mask_blend(p.blur);
let scale = window.scale_factor();
let transform = TransformationMatrix::unit()
.translate(anchor.scale(scale))
.rotate(gpui_kit::Radians(p.angle))
.translate(anchor.scale(-scale));
for (key, weight) in [(normal_key, 1.0 - p.blend), (bold_key, p.blend)] {
if weight <= 0.0 {
continue;
}
let Some(layers) = draw_state.read(cx).masks.get(&key).cloned() else {
let line = &draw_state.read(cx).shapes[&key];
let baseline =
(font * 1.8 - line.ascent.as_f32() - line.descent.as_f32()) * 0.5
+ line.ascent.as_f32();
for run in &line.runs {
for glyph in &run.glyphs {
if glyph.is_emoji {
continue;
}
let origin = point(
anchor.x - px(if right { width } else { 0.0 })
+ glyph.position.x,
anchor.y - px(font * 0.9) + px(baseline) + glyph.position.y,
);
let _ = window.paint_glyph_transformed(
origin,
run.font_id,
glyph.id,
px(font),
mix(ink, active, p.blend).opacity(p.opacity * weight),
transform,
);
}
}
continue;
};
for (level, alpha) in [(lo, 1.0 - t), (hi, t)] {
if alpha <= 0.0 {
continue;
}
let layer = &layers[level];
let dims = layer.mask.size();
let origin = point(
anchor.x - px(if right { width } else { 0.0 }) - px(layer.padding),
anchor.y - px(font * 0.9 + layer.padding),
);
let dest = bounds(
origin,
size(
px(dims.width.0 as f32 / layer.scale),
px(dims.height.0 as f32 / layer.scale),
),
);
let _ = window.paint_alpha_mask(
dest,
&layer.mask,
transform,
mix(ink, active, p.blend).opacity(p.opacity * weight * alpha),
);
}
}
}
#[cfg(debug_assertions)]
draw_state.update(cx, |s, _| {
if let Some(perf) = &mut s.perf
&& perf.warm_start.is_some()
&& !perf.finished
{
perf.paint_ms
.push(paint_start.elapsed().as_secs_f64() * 1000.0);
}
});
if labels.is_empty() {
let style = window.text_style();
let line = window.text_system().shape_line(
"暂无选项 / No options".into(),
px(14.0),
&[TextRun {
len: "暂无选项 / No options".len(),
font: style.font(),
color: ink,
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
let _ = line.paint(
point(rect.left() + px(16.0), rect.center().y),
px(20.0),
gpui_kit::TextAlign::Left,
None,
window,
cx,
);
}
},
)
.w_full()
.h_full();
let st_down = state.clone();
let st_click = state.clone();
let st_key = state.clone();
let st_scroll = state.clone();
let mut root = div()
.id(self.id.clone())
.test_support()
.track_focus(&focus)
.role(Role::ListBox)
.aria_label(self.label)
.aria_value(
state
.read(cx)
.items
.get(index)
.cloned()
.unwrap_or_else(|| "".into()),
)
.relative()
.w_full()
.min_w_0()
.h(px(c.height))
.overflow_hidden()
.cursor(if dragging {
gpui_kit::CursorStyle::ClosedHand
} else if c.draggable {
gpui_kit::CursorStyle::OpenHand
} else {
gpui_kit::CursorStyle::Arrow
})
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
let focus = st_down.read(cx).focus.clone();
window.focus(&focus, cx);
let now = motion_now(cx);
st_down.update(cx, |s, _| {
s.moved = false;
s.wheel_revision = s.wheel_revision.wrapping_add(1);
if s.config.draggable {
let position = s.motion.value();
s.drag = Some((event.position.y.as_f32(), position));
s.motion = ExponentialSmoother::new(position, now);
}
});
window.refresh();
cx.stop_propagation();
})
.on_click(move |event, window, cx| {
if st_click.read(cx).moved {
return;
}
let hit = st_click
.read(cx)
.hits
.iter()
.rev()
.find(|h| h.contains(event.position()))
.map(|h| h.index);
if let Some(i) = hit {
let s = st_click.read(cx);
let d = distance(i, s.target, s.items.len(), s.config.looping);
let v = s.target + f64::from(d);
apply(&st_click, v, true, window, cx);
}
})
.on_key_down(move |event, window, cx| {
let s = st_key.read(cx);
let value = match event.keystroke.key.as_str() {
"up" | "left" => js_round(s.target) - 1.0,
"down" | "right" => js_round(s.target) + 1.0,
"home" => 0.0,
"end" => s.items.len().saturating_sub(1) as f64,
_ => return,
};
st_key.update(cx, |s, _| {
s.wheel_revision = s.wheel_revision.wrapping_add(1);
s.drag = None;
});
apply(&st_key, value, true, window, cx);
cx.stop_propagation();
})
.on_scroll(move |event, window, cx| {
let delta = -event.delta.pixel_delta(px(24.0)).y.as_f32();
if delta == 0.0 || st_scroll.read(cx).items.is_empty() {
return;
}
let value = st_scroll.read(cx).target
+ f64::from((delta / st_scroll.read(cx).row).clamp(-1.0, 1.0));
apply(&st_scroll, value, false, window, cx);
cx.stop_propagation();
let generation = st_scroll.update(cx, |s, _| {
s.wheel_revision = s.wheel_revision.wrapping_add(1);
s.wheel_revision
});
let weak = st_scroll.downgrade();
window
.spawn(cx, async move |cx| {
cx.background_executor()
.timer(Duration::from_millis(140))
.await;
let _ = cx.update(|window, cx| {
let Some(st) = weak.upgrade() else {
return;
};
if st.read(cx).wheel_revision != generation
|| st.read(cx).drag.is_some()
{
return;
}
let value = st.read(cx).target;
apply(&st, value, true, window, cx);
});
})
.detach();
})
.child(drawing);
for (i, label) in state.read(cx).items.iter().enumerate() {
root = root.child(
div()
.id(("ow-option", i))
.test_support()
.role(Role::ListBoxOption)
.aria_label(label.clone())
.aria_selected(i == index)
.absolute()
.w(px(0.0))
.h(px(0.0))
.overflow_hidden(),
);
}
if focus.is_focused(window) {
root = root.border_1().border_color(colors.focus_outline);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, TestAppContext,
test::{TestEventExt as _, TestWindowExt as _},
};
struct Host {
config: OptionWheelConfig,
items: Vec<SharedString>,
changes: Vec<usize>,
probe: Rc<std::cell::RefCell<Option<Entity<State>>>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut wheel = OptionWheel::new("ow-test");
wheel.probe = Some(self.probe.clone());
div().w(px(800.0)).child(
wheel
.items(self.items.clone())
.config(self.config.clone())
.on_change(cx.listener(|this, e: &OptionWheelChange, _, cx| {
this.changes.push(e.index);
cx.notify();
})),
)
}
}
fn state(view: &Entity<Host>, cx: &App) -> Entity<State> {
view.read(cx)
.probe
.borrow()
.as_ref()
.expect("滚轮应已挂载")
.clone()
}
fn init(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
}
#[gpui_kit::test]
fn option_wheel_click_keyboard_loop_empty_and_theme(cx: &mut TestAppContext) {
init(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: default_items(),
changes: Vec::new(),
probe: Default::default(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let st = state(&view, cx);
assert_eq!(st.read(cx).index, 3);
assert!(view.read(cx).changes.is_empty());
assert_eq!(window.find("ow-test").role(), Some(Role::ListBox));
let hit = st.read(cx).hits.iter().find(|h| h.index == 4).unwrap();
let p = hit.anchor + point(px(20.0 * hit.angle.cos()), px(20.0 * hit.angle.sin()));
window.pointer_down(p, MouseButton::Left, cx);
window.render_frame(cx);
window.pointer_up(p, MouseButton::Left, cx);
window.render_frame(cx);
assert_eq!(st.read(cx).index, 4);
assert_eq!(view.read(cx).changes, vec![4]);
window.press("up", cx);
window.render_frame(cx);
assert_eq!(st.read(cx).index, 3);
window.press("home", cx);
window.render_frame(cx);
window.press("left", cx);
window.render_frame(cx);
assert_eq!(st.read(cx).index, 0);
view.update(cx, |v, cx| {
v.config.looping = true;
cx.notify();
});
window.render_frame(cx);
window.press("left", cx);
window.render_frame(cx);
assert_eq!(st.read(cx).index, 11);
assert_eq!(st.read(cx).motion.value(), -1.0);
view.update(cx, |v, cx| {
v.config.side = OptionWheelSide::Right;
cx.notify();
});
window.render_frame(cx);
assert!(st.read(cx).hits.iter().all(|h| h.right));
for mode in [ThemeMode::Dark, ThemeMode::Light] {
install_arc_theme(mode, Accent::Neutral, cx);
window.render_frame(cx);
}
view.update(cx, |v, cx| {
v.items = vec!["Only".into()];
cx.notify();
});
window.render_frame(cx);
assert_eq!(st.read(cx).index, 0);
view.update(cx, |v, cx| {
v.items.clear();
cx.notify();
});
window.render_frame(cx);
assert!(st.read(cx).hits.is_empty());
window.press("down", cx);
window.render_frame(cx);
});
}
#[gpui_kit::test]
fn option_wheel_drag_outside_disabled_and_click_suppression(cx: &mut TestAppContext) {
init(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: default_items(),
changes: Vec::new(),
probe: Default::default(),
});
cx.update(|window, cx| {
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
window.render_frame(cx);
let st = state(&view, cx);
let rect = window.find("ow-test").bounds();
let start = rect.center();
let row = st.read(cx).row;
window.pointer_down(start, MouseButton::Left, cx);
window.render_frame(cx);
window.pointer_move(
start - point(px(0.0), px(row * 1.7)),
Some(MouseButton::Left),
cx,
);
window.render_frame(cx);
assert_eq!(st.read(cx).index, 5);
assert!(st.read(cx).moved);
assert!(
(st.read(cx).motion.value() - st.read(cx).target).abs() < 1e-6,
"拖拽必须直接跟手"
);
window.pointer_up(point(px(1100.0), px(-30.0)), MouseButton::Left, cx);
window.render_frame(cx);
assert!(st.read(cx).drag.is_none());
assert_eq!(st.read(cx).target, 5.0);
assert_eq!(view.read(cx).changes, vec![5]);
view.update(cx, |v, cx| {
v.config.draggable = false;
cx.notify();
});
window.render_frame(cx);
window.pointer_down(start, MouseButton::Left, cx);
window.render_frame(cx);
window.pointer_move(
start - point(px(0.0), px(row * 2.0)),
Some(MouseButton::Left),
cx,
);
window.render_frame(cx);
window.pointer_up(point(px(1100.0), px(-30.0)), MouseButton::Left, cx);
window.render_frame(cx);
assert!(st.read(cx).drag.is_none());
assert_eq!(st.read(cx).index, 5);
});
}
#[gpui_kit::test]
fn option_wheel_drag_handoff_and_release_between_frames(cx: &mut TestAppContext) {
init(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: default_items(),
changes: Vec::new(),
probe: Default::default(),
});
cx.update(|window, cx| {
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
let st = state(&view, cx);
let now = motion_now(cx);
st.update(cx, |s, _| {
s.target = 8.0;
s.motion = ExponentialSmoother::new(3.0, now);
});
window.render_frame(cx);
let start = window.find("ow-test").bounds().center();
window.pointer_down(start, MouseButton::Left, cx);
window.render_frame(cx);
});
cx.executor().advance_clock(Duration::from_millis(32));
cx.update(|window, cx| {
window.render_frame(cx);
let st = state(&view, cx);
assert_eq!(
st.read(cx).motion.value(),
3.0,
"按下后必须接管当前画面,不能继续追逐旧目标"
);
let start = window.find("ow-test").bounds().center();
let row = st.read(cx).row;
window.pointer_move(
start - point(px(0.0), px(row * 0.7)),
Some(MouseButton::Left),
cx,
);
assert!((st.read(cx).motion.value() - 3.7).abs() < 1e-5);
window.pointer_move(
start + point(px(0.0), px(row * 0.35)),
Some(MouseButton::Left),
cx,
);
assert!((st.read(cx).motion.value() - 2.65).abs() < 1e-5);
window.pointer_up(
start + point(px(0.0), px(row * 0.35)),
MouseButton::Left,
cx,
);
window.render_frame(cx);
assert!(st.read(cx).drag.is_none());
assert_eq!(st.read(cx).target, 3.0);
assert!(
(st.read(cx).motion.value() - 2.65).abs() < 1e-5,
"吸附必须从最后输入位置开始,不能退回旧帧"
);
});
cx.executor().advance_clock(Duration::from_millis(16));
cx.update(|window, cx| {
window.render_frame(cx);
let value = state(&view, cx).read(cx).motion.value();
assert!(value > 2.65 && value < 3.0, "松手后才平滑吸附");
});
}
#[gpui_kit::test]
fn option_wheel_wheel_debounce_and_keyboard_cancellation(cx: &mut TestAppContext) {
init(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: default_items(),
changes: Vec::new(),
probe: Default::default(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let st = state(&view, cx);
let row = st.read(cx).row;
window.scroll(
"ow-test",
gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-row * 0.3))),
cx,
);
window.render_frame(cx);
assert!((st.read(cx).target - 3.3).abs() < 0.001);
window.scroll(
"ow-test",
gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-row * 0.3))),
cx,
);
window.render_frame(cx);
assert!((st.read(cx).target - 3.6).abs() < 0.001);
assert_eq!(st.read(cx).index, 4);
});
cx.executor().run_until_parked();
cx.executor().advance_clock(Duration::from_millis(150));
cx.update(|window, cx| {
window.render_frame(cx);
let st = state(&view, cx);
assert_eq!(st.read(cx).target, 4.0);
window.focus_next(cx);
window.render_frame(cx);
assert!(window.focused(cx).is_some());
let row = st.read(cx).row;
window.scroll(
"ow-test",
gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-row * 0.4))),
cx,
);
window.render_frame(cx);
window.press("home", cx);
window.render_frame(cx);
assert_eq!(st.read(cx).index, 0);
});
cx.executor().run_until_parked();
cx.executor().advance_clock(Duration::from_millis(150));
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(state(&view, cx).read(cx).target, 0.0);
});
}
#[gpui_kit::test]
fn option_wheel_reuses_native_mask_pyramids(cx: &mut TestAppContext) {
init(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: default_items(),
changes: Vec::new(),
probe: Default::default(),
});
cx.update(|w, cx| {
let st = state(&view, cx);
st.update(cx, |s, _| {
s.masks.clear();
s.shapes.clear();
s.pending.clear();
});
w.render_frame(cx);
assert!(st.read(cx).masks.is_empty(), "绘制线程不能同步烘焙缓存");
assert!(st.read(cx).raster_busy);
assert_eq!(st.read(cx).pending.len(), 1, "每实例只允许一个后台工作");
});
for _ in 0..24 {
cx.executor().run_until_parked();
cx.update(|w, cx| {
w.render_frame(cx);
});
}
cx.update(|w, cx| {
let st = state(&view, cx);
assert!(!st.read(cx).raster_busy);
assert!(st.read(cx).pending.is_empty());
let before = st.read(cx).masks.clone();
let paths = st.read(cx).shapes.len();
assert!(!before.is_empty());
for _ in 0..20 {
w.render_frame(cx);
}
assert_eq!(st.read(cx).shapes.len(), paths);
assert_eq!(st.read(cx).masks.len(), before.len());
let sprites = &w.rendered_scene().monochrome_sprites;
assert!(!sprites.is_empty(), "原始蒙版必须进入原生sprite场景");
assert!(
sprites
.iter()
.any(|s| s.transformation != TransformationMatrix::unit()),
"邻项旋转不可退化为直排"
);
for frame in 0..120 {
let now = motion_now(cx);
st.update(cx, |s, _| {
s.target = frame as f64 / 12.0;
s.motion = ExponentialSmoother::new(s.target, now);
});
w.render_frame(cx);
assert!(!st.read(cx).raster_busy);
assert_eq!(st.read(cx).masks.len(), before.len());
}
for (key, layers) in before {
assert!(
Arc::ptr_eq(&layers, &st.read(cx).masks[&key]),
"运动不得重新构造蒙版"
);
assert_eq!(layers.len(), arc_motion::alpha_mask::BLUR_LEVELS.len());
}
});
}
#[gpui_kit::test]
fn option_wheel_discards_stale_background_raster(cx: &mut TestAppContext) {
init(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
items: default_items(),
changes: Vec::new(),
probe: Default::default(),
});
cx.update(|w, cx| {
let st = state(&view, cx);
st.update(cx, |s, _| {
s.masks.clear();
s.shapes.clear();
s.pending.clear();
});
w.render_frame(cx);
assert!(st.read(cx).raster_busy);
let generation = st.read(cx).raster_generation;
view.update(cx, |v, cx| {
v.items = vec!["Replacement".into()];
cx.notify();
});
w.render_frame(cx);
assert!(st.read(cx).raster_generation > generation);
assert!(st.read(cx).pending.is_empty());
});
cx.executor().run_until_parked();
cx.update(|w, cx| {
let st = state(&view, cx);
assert!(
st.read(cx).masks.keys().all(|k| k.0 == "Replacement"),
"旧任务不得写入新配置"
);
assert!(st.read(cx).shapes.keys().all(|k| k.0 == "Replacement"));
w.render_frame(cx);
});
cx.executor().run_until_parked();
cx.update(|_, cx| {
let st = state(&view, cx);
assert_eq!(st.read(cx).masks.len(), 2);
assert!(st.read(cx).masks.keys().all(|k| k.0 == "Replacement"));
});
}
#[gpui_kit::test]
fn option_wheel_native_masks_retain_coverage(cx: &mut TestAppContext) {
init(cx);
cx.update(|cx| {
let system = gpui_kit::WindowTextSystem::new(cx.text_system().clone());
let line = system.shape_line(
"Jazz".into(),
px(48.0),
&[TextRun {
len: 4,
font: gpui_kit::font(".SystemUIFont"),
color: gpui_kit::black(),
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
let start = Instant::now();
let layers =
arc_motion::alpha_mask::native_mask_pyramid(cx.text_system(), &line, px(86.4), 2.0)
.unwrap();
eprintln!(
"native_mask_pyramid_ms={:.2}",
start.elapsed().as_secs_f64() * 1000.0
);
assert_eq!(layers.len(), 7);
assert_eq!(
layers[0].mask.size().width.0,
((line.width().as_f32() + 4.0) * 2.0).ceil() as i32
);
assert!(
gpui_kit::AlphaMask::new(
gpui_kit::size(gpui_kit::DevicePixels(2), gpui_kit::DevicePixels(2)),
vec![0u8; 3].into()
)
.is_err()
);
});
}
#[gpui_kit::test]
fn option_wheel_path_pipeline_keeps_glyphs_and_blur(cx: &mut TestAppContext) {
init(cx);
cx.update(|cx| {
let paths = label_paths("Jazz", "Segoe UI", 48.0, 220.0, true);
assert!(paths.contains("<path"));
assert!(!paths.contains("<text"), "模糊档位不得再次塑形文本");
assert_eq!(
label_paths("Jazz", "missing-system-font-alias", 48.0, 220.0, true),
paths,
"未知系统字体别名应使用同一无衬线回退,而不是衬线字体"
);
let count = |blur| {
let (_, data, _) = blurred_paths(&paths, 48.0, 220.0, blur);
let image = cx.svg_renderer().render_single_frame(&data, 1.0).unwrap();
image
.as_bytes(0)
.unwrap()
.chunks_exact(4)
.filter(|p| p[3] > 0)
.count()
};
let sharp = count(0.0);
assert!(sharp > 100);
assert!(count(4.0) > sharp);
});
}
#[gpui_kit::test]
#[ignore = "手动性能诊断:包含真实 SVG 光栅化,不作为 FPS 断言"]
fn option_wheel_raster_cost_diagnostic(cx: &mut TestAppContext) {
init(cx);
cx.update(|cx| {
let label = "Electronic";
let start = Instant::now();
let paths = label_paths(label, "Segoe UI", 48.0, 260.0, false);
let shape_ms = start.elapsed().as_secs_f64() * 1000.0;
let mut old = Vec::new();
let mut new = Vec::new();
for blur in [0.0, 2.0, 4.0, 6.0, 8.0] {
let start = Instant::now();
let (_, data, _) = text_svg(label, "Segoe UI", 48.0, 260.0, false, blur);
cx.svg_renderer().render_single_frame(&data, 1.0).unwrap();
old.push(start.elapsed().as_secs_f64() * 1000.0);
let start = Instant::now();
let (_, data, _) = blurred_paths(&paths, 48.0, 260.0, blur);
cx.svg_renderer().render_single_frame(&data, 1.0).unwrap();
new.push(start.elapsed().as_secs_f64() * 1000.0);
}
eprintln!("OptionWheel cold_shape_ms={shape_ms:.2}; old_raster_ms={old:?}; path_raster_ms={new:?}; diagnostic_is_not_fps=true");
});
}
#[gpui_kit::test]
fn option_wheel_svg_really_blurs_system_glyphs(cx: &mut TestAppContext) {
init(cx);
cx.update(|cx| {
let renderer = cx.svg_renderer();
let count = |blur| {
let (_, svg, _) = text_svg("Jazz", "Segoe UI", 48.0, 220.0, true, blur);
let image = renderer
.render_single_frame(&svg, 1.0)
.expect("SVG 应成功解析绘制");
image
.as_bytes(0)
.unwrap()
.chunks_exact(4)
.filter(|p| p[3] > 0)
.count()
};
let sharp = count(0.0);
let soft = count(4.0);
assert!(sharp > 100, "不能渲染空白字形");
assert!(soft > sharp, "高斯模糊应扩散字形 alpha 而不是只降低透明度");
});
}
#[test]
fn option_wheel_wrap_and_js_rounding() {
assert_eq!(selected(-0.5, 12), 0);
assert_eq!(selected(-1.0, 12), 11);
assert_eq!(selected(0.0, 0), 0);
assert_eq!(target(99.0, 6, false, true), 5.0);
assert_eq!(target(-2.0, 6, false, false), 0.0);
assert_eq!(distance(0, 11.0, 12, true), 1.0);
assert_eq!(distance(11, 0.0, 12, true), -1.0);
assert_eq!(target(f64::NAN, 0, false, true), 0.0);
}
#[test]
fn option_wheel_arc_mirror_and_hit() {
let c = OptionWheelConfig::default();
let a = pose(2.0, 67.2, &c);
let b = pose(
2.0,
67.2,
&OptionWheelConfig {
side: OptionWheelSide::Right,
..c.clone()
},
);
assert!((a.x + b.x).abs() < 1e-5);
assert_eq!(a.y, b.y);
assert_eq!(a.angle, -b.angle);
assert_eq!(pose(0.0, 67.2, &c).blend, 1.0);
assert_eq!(a.blur, 4.0);
let flat = pose(2.0, 67.2, &OptionWheelConfig { tilt: 0.0, ..c });
assert_eq!(flat.y, 134.4);
assert_eq!(flat.angle, 0.0);
let hit = Hit {
index: 0,
anchor: point(px(80.0), px(200.0)),
width: 200.0,
font: 48.0,
angle: 0.2,
right: false,
};
assert!(hit.contains(point(
px(80.0 + 100.0 * 0.2_f32.cos()),
px(200.0 + 100.0 * 0.2_f32.sin())
)));
assert!(!hit.contains(point(px(0.0), px(0.0))));
}
#[test]
fn option_wheel_config_and_svg() {
let c = OptionWheelConfig {
font_size: f32::NAN,
sound_volume: 3.0,
..Default::default()
}
.normalized();
assert_eq!(c.font_size, 3.0);
assert_eq!(c.sound_volume, 1.0);
let (_, svg, _) = text_svg("A<&\"", "Segoe UI", 48.0, 200.0, false, 2.0);
let svg = std::str::from_utf8(&svg).unwrap();
assert!(svg.contains("feGaussianBlur"));
assert!(svg.contains("A<&""));
}
}