Skip to main content

arc_ui/inputs/
option_wheel.rs

1//! OptionWheel 原生移植,参考 React Bits © David Haz (DavidHDev)。
2//! MIT + Commons Clause,见 THIRD_PARTY_NOTICES。原生字形蒙版及后台高斯近似层级连续混合。
3//! Props:Config 对齐源码默认值;State:focus / drag / wheel / selected;
4//! Motion:目标改变 → ExponentialSmoother(200ms tau)→ 圆弧位置/旋转/颜色/透明度。
5
6use super::option_wheel_sound::TickPlayer;
7use arc_motion::{ExponentialSmoother, is_reduced_motion, motion_now};
8use arc_tokens::ActiveArcTheme as _;
9use gpui_kit::{
10    App, ElementId, Entity, FocusHandle, FontWeight, Hsla, IntoElement, MouseButton,
11    MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, RenderOnce, Role, SharedString,
12    Styled, TestSupportExt as _, TextRun, TransformationMatrix, Window, bounds, canvas, div, point,
13    prelude::*, px, size,
14};
15use std::{
16    collections::{HashMap, HashSet},
17    rc::Rc,
18    sync::Arc,
19    time::{Duration, Instant},
20};
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum OptionWheelSide {
24    #[default]
25    Left,
26    Right,
27}
28
29#[derive(Clone, Debug)]
30pub struct OptionWheelConfig {
31    pub default_selected: usize,
32    pub text_color: Option<Hsla>,
33    pub active_color: Option<Hsla>,
34    pub side: OptionWheelSide,
35    /// rem,按宿主窗口 rem_size 换算。
36    pub font_size: f32,
37    pub spacing: f32,
38    pub curve: f32,
39    pub tilt: f32,
40    pub blur: f32,
41    pub fade: f32,
42    pub min_opacity: f32,
43    pub smoothing: f32,
44    pub inset: f32,
45    pub looping: bool,
46    pub draggable: bool,
47    /// 空值禁用;builtin:soft 为本地合成短音;支持资源路径、本地文件及 http(s)。
48    pub sound_url: SharedString,
49    pub sound_volume: f32,
50    /// 原生组件不依赖父节点百分比高度,默认 420px。
51    pub height: f32,
52}
53impl Default for OptionWheelConfig {
54    fn default() -> Self {
55        Self {
56            default_selected: 3,
57            text_color: None,
58            active_color: None,
59            side: OptionWheelSide::Left,
60            font_size: 3.0,
61            spacing: 1.4,
62            curve: 1.0,
63            tilt: 6.0,
64            blur: 2.0,
65            fade: 0.25,
66            min_opacity: 0.05,
67            smoothing: 200.0,
68            inset: 80.0,
69            looping: false,
70            draggable: true,
71            sound_url: "".into(),
72            sound_volume: 0.5,
73            height: 420.0,
74        }
75    }
76}
77fn finite(v: f32, default: f32, lo: f32, hi: f32) -> f32 {
78    if v.is_finite() {
79        v.clamp(lo, hi)
80    } else {
81        default
82    }
83}
84impl OptionWheelConfig {
85    fn normalized(mut self) -> Self {
86        self.font_size = finite(self.font_size, 3.0, 0.5, 12.0);
87        self.spacing = finite(self.spacing, 1.4, 0.5, 4.0);
88        self.curve = finite(self.curve, 1.0, 0.0, 4.0);
89        self.tilt = finite(self.tilt, 6.0, 0.0, 45.0);
90        self.blur = finite(self.blur, 2.0, 0.0, 16.0);
91        self.fade = finite(self.fade, 0.25, 0.0, 1.0);
92        self.min_opacity = finite(self.min_opacity, 0.05, 0.0, 1.0);
93        self.smoothing = finite(self.smoothing, 200.0, 1.0, 3000.0);
94        self.inset = finite(self.inset, 80.0, 0.0, 1200.0);
95        self.sound_volume = finite(self.sound_volume, 0.5, 0.0, 1.0);
96        self.height = finite(self.height, 420.0, 80.0, 1600.0);
97        self
98    }
99}
100#[derive(Clone, Debug)]
101pub struct OptionWheelChange {
102    pub index: usize,
103    pub item: SharedString,
104}
105type Change = Rc<dyn Fn(&OptionWheelChange, &mut Window, &mut App)>;
106
107#[derive(IntoElement)]
108pub struct OptionWheel {
109    id: ElementId,
110    items: Vec<SharedString>,
111    config: OptionWheelConfig,
112    on_change: Option<Change>,
113    label: SharedString,
114    #[cfg(test)]
115    probe: Option<Rc<std::cell::RefCell<Option<Entity<State>>>>>,
116}
117impl OptionWheel {
118    pub fn new(id: impl Into<ElementId>) -> Self {
119        Self {
120            id: id.into(),
121            items: default_items(),
122            config: Default::default(),
123            on_change: None,
124            label: "Option wheel".into(),
125            #[cfg(test)]
126            probe: None,
127        }
128    }
129    pub fn items(mut self, items: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
130        self.items = items.into_iter().map(Into::into).collect();
131        self
132    }
133    pub fn config(mut self, config: OptionWheelConfig) -> Self {
134        self.config = config;
135        self
136    }
137    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
138        self.label = label.into();
139        self
140    }
141    /// 与源码一致:目标的四舍五入索引改变时触发,不等待视觉动画落定。
142    pub fn on_change(
143        mut self,
144        callback: impl Fn(&OptionWheelChange, &mut Window, &mut App) + 'static,
145    ) -> Self {
146        self.on_change = Some(Rc::new(callback));
147        self
148    }
149}
150pub fn default_items() -> Vec<SharedString> {
151    [
152        "Ambient",
153        "House",
154        "Techno",
155        "Jazz",
156        "Lo-Fi",
157        "Synthwave",
158        "Trance",
159        "Funk",
160        "Disco",
161        "Hip-Hop",
162        "Chillwave",
163        "Drum & Bass",
164    ]
165    .into_iter()
166    .map(Into::into)
167    .collect()
168}
169fn selected(value: f64, count: usize) -> usize {
170    if count == 0 {
171        0
172    } else {
173        js_round(value).rem_euclid(count as f64) as usize
174    }
175}
176fn js_round(value: f64) -> f64 {
177    (value + 0.5).floor()
178}
179fn target(value: f64, count: usize, looping: bool, snap: bool) -> f64 {
180    let value = if value.is_finite() { value } else { 0.0 };
181    let value = if looping && count > 1 {
182        value
183    } else {
184        value.clamp(0.0, count.saturating_sub(1) as f64)
185    };
186    if snap { js_round(value) } else { value }
187}
188fn distance(index: usize, pos: f64, count: usize, looping: bool) -> f32 {
189    let mut d = index as f64 - pos;
190    if looping && count > 1 {
191        d = d.rem_euclid(count as f64);
192        if d > count as f64 / 2.0 {
193            d -= count as f64;
194        }
195    }
196    d as f32
197}
198#[derive(Clone, Copy, Debug)]
199struct Pose {
200    x: f32,
201    y: f32,
202    angle: f32,
203    opacity: f32,
204    blend: f32,
205    blur: f32,
206}
207fn pose(d: f32, row: f32, c: &OptionWheelConfig) -> Pose {
208    let mirror = if c.side == OptionWheelSide::Right {
209        -1.0
210    } else {
211        1.0
212    };
213    let tilt = c.tilt.to_radians();
214    let (x, y, angle) = if tilt > 0.0005 {
215        let radius = row / tilt;
216        let angle = (d * tilt).clamp(-std::f32::consts::FRAC_PI_2, std::f32::consts::FRAC_PI_2);
217        (
218            -mirror * radius * (1.0 - angle.cos()) * c.curve,
219            radius * angle.sin(),
220            mirror * angle,
221        )
222    } else {
223        (0.0, d * row, 0.0)
224    };
225    Pose {
226        x,
227        y,
228        angle,
229        opacity: (1.0 - d.abs() * c.fade).max(c.min_opacity),
230        blend: (1.0 - d.abs()).clamp(0.0, 1.0),
231        blur: (d.abs() * c.blur).min(32.0),
232    }
233}
234struct Hit {
235    index: usize,
236    anchor: Point<Pixels>,
237    width: f32,
238    font: f32,
239    angle: f32,
240    right: bool,
241}
242impl Hit {
243    fn contains(&self, p: Point<Pixels>) -> bool {
244        let x = (p.x - self.anchor.x).as_f32();
245        let y = (p.y - self.anchor.y).as_f32();
246        let u = x * self.angle.cos() + y * self.angle.sin();
247        let v = -x * self.angle.sin() + y * self.angle.cos();
248        let u = if self.right { -u } else { u };
249        u >= 0.0 && u <= self.width && v.abs() <= self.font * 0.5
250    }
251}
252type LabelKey = (SharedString, SharedString, u32, bool);
253type RasterKey = LabelKey;
254type RasterEntry = Arc<Vec<arc_motion::alpha_mask::MaskLayer>>;
255
256/// 显式环境开关的原生诊断,不作为 FPS/呈现时间断言。
257#[cfg(debug_assertions)]
258struct WheelPerf {
259    cold_start: Instant,
260    warm_start: Option<Instant>,
261    last_frame: Option<Instant>,
262    intervals_ms: Vec<f64>,
263    paint_ms: Vec<f64>,
264    finished: bool,
265}
266#[cfg(debug_assertions)]
267impl WheelPerf {
268    fn new() -> Self {
269        Self {
270            cold_start: Instant::now(),
271            warm_start: None,
272            last_frame: None,
273            intervals_ms: Vec::new(),
274            paint_ms: Vec::new(),
275            finished: false,
276        }
277    }
278    fn sample(&mut self, ready: bool, count: usize) -> Option<f64> {
279        if self.finished || !ready || count < 2 {
280            return None;
281        }
282        let now = Instant::now();
283        let start = *self.warm_start.get_or_insert_with(|| {
284            eprintln!(
285                "OptionWheel native diagnostic cold_prepare_ms={:.2}",
286                self.cold_start.elapsed().as_secs_f64() * 1000.0
287            );
288            now
289        });
290        if let Some(last) = self.last_frame.replace(now) {
291            self.intervals_ms
292                .push(now.duration_since(last).as_secs_f64() * 1000.0);
293        }
294        let elapsed = now.duration_since(start).as_secs_f64();
295        if elapsed >= 10.0 {
296            self.finished = true;
297            self.intervals_ms.sort_by(f64::total_cmp);
298            self.paint_ms.sort_by(f64::total_cmp);
299            let percentile = |data: &[f64], p: f64| {
300                data.get(((data.len().saturating_sub(1) as f64) * p).round() as usize)
301                    .copied()
302                    .unwrap_or(0.0)
303            };
304            eprintln!(
305                "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",
306                self.intervals_ms.len(),
307                percentile(&self.intervals_ms, 0.5),
308                percentile(&self.intervals_ms, 0.95),
309                percentile(&self.intervals_ms, 0.99),
310                percentile(&self.intervals_ms, 1.0),
311                percentile(&self.paint_ms, 0.95)
312            );
313            None
314        } else {
315            Some((count - 1) as f64 * (0.5 + 0.45 * (elapsed * std::f64::consts::PI).sin()))
316        }
317    }
318}
319
320struct State {
321    focus: FocusHandle,
322    config: OptionWheelConfig,
323    items: Vec<SharedString>,
324    callback: Option<Change>,
325    target: f64,
326    motion: ExponentialSmoother,
327    index: usize,
328    row: f32,
329    drag: Option<(f32, f64)>,
330    moved: bool,
331    wheel_revision: u64,
332    hits: Vec<Hit>,
333    dimensions: HashMap<LabelKey, f32>,
334    masks: HashMap<RasterKey, RasterEntry>,
335    shapes: HashMap<LabelKey, gpui_kit::ShapedLine>,
336    pending: HashSet<RasterKey>,
337    failed: HashSet<RasterKey>,
338    raster_busy: bool,
339    raster_generation: u64,
340    raster_font: Option<(SharedString, u32, u32)>,
341    release_hook: bool,
342    #[cfg(debug_assertions)]
343    perf: Option<WheelPerf>,
344    sound_source: SharedString,
345    sound_bytes: Option<Arc<[u8]>>,
346    sound_ready: bool,
347    player: Option<TickPlayer>,
348    last_tick: Option<Instant>,
349}
350fn apply(state: &Entity<State>, value: f64, snap: bool, window: &mut Window, cx: &mut App) {
351    let now = motion_now(cx);
352    let event = state.update(cx, |s, _| {
353        if s.items.is_empty() {
354            return None;
355        }
356        let value = target(value, s.items.len(), s.config.looping, snap);
357        s.target = value;
358        // 输入回调内同步视觉位置;移动后尚未绘制就松手,也从最后输入处吸附。
359        if !snap && s.drag.is_some() && s.moved {
360            s.motion = ExponentialSmoother::new(value, now);
361        }
362        let index = selected(value, s.items.len());
363        if index == s.index {
364            return None;
365        }
366        s.index = index;
367        let tick = !s.config.sound_url.is_empty()
368            && s.last_tick
369                .is_none_or(|t| t.elapsed() >= Duration::from_millis(70));
370        if tick && s.sound_ready {
371            s.last_tick = Some(Instant::now());
372            if s.player.is_none() {
373                s.player = TickPlayer::new();
374            }
375            if let Some(player) = &s.player {
376                player.play(s.sound_bytes.clone(), s.config.sound_volume);
377            }
378        }
379        Some((
380            OptionWheelChange {
381                index,
382                item: s.items[index].clone(),
383            },
384            s.callback.clone(),
385        ))
386    });
387    if let Some((event, Some(callback))) = event {
388        callback(&event, window, cx);
389    }
390    window.refresh();
391}
392fn prepare_sound(state: &Entity<State>, window: &mut Window, cx: &mut App) {
393    let url = state.read(cx).config.sound_url.clone();
394    if state.read(cx).sound_source == url {
395        return;
396    }
397    state.update(cx, |s, _| {
398        s.sound_source = url.clone();
399        s.sound_bytes = None;
400        s.sound_ready = url == "builtin:soft";
401        s.last_tick = None;
402        s.player = None;
403    });
404    if url.is_empty() || url == "builtin:soft" {
405        return;
406    }
407    let client = cx.http_client();
408    let assets = cx.asset_source().clone();
409    let weak = state.downgrade();
410    window
411        .spawn(cx, async move |cx| {
412            let source = url.clone();
413            let result = cx
414                .background_executor()
415                .spawn(async move {
416                    const LIMIT: u64 = 4 * 1024 * 1024;
417                    if source.starts_with("https://") || source.starts_with("http://") {
418                        use futures_lite::AsyncReadExt;
419                        let mut response =
420                            client.get(source.as_ref(), ().into(), true).await.ok()?;
421                        if !response.status().is_success() {
422                            return None;
423                        }
424                        let mut bytes = Vec::new();
425                        response
426                            .body_mut()
427                            .take(LIMIT + 1)
428                            .read_to_end(&mut bytes)
429                            .await
430                            .ok()?;
431                        if bytes.len() as u64 > LIMIT {
432                            return None;
433                        }
434                        Some(Arc::<[u8]>::from(bytes))
435                    } else {
436                        if let Ok(Some(bytes)) = assets.load(&source) {
437                            return (bytes.len() as u64 <= LIMIT)
438                                .then(|| Arc::<[u8]>::from(bytes.to_vec()));
439                        }
440                        let path = std::path::Path::new(source.as_ref());
441                        if std::fs::metadata(path).ok()?.len() > LIMIT {
442                            return None;
443                        }
444                        let bytes = std::fs::read(path).ok()?;
445                        (bytes.len() as u64 <= LIMIT).then(|| Arc::<[u8]>::from(bytes))
446                    }
447                })
448                .await;
449            let _ = cx.update(|_, cx| {
450                let Some(st) = weak.upgrade() else {
451                    return;
452                };
453                st.update(cx, |s, _| {
454                    if s.sound_source == url {
455                        s.sound_ready = result.is_some();
456                        s.sound_bytes = result;
457                    }
458                });
459            });
460        })
461        .detach();
462}
463#[cfg(test)]
464use std::hash::{Hash, Hasher};
465
466#[cfg(test)]
467fn xml(text: &str) -> String {
468    text.replace('&', "&amp;")
469        .replace('<', "&lt;")
470        .replace('>', "&gt;")
471        .replace('"', "&quot;")
472        .replace('\'', "&apos;")
473}
474#[cfg(test)]
475fn text_svg(
476    label: &str,
477    family: &str,
478    font: f32,
479    width: f32,
480    bold: bool,
481    blur: f32,
482) -> (SharedString, Arc<[u8]>, f32) {
483    // 0.5px 档位控制 SVG 图集种类;旋转、位置和颜色仍为连续值。
484    let blur = (blur * 2.0).round() * 0.5;
485    let pad = (blur * 3.0 + 2.0).ceil();
486    let h = font * 1.8;
487    let w = width.max(1.0) + pad * 2.0;
488    let height = h + pad * 2.0;
489    let baseline = pad + font * 1.2;
490    let weight = if bold { 500 } else { 200 };
491    let filter = if blur > 0.0 {
492        r#"filter="url(#b)""#.to_string()
493    } else {
494        String::new()
495    };
496    let svg = format!(
497        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>"#,
498        xml(family),
499        xml(label)
500    );
501    let mut hasher = std::collections::hash_map::DefaultHasher::new();
502    svg.hash(&mut hasher);
503    (
504        format!("arc-option-text-{:016x}", hasher.finish()).into(),
505        Arc::from(svg.into_bytes()),
506        pad,
507    )
508}
509/// 先将文字塑形为纯路径;后续模糊档位不再经过 fontdb/rustybuzz。
510#[cfg(test)]
511fn label_paths(label: &str, family: &str, font: f32, width: f32, bold: bool) -> String {
512    // 与原生系统字体别名对齐;未知别名先尝试系统无衬线族,避免 usvg 自动加 Serif。
513    let families = format!("{family}, Segoe UI, Helvetica Neue, DejaVu Sans, sans-serif");
514    let (_, data, _) = text_svg(label, &families, font, width, bold, 0.0);
515    let converted = crate::text::glyph_outline::svg_font_database()
516        .ok()
517        .and_then(|fontdb| {
518            let options = usvg::Options {
519                fontdb,
520                ..Default::default()
521            };
522            usvg::Tree::from_data(&data, &options)
523                .ok()
524                .map(|tree| tree.to_string(&usvg::WriteOptions::default()))
525        });
526    let svg = converted.unwrap_or_else(|| String::from_utf8_lossy(&data).into_owned());
527    let start = svg
528        .find("<svg")
529        .and_then(|i| svg[i..].find('>').map(|j| i + j + 1))
530        .unwrap_or(0);
531    let end = svg.rfind("</svg>").unwrap_or(svg.len());
532    svg[start..end].to_string()
533}
534
535#[cfg(test)]
536fn blurred_paths(paths: &str, font: f32, width: f32, blur: f32) -> (SharedString, Arc<[u8]>, f32) {
537    let pad = (blur * 3.0 + 2.0).ceil();
538    let w = width.max(1.0) + pad * 2.0;
539    let h = font * 1.8 + pad * 2.0;
540    // 将过滤器限定在已包含 3σ 留白的画布内,不再分配原来 3×3 的过滤区域。
541    let svg = format!(
542        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>"#,
543        offset = pad - 2.0
544    );
545    let mut hasher = std::collections::hash_map::DefaultHasher::new();
546    svg.hash(&mut hasher);
547    (
548        format!("arc-option-path-{:016x}", hasher.finish()).into(),
549        Arc::from(svg.into_bytes()),
550        pad,
551    )
552}
553
554fn queue_raster(state: &Entity<State>, key: RasterKey, window: &mut Window, cx: &mut App) {
555    if state.read(cx).raster_busy
556        || state.read(cx).pending.contains(&key)
557        || state.read(cx).failed.contains(&key)
558    {
559        return;
560    }
561    let Some(line) = state.read(cx).shapes.get(&key).cloned() else {
562        return;
563    };
564    let font = f32::from_bits(key.2);
565    let generation = state.read(cx).raster_generation;
566    state.update(cx, |s, _| {
567        s.raster_busy = true;
568        s.pending.insert(key.clone());
569    });
570    let system = cx.text_system().clone();
571    let scale = window.scale_factor().max(1.0) * 2.0;
572    let weak = state.downgrade();
573    window
574        .spawn(cx, async move |cx| {
575            let result = cx
576                .background_executor()
577                .spawn(async move {
578                    arc_motion::alpha_mask::native_mask_pyramid(
579                        &system,
580                        &line,
581                        px(font * 1.8),
582                        scale,
583                    )
584                    .map(Arc::new)
585                })
586                .await;
587            let _ = cx.update(|window, cx| {
588                if let Some(state) = weak.upgrade() {
589                    state.update(cx, |s, _| {
590                        s.raster_busy = false;
591                        if generation == s.raster_generation {
592                            s.pending.remove(&key);
593                            if let Ok(entry) = result {
594                                s.masks.insert(key, entry);
595                            } else {
596                                // 失败档位保持原生文字回退,不在每帧无限重试并刷新。
597                                s.failed.insert(key);
598                            }
599                        }
600                    });
601                    window.refresh();
602                }
603            });
604        })
605        .detach();
606}
607
608fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla {
609    let a = a.to_rgb();
610    let b = b.to_rgb();
611    gpui_kit::Rgba {
612        r: a.r + (b.r - a.r) * t,
613        g: a.g + (b.g - a.g) * t,
614        b: a.b + (b.b - a.b) * t,
615        a: a.a + (b.a - a.a) * t,
616    }
617    .into()
618}
619impl RenderOnce for OptionWheel {
620    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
621        let c = self.config.normalized();
622        let now = motion_now(cx);
623        let reduced = is_reduced_motion(cx);
624        let count = self.items.len();
625        let initial = c.default_selected.min(count.saturating_sub(1));
626        let state =
627            window.use_keyed_state((self.id.clone(), "option-wheel-state"), cx, |_, cx| State {
628                focus: cx.focus_handle().tab_index(0).tab_stop(true),
629                config: c.clone(),
630                items: self.items.clone(),
631                callback: None,
632                target: initial as f64,
633                motion: ExponentialSmoother::new(initial as f64, now),
634                index: initial,
635                row: 1.0,
636                drag: None,
637                moved: false,
638                wheel_revision: 0,
639                hits: Vec::new(),
640                dimensions: HashMap::new(),
641                masks: HashMap::new(),
642                shapes: HashMap::new(),
643                pending: HashSet::new(),
644                failed: HashSet::new(),
645                raster_busy: false,
646                raster_generation: 0,
647                raster_font: None,
648                release_hook: false,
649                #[cfg(debug_assertions)]
650                perf: std::env::var_os("ARC_OPTION_WHEEL_DIAGNOSTIC").map(|_| WheelPerf::new()),
651                sound_source: "".into(),
652                sound_bytes: None,
653                sound_ready: false,
654                player: None,
655                last_tick: None,
656            });
657        #[cfg(test)]
658        if let Some(probe) = &self.probe {
659            *probe.borrow_mut() = Some(state.clone());
660        }
661        if !state.read(cx).release_hook {
662            state.update(cx, |s, cx| {
663                s.release_hook = true;
664                cx.on_release_in(window, |s, window, _| {
665                    for layers in s.masks.values() {
666                        for layer in layers.iter() {
667                            window.drop_alpha_mask(&layer.mask);
668                        }
669                    }
670                })
671                .detach();
672            });
673        }
674        let rem = window.rem_size().as_f32();
675        let family = window.text_style().font_family;
676        state.update(cx, |s, _| {
677            let changed = s.items != self.items;
678            // 按最终字体与 px 字号失效,包含宿主 rem/主题字体变化。
679            let raster_font = (
680                family.clone(),
681                (c.font_size * rem).to_bits(),
682                window.scale_factor().to_bits(),
683            );
684            let font_changed = s.raster_font.as_ref() != Some(&raster_font);
685            s.raster_font = Some(raster_font);
686            s.config = c.clone();
687            s.items = self.items;
688            s.callback = self.on_change;
689            s.row = (c.font_size * c.spacing * rem).max(1.0);
690            if changed {
691                s.wheel_revision = s.wheel_revision.wrapping_add(1);
692                s.drag = None;
693                s.moved = false;
694            }
695            if changed || font_changed {
696                s.dimensions.clear();
697                for pyramid in s.masks.values() {
698                    for layer in pyramid.iter() {
699                        window.drop_alpha_mask(&layer.mask);
700                    }
701                }
702                s.masks.clear();
703                s.shapes.clear();
704                s.pending.clear();
705                s.failed.clear();
706                s.raster_generation = s.raster_generation.wrapping_add(1);
707            }
708            if !c.draggable {
709                s.drag = None;
710            }
711            s.target = target(s.target, count, c.looping, false);
712            if changed || !c.looping {
713                s.index = selected(s.target, count);
714            }
715            if count <= 1 {
716                s.target = 0.0;
717                s.motion = ExponentialSmoother::new(0.0, now);
718            }
719            if c.looping && count > 1 && s.target.abs() > count as f64 * 1024.0 {
720                let shift = (s.target / count as f64).floor() * count as f64;
721                s.target -= shift;
722                s.motion.shift(shift);
723                if let Some((_, start)) = &mut s.drag {
724                    *start -= shift;
725                }
726            }
727            if s.drag.is_some() {
728                let position = if s.moved { s.target } else { s.motion.value() };
729                s.motion = ExponentialSmoother::new(position, now);
730            } else {
731                s.motion.advance(s.target, now, c.smoothing, reduced);
732            }
733        });
734        prepare_sound(&state, window, cx);
735        let s = state.read(cx);
736        let pos = s.motion.value();
737        #[cfg(debug_assertions)]
738        let pos = {
739            let diagnostic = state.update(cx, |s, _| {
740                let ready = s.masks.len() == s.items.len() * 2 && !s.raster_busy;
741                s.perf.as_mut().and_then(|perf| perf.sample(ready, count))
742            });
743            if diagnostic.is_some() {
744                window.request_animation_frame();
745            }
746            diagnostic.unwrap_or(pos)
747        };
748        let s = state.read(cx);
749        let index = s.index;
750        let focus = s.focus.clone();
751        let dragging = s.drag.is_some();
752        if (pos - s.target).abs() >= 0.001 {
753            window.request_animation_frame();
754        }
755        let colors = cx.arc_theme().colors;
756        let ink = c.text_color.unwrap_or(colors.text_muted);
757        let active = c.active_color.unwrap_or(colors.foreground);
758        let draw_state = state.clone();
759        let draw_c = c.clone();
760        let measure = state.clone();
761        let drawing = canvas(
762            move |rect, _, cx| {
763                measure.update(cx, |s, _| s.hits.clear());
764                rect
765            },
766            move |_, rect, window, cx| {
767                #[cfg(debug_assertions)]
768                let paint_start = Instant::now();
769                // 全窗口监听保证拖出边界仍能松手;只在已按下时注册,失去按键立即取消。
770                if draw_state.read(cx).drag.is_some() {
771                    let st = draw_state.clone();
772                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
773                        if !phase.bubble() {
774                            return;
775                        }
776                        let Some((y, from)) = st.read(cx).drag else {
777                            return;
778                        };
779                        if event.pressed_button != Some(MouseButton::Left) {
780                            st.update(cx, |s, _| s.drag = None);
781                            let value = st.read(cx).target;
782                            apply(&st, value, true, window, cx);
783                            return;
784                        }
785                        let dy = event.position.y.as_f32() - y;
786                        if dy.abs() > 4.0 {
787                            st.update(cx, |s, _| s.moved = true);
788                        }
789                        if st.read(cx).moved {
790                            let value = from - f64::from(dy / st.read(cx).row);
791                            apply(&st, value, false, window, cx);
792                            cx.stop_propagation();
793                        }
794                    });
795                    let st = draw_state.clone();
796                    window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
797                        if !phase.bubble()
798                            || event.button != MouseButton::Left
799                            || st.read(cx).drag.is_none()
800                        {
801                            return;
802                        }
803                        st.update(cx, |s, _| s.drag = None);
804                        if st.read(cx).moved {
805                            let value = st.read(cx).target;
806                            apply(&st, value, true, window, cx);
807                        }
808                        window.refresh();
809                    });
810                }
811                let (labels, row) = {
812                    let s = draw_state.read(cx);
813                    (s.items.clone(), s.row)
814                };
815                let font = draw_c.font_size * rem;
816                let right = draw_c.side == OptionWheelSide::Right;
817                let inset = draw_c.inset.min((rect.size.width.as_f32() - font).max(0.0));
818                let anchor_x = if right {
819                    rect.right() - px(inset)
820                } else {
821                    rect.left() + px(inset)
822                };
823                // 单后台任务优先准备中心及邻近项,避免远端档位饿住当前选项。
824                let mut order: Vec<_> = (0..labels.len()).collect();
825                order.sort_by(|&a, &b| {
826                    distance(a, pos, labels.len(), draw_c.looping)
827                        .abs()
828                        .total_cmp(&distance(b, pos, labels.len(), draw_c.looping).abs())
829                });
830                for i in order {
831                    let label = &labels[i];
832                    let p = pose(distance(i, pos, labels.len(), draw_c.looping), row, &draw_c);
833                    // 两种字重始终共存,按视觉距离连续混合,不随整数选中切换缓存。
834                    for bold in [false, true] {
835                        let key = (label.clone(), family.clone(), font.to_bits(), bold);
836                        if !draw_state.read(cx).shapes.contains_key(&key) {
837                            let mut text_font = window.text_style().font();
838                            text_font.weight = if bold {
839                                FontWeight::MEDIUM
840                            } else {
841                                FontWeight::EXTRA_LIGHT
842                            };
843                            let line = window.text_system().shape_line(
844                                label.clone(),
845                                px(font),
846                                &[TextRun {
847                                    len: label.len(),
848                                    font: text_font,
849                                    color: active,
850                                    background_color: None,
851                                    underline: None,
852                                    strikethrough: None,
853                                }],
854                                None,
855                            );
856                            draw_state.update(cx, |s, _| {
857                                s.dimensions.insert(key.clone(), line.width().as_f32());
858                                s.shapes.insert(key.clone(), line);
859                            });
860                        }
861                        if !draw_state.read(cx).masks.contains_key(&key) {
862                            queue_raster(&draw_state, key, window, cx);
863                        }
864                    }
865                    let normal_key = (label.clone(), family.clone(), font.to_bits(), false);
866                    let bold_key = (label.clone(), family.clone(), font.to_bits(), true);
867                    let width = draw_state.read(cx).dimensions[&normal_key] * (1.0 - p.blend)
868                        + draw_state.read(cx).dimensions[&bold_key] * p.blend;
869                    let anchor = point(anchor_x + px(p.x), rect.center().y + px(p.y));
870                    // 在与绘制相同的旋转坐标系中命中,避免旋转文字的包围盒误选。
871                    if (anchor.y - rect.center().y).abs()
872                        > rect.size.height * 0.5 + px(width + font)
873                    {
874                        continue;
875                    }
876                    draw_state.update(cx, |s, _| {
877                        s.hits.push(Hit {
878                            index: i,
879                            anchor,
880                            width,
881                            font,
882                            angle: p.angle,
883                            right,
884                        })
885                    });
886                    let (lo, hi, t) = arc_motion::alpha_mask::mask_blend(p.blur);
887                    let scale = window.scale_factor();
888                    let transform = TransformationMatrix::unit()
889                        .translate(anchor.scale(scale))
890                        .rotate(gpui_kit::Radians(p.angle))
891                        .translate(anchor.scale(-scale));
892                    for (key, weight) in [(normal_key, 1.0 - p.blend), (bold_key, p.blend)] {
893                        if weight <= 0.0 {
894                            continue;
895                        }
896                        let Some(layers) = draw_state.read(cx).masks.get(&key).cloned() else {
897                            // 准备期间仍用相同字形和旋转,不再先显示直排文字后突然切图。
898                            let line = &draw_state.read(cx).shapes[&key];
899                            let baseline =
900                                (font * 1.8 - line.ascent.as_f32() - line.descent.as_f32()) * 0.5
901                                    + line.ascent.as_f32();
902                            for run in &line.runs {
903                                for glyph in &run.glyphs {
904                                    if glyph.is_emoji {
905                                        continue;
906                                    }
907                                    let origin = point(
908                                        anchor.x - px(if right { width } else { 0.0 })
909                                            + glyph.position.x,
910                                        anchor.y - px(font * 0.9) + px(baseline) + glyph.position.y,
911                                    );
912                                    let _ = window.paint_glyph_transformed(
913                                        origin,
914                                        run.font_id,
915                                        glyph.id,
916                                        px(font),
917                                        mix(ink, active, p.blend).opacity(p.opacity * weight),
918                                        transform,
919                                    );
920                                }
921                            }
922                            continue;
923                        };
924                        for (level, alpha) in [(lo, 1.0 - t), (hi, t)] {
925                            if alpha <= 0.0 {
926                                continue;
927                            }
928                            let layer = &layers[level];
929                            let dims = layer.mask.size();
930                            let origin = point(
931                                anchor.x - px(if right { width } else { 0.0 }) - px(layer.padding),
932                                anchor.y - px(font * 0.9 + layer.padding),
933                            );
934                            let dest = bounds(
935                                origin,
936                                size(
937                                    px(dims.width.0 as f32 / layer.scale),
938                                    px(dims.height.0 as f32 / layer.scale),
939                                ),
940                            );
941                            let _ = window.paint_alpha_mask(
942                                dest,
943                                &layer.mask,
944                                transform,
945                                mix(ink, active, p.blend).opacity(p.opacity * weight * alpha),
946                            );
947                        }
948                    }
949                }
950                #[cfg(debug_assertions)]
951                draw_state.update(cx, |s, _| {
952                    if let Some(perf) = &mut s.perf
953                        && perf.warm_start.is_some()
954                        && !perf.finished
955                    {
956                        perf.paint_ms
957                            .push(paint_start.elapsed().as_secs_f64() * 1000.0);
958                    }
959                });
960                if labels.is_empty() {
961                    let style = window.text_style();
962                    let line = window.text_system().shape_line(
963                        "暂无选项 / No options".into(),
964                        px(14.0),
965                        &[TextRun {
966                            len: "暂无选项 / No options".len(),
967                            font: style.font(),
968                            color: ink,
969                            background_color: None,
970                            underline: None,
971                            strikethrough: None,
972                        }],
973                        None,
974                    );
975                    let _ = line.paint(
976                        point(rect.left() + px(16.0), rect.center().y),
977                        px(20.0),
978                        gpui_kit::TextAlign::Left,
979                        None,
980                        window,
981                        cx,
982                    );
983                }
984            },
985        )
986        .w_full()
987        .h_full();
988        let st_down = state.clone();
989        let st_click = state.clone();
990        let st_key = state.clone();
991        let st_scroll = state.clone();
992        let mut root = div()
993            .id(self.id.clone())
994            .test_support()
995            .track_focus(&focus)
996            .role(Role::ListBox)
997            .aria_label(self.label)
998            .aria_value(
999                state
1000                    .read(cx)
1001                    .items
1002                    .get(index)
1003                    .cloned()
1004                    .unwrap_or_else(|| "".into()),
1005            )
1006            .relative()
1007            .w_full()
1008            .min_w_0()
1009            .h(px(c.height))
1010            .overflow_hidden()
1011            .cursor(if dragging {
1012                gpui_kit::CursorStyle::ClosedHand
1013            } else if c.draggable {
1014                gpui_kit::CursorStyle::OpenHand
1015            } else {
1016                gpui_kit::CursorStyle::Arrow
1017            })
1018            .on_mouse_down(MouseButton::Left, move |event, window, cx| {
1019                let focus = st_down.read(cx).focus.clone();
1020                window.focus(&focus, cx);
1021                let now = motion_now(cx);
1022                st_down.update(cx, |s, _| {
1023                    s.moved = false;
1024                    s.wheel_revision = s.wheel_revision.wrapping_add(1);
1025                    if s.config.draggable {
1026                        let position = s.motion.value();
1027                        s.drag = Some((event.position.y.as_f32(), position));
1028                        // 按下立即接管正在运动的画面,不再继续追逐旧目标。
1029                        s.motion = ExponentialSmoother::new(position, now);
1030                    }
1031                });
1032                window.refresh();
1033                cx.stop_propagation();
1034            })
1035            .on_click(move |event, window, cx| {
1036                if st_click.read(cx).moved {
1037                    return;
1038                }
1039                let hit = st_click
1040                    .read(cx)
1041                    .hits
1042                    .iter()
1043                    .rev()
1044                    .find(|h| h.contains(event.position()))
1045                    .map(|h| h.index);
1046                if let Some(i) = hit {
1047                    let s = st_click.read(cx);
1048                    let d = distance(i, s.target, s.items.len(), s.config.looping);
1049                    let v = s.target + f64::from(d);
1050                    apply(&st_click, v, true, window, cx);
1051                }
1052            })
1053            .on_key_down(move |event, window, cx| {
1054                let s = st_key.read(cx);
1055                let value = match event.keystroke.key.as_str() {
1056                    "up" | "left" => js_round(s.target) - 1.0,
1057                    "down" | "right" => js_round(s.target) + 1.0,
1058                    "home" => 0.0,
1059                    "end" => s.items.len().saturating_sub(1) as f64,
1060                    _ => return,
1061                };
1062                st_key.update(cx, |s, _| {
1063                    s.wheel_revision = s.wheel_revision.wrapping_add(1);
1064                    s.drag = None;
1065                });
1066                apply(&st_key, value, true, window, cx);
1067                cx.stop_propagation();
1068            })
1069            .on_scroll(move |event, window, cx| {
1070                let delta = -event.delta.pixel_delta(px(24.0)).y.as_f32();
1071                if delta == 0.0 || st_scroll.read(cx).items.is_empty() {
1072                    return;
1073                }
1074                let value = st_scroll.read(cx).target
1075                    + f64::from((delta / st_scroll.read(cx).row).clamp(-1.0, 1.0));
1076                apply(&st_scroll, value, false, window, cx);
1077                cx.stop_propagation();
1078                let generation = st_scroll.update(cx, |s, _| {
1079                    s.wheel_revision = s.wheel_revision.wrapping_add(1);
1080                    s.wheel_revision
1081                });
1082                let weak = st_scroll.downgrade();
1083                window
1084                    .spawn(cx, async move |cx| {
1085                        cx.background_executor()
1086                            .timer(Duration::from_millis(140))
1087                            .await;
1088                        let _ = cx.update(|window, cx| {
1089                            let Some(st) = weak.upgrade() else {
1090                                return;
1091                            };
1092                            if st.read(cx).wheel_revision != generation
1093                                || st.read(cx).drag.is_some()
1094                            {
1095                                return;
1096                            }
1097                            let value = st.read(cx).target;
1098                            apply(&st, value, true, window, cx);
1099                        });
1100                    })
1101                    .detach();
1102            })
1103            .child(drawing);
1104        // 选项语义单独保留,不让隐藏的普通矩形承担旋转后的鼠标命中。
1105        for (i, label) in state.read(cx).items.iter().enumerate() {
1106            root = root.child(
1107                div()
1108                    .id(("ow-option", i))
1109                    .test_support()
1110                    .role(Role::ListBoxOption)
1111                    .aria_label(label.clone())
1112                    .aria_selected(i == index)
1113                    .absolute()
1114                    .w(px(0.0))
1115                    .h(px(0.0))
1116                    .overflow_hidden(),
1117            );
1118        }
1119        if focus.is_focused(window) {
1120            root = root.border_1().border_color(colors.focus_outline);
1121        }
1122        root
1123    }
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128    use super::*;
1129    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1130    use gpui_kit::{
1131        Context, Render, TestAppContext,
1132        test::{TestEventExt as _, TestWindowExt as _},
1133    };
1134    struct Host {
1135        config: OptionWheelConfig,
1136        items: Vec<SharedString>,
1137        changes: Vec<usize>,
1138        probe: Rc<std::cell::RefCell<Option<Entity<State>>>>,
1139    }
1140    impl Render for Host {
1141        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1142            let mut wheel = OptionWheel::new("ow-test");
1143            wheel.probe = Some(self.probe.clone());
1144            div().w(px(800.0)).child(
1145                wheel
1146                    .items(self.items.clone())
1147                    .config(self.config.clone())
1148                    .on_change(cx.listener(|this, e: &OptionWheelChange, _, cx| {
1149                        this.changes.push(e.index);
1150                        cx.notify();
1151                    })),
1152            )
1153        }
1154    }
1155    fn state(view: &Entity<Host>, cx: &App) -> Entity<State> {
1156        view.read(cx)
1157            .probe
1158            .borrow()
1159            .as_ref()
1160            .expect("滚轮应已挂载")
1161            .clone()
1162    }
1163    fn init(cx: &mut TestAppContext) {
1164        cx.update(|cx| {
1165            gpui_kit::init(cx);
1166            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
1167            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1168        });
1169    }
1170    #[gpui_kit::test]
1171    fn option_wheel_click_keyboard_loop_empty_and_theme(cx: &mut TestAppContext) {
1172        init(cx);
1173        let (view, cx) = cx.add_window_view(|_, _| Host {
1174            config: Default::default(),
1175            items: default_items(),
1176            changes: Vec::new(),
1177            probe: Default::default(),
1178        });
1179        cx.update(|window, cx| {
1180            window.render_frame(cx);
1181            let st = state(&view, cx);
1182            assert_eq!(st.read(cx).index, 3);
1183            assert!(view.read(cx).changes.is_empty());
1184            assert_eq!(window.find("ow-test").role(), Some(Role::ListBox));
1185            let hit = st.read(cx).hits.iter().find(|h| h.index == 4).unwrap();
1186            let p = hit.anchor + point(px(20.0 * hit.angle.cos()), px(20.0 * hit.angle.sin()));
1187            window.pointer_down(p, MouseButton::Left, cx);
1188            window.render_frame(cx);
1189            window.pointer_up(p, MouseButton::Left, cx);
1190            window.render_frame(cx);
1191            assert_eq!(st.read(cx).index, 4);
1192            assert_eq!(view.read(cx).changes, vec![4]);
1193            window.press("up", cx);
1194            window.render_frame(cx);
1195            assert_eq!(st.read(cx).index, 3);
1196            window.press("home", cx);
1197            window.render_frame(cx);
1198            window.press("left", cx);
1199            window.render_frame(cx);
1200            assert_eq!(st.read(cx).index, 0);
1201            view.update(cx, |v, cx| {
1202                v.config.looping = true;
1203                cx.notify();
1204            });
1205            window.render_frame(cx);
1206            window.press("left", cx);
1207            window.render_frame(cx);
1208            assert_eq!(st.read(cx).index, 11);
1209            assert_eq!(st.read(cx).motion.value(), -1.0);
1210            view.update(cx, |v, cx| {
1211                v.config.side = OptionWheelSide::Right;
1212                cx.notify();
1213            });
1214            window.render_frame(cx);
1215            assert!(st.read(cx).hits.iter().all(|h| h.right));
1216            for mode in [ThemeMode::Dark, ThemeMode::Light] {
1217                install_arc_theme(mode, Accent::Neutral, cx);
1218                window.render_frame(cx);
1219            }
1220            view.update(cx, |v, cx| {
1221                v.items = vec!["Only".into()];
1222                cx.notify();
1223            });
1224            window.render_frame(cx);
1225            assert_eq!(st.read(cx).index, 0);
1226            view.update(cx, |v, cx| {
1227                v.items.clear();
1228                cx.notify();
1229            });
1230            window.render_frame(cx);
1231            assert!(st.read(cx).hits.is_empty());
1232            window.press("down", cx);
1233            window.render_frame(cx);
1234        });
1235    }
1236    #[gpui_kit::test]
1237    fn option_wheel_drag_outside_disabled_and_click_suppression(cx: &mut TestAppContext) {
1238        init(cx);
1239        let (view, cx) = cx.add_window_view(|_, _| Host {
1240            config: Default::default(),
1241            items: default_items(),
1242            changes: Vec::new(),
1243            probe: Default::default(),
1244        });
1245        cx.update(|window, cx| {
1246            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
1247            window.render_frame(cx);
1248            let st = state(&view, cx);
1249            let rect = window.find("ow-test").bounds();
1250            let start = rect.center();
1251            let row = st.read(cx).row;
1252            window.pointer_down(start, MouseButton::Left, cx);
1253            window.render_frame(cx);
1254            window.pointer_move(
1255                start - point(px(0.0), px(row * 1.7)),
1256                Some(MouseButton::Left),
1257                cx,
1258            );
1259            window.render_frame(cx);
1260            assert_eq!(st.read(cx).index, 5);
1261            assert!(st.read(cx).moved);
1262            assert!(
1263                (st.read(cx).motion.value() - st.read(cx).target).abs() < 1e-6,
1264                "拖拽必须直接跟手"
1265            );
1266            window.pointer_up(point(px(1100.0), px(-30.0)), MouseButton::Left, cx);
1267            window.render_frame(cx);
1268            assert!(st.read(cx).drag.is_none());
1269            assert_eq!(st.read(cx).target, 5.0);
1270            assert_eq!(view.read(cx).changes, vec![5]);
1271            view.update(cx, |v, cx| {
1272                v.config.draggable = false;
1273                cx.notify();
1274            });
1275            window.render_frame(cx);
1276            window.pointer_down(start, MouseButton::Left, cx);
1277            window.render_frame(cx);
1278            window.pointer_move(
1279                start - point(px(0.0), px(row * 2.0)),
1280                Some(MouseButton::Left),
1281                cx,
1282            );
1283            window.render_frame(cx);
1284            window.pointer_up(point(px(1100.0), px(-30.0)), MouseButton::Left, cx);
1285            window.render_frame(cx);
1286            assert!(st.read(cx).drag.is_none());
1287            assert_eq!(st.read(cx).index, 5);
1288        });
1289    }
1290    #[gpui_kit::test]
1291    fn option_wheel_drag_handoff_and_release_between_frames(cx: &mut TestAppContext) {
1292        init(cx);
1293        let (view, cx) = cx.add_window_view(|_, _| Host {
1294            config: Default::default(),
1295            items: default_items(),
1296            changes: Vec::new(),
1297            probe: Default::default(),
1298        });
1299        cx.update(|window, cx| {
1300            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
1301            let st = state(&view, cx);
1302            let now = motion_now(cx);
1303            st.update(cx, |s, _| {
1304                s.target = 8.0;
1305                s.motion = ExponentialSmoother::new(3.0, now);
1306            });
1307            window.render_frame(cx);
1308            let start = window.find("ow-test").bounds().center();
1309            window.pointer_down(start, MouseButton::Left, cx);
1310            window.render_frame(cx);
1311        });
1312        cx.executor().advance_clock(Duration::from_millis(32));
1313        cx.update(|window, cx| {
1314            window.render_frame(cx);
1315            let st = state(&view, cx);
1316            assert_eq!(
1317                st.read(cx).motion.value(),
1318                3.0,
1319                "按下后必须接管当前画面,不能继续追逐旧目标"
1320            );
1321            let start = window.find("ow-test").bounds().center();
1322            let row = st.read(cx).row;
1323            // 同一显示帧内先向上,再反向向下,随后松手,不插入 render_frame。
1324            window.pointer_move(
1325                start - point(px(0.0), px(row * 0.7)),
1326                Some(MouseButton::Left),
1327                cx,
1328            );
1329            assert!((st.read(cx).motion.value() - 3.7).abs() < 1e-5);
1330            window.pointer_move(
1331                start + point(px(0.0), px(row * 0.35)),
1332                Some(MouseButton::Left),
1333                cx,
1334            );
1335            assert!((st.read(cx).motion.value() - 2.65).abs() < 1e-5);
1336            window.pointer_up(
1337                start + point(px(0.0), px(row * 0.35)),
1338                MouseButton::Left,
1339                cx,
1340            );
1341            window.render_frame(cx);
1342            assert!(st.read(cx).drag.is_none());
1343            assert_eq!(st.read(cx).target, 3.0);
1344            assert!(
1345                (st.read(cx).motion.value() - 2.65).abs() < 1e-5,
1346                "吸附必须从最后输入位置开始,不能退回旧帧"
1347            );
1348        });
1349        cx.executor().advance_clock(Duration::from_millis(16));
1350        cx.update(|window, cx| {
1351            window.render_frame(cx);
1352            let value = state(&view, cx).read(cx).motion.value();
1353            assert!(value > 2.65 && value < 3.0, "松手后才平滑吸附");
1354        });
1355    }
1356
1357    #[gpui_kit::test]
1358    fn option_wheel_wheel_debounce_and_keyboard_cancellation(cx: &mut TestAppContext) {
1359        init(cx);
1360        let (view, cx) = cx.add_window_view(|_, _| Host {
1361            config: Default::default(),
1362            items: default_items(),
1363            changes: Vec::new(),
1364            probe: Default::default(),
1365        });
1366        cx.update(|window, cx| {
1367            window.render_frame(cx);
1368            let st = state(&view, cx);
1369            let row = st.read(cx).row;
1370            window.scroll(
1371                "ow-test",
1372                gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-row * 0.3))),
1373                cx,
1374            );
1375            window.render_frame(cx);
1376            assert!((st.read(cx).target - 3.3).abs() < 0.001);
1377            window.scroll(
1378                "ow-test",
1379                gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-row * 0.3))),
1380                cx,
1381            );
1382            window.render_frame(cx);
1383            assert!((st.read(cx).target - 3.6).abs() < 0.001);
1384            assert_eq!(st.read(cx).index, 4);
1385        });
1386        cx.executor().run_until_parked();
1387        cx.executor().advance_clock(Duration::from_millis(150));
1388        cx.update(|window, cx| {
1389            window.render_frame(cx);
1390            let st = state(&view, cx);
1391            assert_eq!(st.read(cx).target, 4.0);
1392            window.focus_next(cx);
1393            window.render_frame(cx);
1394            assert!(window.focused(cx).is_some());
1395            let row = st.read(cx).row;
1396            window.scroll(
1397                "ow-test",
1398                gpui_kit::ScrollDelta::Pixels(point(px(0.0), px(-row * 0.4))),
1399                cx,
1400            );
1401            window.render_frame(cx);
1402            window.press("home", cx);
1403            window.render_frame(cx);
1404            assert_eq!(st.read(cx).index, 0);
1405        });
1406        cx.executor().run_until_parked();
1407        cx.executor().advance_clock(Duration::from_millis(150));
1408        cx.update(|window, cx| {
1409            window.render_frame(cx);
1410            assert_eq!(state(&view, cx).read(cx).target, 0.0);
1411        });
1412    }
1413    #[gpui_kit::test]
1414    fn option_wheel_reuses_native_mask_pyramids(cx: &mut TestAppContext) {
1415        init(cx);
1416        let (view, cx) = cx.add_window_view(|_, _| Host {
1417            config: Default::default(),
1418            items: default_items(),
1419            changes: Vec::new(),
1420            probe: Default::default(),
1421        });
1422        cx.update(|w, cx| {
1423            let st = state(&view, cx);
1424            st.update(cx, |s, _| {
1425                s.masks.clear();
1426                s.shapes.clear();
1427                s.pending.clear();
1428            });
1429            w.render_frame(cx);
1430            assert!(st.read(cx).masks.is_empty(), "绘制线程不能同步烘焙缓存");
1431            assert!(st.read(cx).raster_busy);
1432            assert_eq!(st.read(cx).pending.len(), 1, "每实例只允许一个后台工作");
1433        });
1434        // 每次完成一个任务后刷新,直到可见档位准备完;不用真实计时等待。
1435        for _ in 0..24 {
1436            cx.executor().run_until_parked();
1437            cx.update(|w, cx| {
1438                w.render_frame(cx);
1439            });
1440        }
1441        cx.update(|w, cx| {
1442            let st = state(&view, cx);
1443            assert!(!st.read(cx).raster_busy);
1444            assert!(st.read(cx).pending.is_empty());
1445            let before = st.read(cx).masks.clone();
1446            let paths = st.read(cx).shapes.len();
1447            assert!(!before.is_empty());
1448            for _ in 0..20 {
1449                w.render_frame(cx);
1450            }
1451            assert_eq!(st.read(cx).shapes.len(), paths);
1452            assert_eq!(st.read(cx).masks.len(), before.len());
1453            let sprites = &w.rendered_scene().monochrome_sprites;
1454            assert!(!sprites.is_empty(), "原始蒙版必须进入原生sprite场景");
1455            assert!(
1456                sprites
1457                    .iter()
1458                    .any(|s| s.transformation != TransformationMatrix::unit()),
1459                "邻项旋转不可退化为直排"
1460            );
1461            // 缓存备齐后连续改变位置,运动帧不得增加新光栅任务/缓存。
1462            for frame in 0..120 {
1463                let now = motion_now(cx);
1464                st.update(cx, |s, _| {
1465                    s.target = frame as f64 / 12.0;
1466                    s.motion = ExponentialSmoother::new(s.target, now);
1467                });
1468                w.render_frame(cx);
1469                assert!(!st.read(cx).raster_busy);
1470                assert_eq!(st.read(cx).masks.len(), before.len());
1471            }
1472            for (key, layers) in before {
1473                assert!(
1474                    Arc::ptr_eq(&layers, &st.read(cx).masks[&key]),
1475                    "运动不得重新构造蒙版"
1476                );
1477                assert_eq!(layers.len(), arc_motion::alpha_mask::BLUR_LEVELS.len());
1478            }
1479        });
1480    }
1481
1482    #[gpui_kit::test]
1483    fn option_wheel_discards_stale_background_raster(cx: &mut TestAppContext) {
1484        init(cx);
1485        let (view, cx) = cx.add_window_view(|_, _| Host {
1486            config: Default::default(),
1487            items: default_items(),
1488            changes: Vec::new(),
1489            probe: Default::default(),
1490        });
1491        cx.update(|w, cx| {
1492            let st = state(&view, cx);
1493            st.update(cx, |s, _| {
1494                s.masks.clear();
1495                s.shapes.clear();
1496                s.pending.clear();
1497            });
1498            w.render_frame(cx);
1499            assert!(st.read(cx).raster_busy);
1500            let generation = st.read(cx).raster_generation;
1501            view.update(cx, |v, cx| {
1502                v.items = vec!["Replacement".into()];
1503                cx.notify();
1504            });
1505            w.render_frame(cx);
1506            assert!(st.read(cx).raster_generation > generation);
1507            assert!(st.read(cx).pending.is_empty());
1508        });
1509        cx.executor().run_until_parked();
1510        cx.update(|w, cx| {
1511            let st = state(&view, cx);
1512            // executor 同时处理 refresh,可能已完成新内容;只禁止旧结果污染。
1513            assert!(
1514                st.read(cx).masks.keys().all(|k| k.0 == "Replacement"),
1515                "旧任务不得写入新配置"
1516            );
1517            assert!(st.read(cx).shapes.keys().all(|k| k.0 == "Replacement"));
1518            w.render_frame(cx);
1519        });
1520        cx.executor().run_until_parked();
1521        cx.update(|_, cx| {
1522            let st = state(&view, cx);
1523            assert_eq!(st.read(cx).masks.len(), 2);
1524            assert!(st.read(cx).masks.keys().all(|k| k.0 == "Replacement"));
1525        });
1526    }
1527
1528    #[gpui_kit::test]
1529    fn option_wheel_native_masks_retain_coverage(cx: &mut TestAppContext) {
1530        init(cx);
1531        cx.update(|cx| {
1532            let system = gpui_kit::WindowTextSystem::new(cx.text_system().clone());
1533            let line = system.shape_line(
1534                "Jazz".into(),
1535                px(48.0),
1536                &[TextRun {
1537                    len: 4,
1538                    font: gpui_kit::font(".SystemUIFont"),
1539                    color: gpui_kit::black(),
1540                    background_color: None,
1541                    underline: None,
1542                    strikethrough: None,
1543                }],
1544                None,
1545            );
1546            let start = Instant::now();
1547            let layers =
1548                arc_motion::alpha_mask::native_mask_pyramid(cx.text_system(), &line, px(86.4), 2.0)
1549                    .unwrap();
1550            eprintln!(
1551                "native_mask_pyramid_ms={:.2}",
1552                start.elapsed().as_secs_f64() * 1000.0
1553            );
1554            // TestPlatform 不光栅字形(raster_bounds=0),不能用它伪造真实字体像素验收。
1555            assert_eq!(layers.len(), 7);
1556            assert_eq!(
1557                layers[0].mask.size().width.0,
1558                ((line.width().as_f32() + 4.0) * 2.0).ceil() as i32
1559            );
1560            assert!(
1561                gpui_kit::AlphaMask::new(
1562                    gpui_kit::size(gpui_kit::DevicePixels(2), gpui_kit::DevicePixels(2)),
1563                    vec![0u8; 3].into()
1564                )
1565                .is_err()
1566            );
1567        });
1568    }
1569
1570    #[gpui_kit::test]
1571    fn option_wheel_path_pipeline_keeps_glyphs_and_blur(cx: &mut TestAppContext) {
1572        init(cx);
1573        cx.update(|cx| {
1574            let paths = label_paths("Jazz", "Segoe UI", 48.0, 220.0, true);
1575            assert!(paths.contains("<path"));
1576            assert!(!paths.contains("<text"), "模糊档位不得再次塑形文本");
1577            assert_eq!(
1578                label_paths("Jazz", "missing-system-font-alias", 48.0, 220.0, true),
1579                paths,
1580                "未知系统字体别名应使用同一无衬线回退,而不是衬线字体"
1581            );
1582            let count = |blur| {
1583                let (_, data, _) = blurred_paths(&paths, 48.0, 220.0, blur);
1584                let image = cx.svg_renderer().render_single_frame(&data, 1.0).unwrap();
1585                image
1586                    .as_bytes(0)
1587                    .unwrap()
1588                    .chunks_exact(4)
1589                    .filter(|p| p[3] > 0)
1590                    .count()
1591            };
1592            let sharp = count(0.0);
1593            assert!(sharp > 100);
1594            assert!(count(4.0) > sharp);
1595        });
1596    }
1597
1598    #[gpui_kit::test]
1599    #[ignore = "手动性能诊断:包含真实 SVG 光栅化,不作为 FPS 断言"]
1600    fn option_wheel_raster_cost_diagnostic(cx: &mut TestAppContext) {
1601        init(cx);
1602        cx.update(|cx| {
1603            let label = "Electronic";
1604            let start = Instant::now();
1605            let paths = label_paths(label, "Segoe UI", 48.0, 260.0, false);
1606            let shape_ms = start.elapsed().as_secs_f64() * 1000.0;
1607            let mut old = Vec::new();
1608            let mut new = Vec::new();
1609            for blur in [0.0, 2.0, 4.0, 6.0, 8.0] {
1610                let start = Instant::now();
1611                let (_, data, _) = text_svg(label, "Segoe UI", 48.0, 260.0, false, blur);
1612                cx.svg_renderer().render_single_frame(&data, 1.0).unwrap();
1613                old.push(start.elapsed().as_secs_f64() * 1000.0);
1614                let start = Instant::now();
1615                let (_, data, _) = blurred_paths(&paths, 48.0, 260.0, blur);
1616                cx.svg_renderer().render_single_frame(&data, 1.0).unwrap();
1617                new.push(start.elapsed().as_secs_f64() * 1000.0);
1618            }
1619            eprintln!("OptionWheel cold_shape_ms={shape_ms:.2}; old_raster_ms={old:?}; path_raster_ms={new:?}; diagnostic_is_not_fps=true");
1620        });
1621    }
1622
1623    #[gpui_kit::test]
1624    fn option_wheel_svg_really_blurs_system_glyphs(cx: &mut TestAppContext) {
1625        init(cx);
1626        cx.update(|cx| {
1627            let renderer = cx.svg_renderer();
1628            let count = |blur| {
1629                let (_, svg, _) = text_svg("Jazz", "Segoe UI", 48.0, 220.0, true, blur);
1630                let image = renderer
1631                    .render_single_frame(&svg, 1.0)
1632                    .expect("SVG 应成功解析绘制");
1633                image
1634                    .as_bytes(0)
1635                    .unwrap()
1636                    .chunks_exact(4)
1637                    .filter(|p| p[3] > 0)
1638                    .count()
1639            };
1640            let sharp = count(0.0);
1641            let soft = count(4.0);
1642            assert!(sharp > 100, "不能渲染空白字形");
1643            assert!(soft > sharp, "高斯模糊应扩散字形 alpha 而不是只降低透明度");
1644        });
1645    }
1646    #[test]
1647    fn option_wheel_wrap_and_js_rounding() {
1648        assert_eq!(selected(-0.5, 12), 0);
1649        assert_eq!(selected(-1.0, 12), 11);
1650        assert_eq!(selected(0.0, 0), 0);
1651        assert_eq!(target(99.0, 6, false, true), 5.0);
1652        assert_eq!(target(-2.0, 6, false, false), 0.0);
1653        assert_eq!(distance(0, 11.0, 12, true), 1.0);
1654        assert_eq!(distance(11, 0.0, 12, true), -1.0);
1655        assert_eq!(target(f64::NAN, 0, false, true), 0.0);
1656    }
1657    #[test]
1658    fn option_wheel_arc_mirror_and_hit() {
1659        let c = OptionWheelConfig::default();
1660        let a = pose(2.0, 67.2, &c);
1661        let b = pose(
1662            2.0,
1663            67.2,
1664            &OptionWheelConfig {
1665                side: OptionWheelSide::Right,
1666                ..c.clone()
1667            },
1668        );
1669        assert!((a.x + b.x).abs() < 1e-5);
1670        assert_eq!(a.y, b.y);
1671        assert_eq!(a.angle, -b.angle);
1672        assert_eq!(pose(0.0, 67.2, &c).blend, 1.0);
1673        assert_eq!(a.blur, 4.0);
1674        let flat = pose(2.0, 67.2, &OptionWheelConfig { tilt: 0.0, ..c });
1675        assert_eq!(flat.y, 134.4);
1676        assert_eq!(flat.angle, 0.0);
1677        let hit = Hit {
1678            index: 0,
1679            anchor: point(px(80.0), px(200.0)),
1680            width: 200.0,
1681            font: 48.0,
1682            angle: 0.2,
1683            right: false,
1684        };
1685        assert!(hit.contains(point(
1686            px(80.0 + 100.0 * 0.2_f32.cos()),
1687            px(200.0 + 100.0 * 0.2_f32.sin())
1688        )));
1689        assert!(!hit.contains(point(px(0.0), px(0.0))));
1690    }
1691    #[test]
1692    fn option_wheel_config_and_svg() {
1693        let c = OptionWheelConfig {
1694            font_size: f32::NAN,
1695            sound_volume: 3.0,
1696            ..Default::default()
1697        }
1698        .normalized();
1699        assert_eq!(c.font_size, 3.0);
1700        assert_eq!(c.sound_volume, 1.0);
1701        let (_, svg, _) = text_svg("A<&\"", "Segoe UI", 48.0, 200.0, false, 2.0);
1702        let svg = std::str::from_utf8(&svg).unwrap();
1703        assert!(svg.contains("feGaussianBlur"));
1704        assert!(svg.contains("A&lt;&amp;&quot;"));
1705    }
1706}