ailloli_ui_widgets/chrome/
window_affordance.rs

1//! VR-friendly window affordance frame.
2//!
3//! This widget is a framework-level slate/window surface: it owns title-bar,
4//! chrome button, resize edge/corner hit zones, and visual feedback. Hosts can
5//! map emitted [`WindowAffordanceEvent`] values to desktop window operations or
6//! to OpenXR slate transforms.
7
8use std::rc::Rc;
9
10use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
11use ailloli_ui_core::event::Event;
12use ailloli_ui_core::geometry::{ClipShape, Constraints, Point, Rect, Size};
13use ailloli_ui_core::style::{
14    Border, BorderStyle, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
15};
16use ailloli_ui_core::{Color, FontId, Offset, TextStyle, Theme};
17use ailloli_ui_runtime::component::{ComponentNode, Context, IntoView, Signal, View, Widget};
18use ailloli_ui_runtime::input::{EventCtx, HoverCursorRole, ResizeEdge};
19use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutResult};
20use ailloli_ui_runtime::scene::PaintCtx;
21use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawRRect, DrawRect};
22
23use super::{hit_resize_frame, hit_window_drag_region};
24use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
25use crate::text::Text;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28/// Semantic operation represented by a chrome hit target.
29///
30/// Edge and corner variants retain the exact host [`ResizeEdge`].
31///
32/// # Examples
33///
34/// ```
35/// use ailloli_ui_runtime::input::ResizeEdge;
36/// use ailloli_ui_widgets::chrome::WindowAffordanceKind;
37/// assert_eq!(WindowAffordanceKind::ResizeCorner(ResizeEdge::NW), WindowAffordanceKind::ResizeCorner(ResizeEdge::NW));
38/// ```
39pub enum WindowAffordanceKind {
40    /// Drag the complete window or spatial slate.
41    Move,
42    /// Resize from one cardinal edge.
43    ResizeEdge(ResizeEdge),
44    /// Resize from one diagonal corner.
45    ResizeCorner(ResizeEdge),
46    /// Request closure.
47    Close,
48    /// Request minimization.
49    Minimize,
50    /// Host-defined follow/pin operation.
51    Follow,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55/// Visual interaction state of one affordance.
56///
57/// # Examples
58///
59/// ```
60/// use ailloli_ui_widgets::chrome::WindowAffordanceState;
61/// assert_ne!(WindowAffordanceState::Idle, WindowAffordanceState::Active);
62/// ```
63pub enum WindowAffordanceState {
64    /// Neither hovered nor pressed.
65    Idle,
66    /// Pointer is over the affordance.
67    Hovered,
68    /// Pointer is pressing or dragging the affordance.
69    Active,
70    /// Operation is unavailable; currently used by styling helpers.
71    Disabled,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75/// Lifecycle phase emitted for an affordance interaction.
76///
77/// # Examples
78///
79/// ```
80/// use ailloli_ui_widgets::chrome::WindowAffordanceDragPhase;
81/// assert_ne!(WindowAffordanceDragPhase::Start, WindowAffordanceDragPhase::End);
82/// ```
83pub enum WindowAffordanceDragPhase {
84    /// Initial left-button press on a movable/resizable region.
85    Start,
86    /// Pointer motion while a drag is captured.
87    Drag,
88    /// Left-button release after a drag.
89    End,
90    /// Press and release on the same non-drag chrome control.
91    Click,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq)]
95/// Provider-neutral chrome interaction emitted in screen logical pixels.
96///
97/// `delta` is relative to the previous drag event and `total_delta` is relative
98/// to the drag start. Clicks use zero offsets.
99///
100/// # Examples
101///
102/// ```
103/// use ailloli_ui_core::{Offset, Point};
104/// use ailloli_ui_widgets::chrome::{WindowAffordanceDragPhase, WindowAffordanceEvent, WindowAffordanceKind};
105/// let event = WindowAffordanceEvent {
106///     kind: WindowAffordanceKind::Move,
107///     phase: WindowAffordanceDragPhase::Drag,
108///     position: Point::new(12.0, 8.0),
109///     delta: Offset::new(2.0, 0.0),
110///     total_delta: Offset::new(4.0, 1.0),
111/// };
112/// assert_eq!(event.delta.x, 2.0);
113/// ```
114pub struct WindowAffordanceEvent {
115    /// Operation selected by hit testing.
116    pub kind: WindowAffordanceKind,
117    /// Press/drag/release/click lifecycle phase.
118    pub phase: WindowAffordanceDragPhase,
119    /// Current pointer position in screen logical pixels.
120    pub position: Point,
121    /// Logical-pixel displacement since the previous event.
122    pub delta: Offset,
123    /// Logical-pixel displacement since drag start.
124    pub total_delta: Offset,
125}
126
127#[derive(Debug, Clone, Copy, PartialEq)]
128/// Geometry and colors for [`WindowAffordanceFrame`].
129///
130/// All dimensions are logical pixels. The default uses a 38-pixel title bar,
131/// 12-pixel resize hit frame, three 24-pixel controls, and a 12-pixel radius.
132/// Values are sanitized only where consumed, so custom styles should use
133/// finite non-negative dimensions.
134///
135/// # Examples
136///
137/// ```
138/// use ailloli_ui_widgets::chrome::WindowAffordanceStyle;
139/// let style = WindowAffordanceStyle::default();
140/// assert_eq!(style.titlebar_height, 38.0);
141/// assert_eq!(style.resize_hit_thickness, 12.0);
142/// ```
143pub struct WindowAffordanceStyle {
144    /// Title-bar height in logical pixels.
145    pub titlebar_height: f32,
146    /// Square chrome-control extent in logical pixels.
147    pub control_size: f32,
148    /// Horizontal gap between chrome controls in logical pixels.
149    pub control_gap: f32,
150    /// Distance from the right bound to the close control.
151    pub control_margin: f32,
152    /// Invisible resize-hit frame thickness in logical pixels.
153    pub resize_hit_thickness: f32,
154    /// Visible resize-handle length in logical pixels.
155    pub resize_handle_length: f32,
156    /// Visible resize-handle thickness in logical pixels.
157    pub resize_handle_thickness: f32,
158    /// Frame corner radius in logical pixels.
159    pub radius: f32,
160    /// Content surface color.
161    pub background: Color,
162    /// Title-bar fill color.
163    pub titlebar_background: Color,
164    /// One-logical-pixel frame border color.
165    pub border: Color,
166    /// Outer frame shadow; inset shadows are skipped.
167    pub shadow: BoxShadow,
168    /// Idle chrome-control fill.
169    pub control_idle: Color,
170    /// Hovered chrome-control fill.
171    pub control_hover: Color,
172    /// Pressed chrome-control fill.
173    pub control_active: Color,
174    /// Destructive close-control hover fill.
175    pub close_hover: Color,
176    /// Idle visible resize-handle fill.
177    pub handle_idle: Color,
178    /// Hovered resize-handle fill.
179    pub handle_hover: Color,
180    /// Active resize-handle fill.
181    pub handle_active: Color,
182}
183
184/// Supplies the dark-theme defaults described by [`WindowAffordanceStyle`].
185impl Default for WindowAffordanceStyle {
186    fn default() -> Self {
187        let theme = Theme::default();
188        let palette = theme.palette();
189        Self {
190            titlebar_height: 38.0,
191            control_size: 24.0,
192            control_gap: 6.0,
193            control_margin: 8.0,
194            resize_hit_thickness: 12.0,
195            resize_handle_length: 56.0,
196            resize_handle_thickness: 3.0,
197            radius: 12.0,
198            background: palette.surface,
199            titlebar_background: Color::rgba(20, 28, 44, 0.96),
200            border: palette.border,
201            shadow: BoxShadow::new(0.0, 10.0, 26.0, 0.0, Color::rgba(0, 0, 0, 0.34)),
202            control_idle: Color::rgba(148, 163, 184, 0.24),
203            control_hover: Color::rgba(148, 163, 184, 0.42),
204            control_active: palette.accent,
205            close_hover: Color::rgba(239, 68, 68, 0.78),
206            handle_idle: Color::rgba(148, 163, 184, 0.18),
207            handle_hover: Color::rgba(45, 212, 191, 0.72),
208            handle_active: Color::rgba(45, 212, 191, 0.95),
209        }
210    }
211}
212
213/// Shared retained callback invoked for each emitted affordance event.
214type AffordanceHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, WindowAffordanceEvent)>;
215
216/// Retained frame that paints client chrome and emits provider-neutral actions.
217///
218/// The default logical window id is `"window-affordance"`; movement, resizing,
219/// and the three chrome controls are enabled. The optional content is placed
220/// below the title bar.
221///
222/// # Examples
223///
224/// ```
225/// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
226/// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Inspector");
227/// let _ = frame;
228/// ```
229pub struct WindowAffordanceFrame<A = ()> {
230    /// Outer logical sizing policy.
231    layout: LayoutStyle,
232    /// Parent-flex participation metadata.
233    flex_item: FlexItemStyle,
234    /// Logical host-window identity used by window commands.
235    logical_window_id: String,
236    /// User-visible title painted in the chrome row.
237    title: String,
238    /// Optional body view placed below the title bar.
239    content: Option<View<A>>,
240    /// Whether title-bar hit testing emits move gestures.
241    movable: bool,
242    /// Whether edge/corner hit testing emits resize gestures.
243    resizable: bool,
244    /// Whether close, minimize, and follow controls are painted and interactive.
245    show_controls: bool,
246    /// Chrome colors and logical-pixel geometry.
247    style: WindowAffordanceStyle,
248    /// Optional callback receiving semantic chrome events.
249    on_affordance: Option<AffordanceHandler<A>>,
250}
251
252crate::impl_layout_builders!(WindowAffordanceFrame);
253
254impl<A: 'static> WindowAffordanceFrame<A> {
255    /// Creates a default movable and resizable frame with `title`.
256    ///
257    /// Empty titles are accepted and displayed as empty text.
258    ///
259    /// # Examples
260    ///
261    /// ```
262    /// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
263    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Tools");
264    /// let _ = frame;
265    /// ```
266    pub fn new(title: impl Into<String>) -> Self {
267        let title = title.into();
268        Self {
269            layout: LayoutStyle::default(),
270            flex_item: FlexItemStyle::default(),
271            logical_window_id: "window-affordance".to_string(),
272            title,
273            content: None,
274            movable: true,
275            resizable: true,
276            show_controls: true,
277            style: WindowAffordanceStyle::default(),
278            on_affordance: None,
279        }
280    }
281
282    /// Sets the host logical id used by built-in minimize requests.
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
288    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Tools").logical_window_id("tools");
289    /// let _ = frame;
290    /// ```
291    pub fn logical_window_id(mut self, value: impl Into<String>) -> Self {
292        self.logical_window_id = value.into();
293        self
294    }
295
296    /// Installs the single child view below the title bar.
297    ///
298    /// Repeated calls replace the previous child.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use ailloli_ui_widgets::{chrome::WindowAffordanceFrame, text::Text};
304    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Tools").content(Text::new("Body"));
305    /// let _ = frame;
306    /// ```
307    pub fn content(mut self, content: impl IntoView<A>) -> Self {
308        self.content = Some(content.into_view());
309        self
310    }
311
312    /// Enables or disables title-bar move hit testing.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
318    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Fixed").movable(false);
319    /// let _ = frame;
320    /// ```
321    pub fn movable(mut self, value: bool) -> Self {
322        self.movable = value;
323        self
324    }
325
326    /// Enables or disables edge and corner resize hit testing and handles.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
332    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Fixed").resizable(false);
333    /// let _ = frame;
334    /// ```
335    pub fn resizable(mut self, value: bool) -> Self {
336        self.resizable = value;
337        self
338    }
339
340    /// Shows or hides close, minimize, and follow controls.
341    ///
342    /// Hiding controls removes both paint and hit targets.
343    ///
344    /// # Examples
345    ///
346    /// ```
347    /// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
348    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Bare").show_controls(false);
349    /// let _ = frame;
350    /// ```
351    pub fn show_controls(mut self, value: bool) -> Self {
352        self.show_controls = value;
353        self
354    }
355
356    /// Replaces every chrome geometry and color token.
357    ///
358    /// # Examples
359    ///
360    /// ```
361    /// use ailloli_ui_widgets::chrome::{WindowAffordanceFrame, WindowAffordanceStyle};
362    /// let style = WindowAffordanceStyle { titlebar_height: 42.0, ..Default::default() };
363    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Tools").window_affordance_style(style);
364    /// let _ = frame;
365    /// ```
366    pub fn window_affordance_style(mut self, style: WindowAffordanceStyle) -> Self {
367        self.style = style;
368        self
369    }
370
371    /// Maps each emitted event into an application action.
372    ///
373    /// # Examples
374    ///
375    /// ```
376    /// use ailloli_ui_widgets::chrome::{WindowAffordanceEvent, WindowAffordanceFrame};
377    /// enum Action { Chrome(WindowAffordanceEvent) }
378    /// let frame = WindowAffordanceFrame::new("Tools").on_affordance(Action::Chrome);
379    /// let _: WindowAffordanceFrame<Action> = frame;
380    /// ```
381    pub fn on_affordance(mut self, f: impl Fn(WindowAffordanceEvent) -> A + 'static) -> Self {
382        self.on_affordance = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
383        self
384    }
385
386    /// Handles emitted events with mutable runtime event context access.
387    ///
388    /// # Examples
389    ///
390    /// ```
391    /// use ailloli_ui_widgets::chrome::WindowAffordanceFrame;
392    /// let frame: WindowAffordanceFrame<()> = WindowAffordanceFrame::new("Tools")
393    ///     .on_affordance_ctx(|_ctx, _event| {});
394    /// let _ = frame;
395    /// ```
396    pub fn on_affordance_ctx(
397        mut self,
398        f: impl Fn(&mut EventCtx<A>, WindowAffordanceEvent) + 'static,
399    ) -> Self {
400        self.on_affordance = Some(Rc::new(f));
401        self
402    }
403}
404
405/// Converts the builder into its retained frame component.
406impl<A: 'static> IntoView<A> for WindowAffordanceFrame<A> {
407    fn into_view(self) -> View<A> {
408        View::component(WindowAffordanceFrameComponent {
409            layout: self.layout,
410            flex_item: self.flex_item,
411            logical_window_id: self.logical_window_id,
412            title: self.title,
413            content: self.content,
414            movable: self.movable,
415            resizable: self.resizable,
416            show_controls: self.show_controls,
417            style: self.style,
418            on_affordance: self.on_affordance,
419        })
420    }
421}
422
423#[derive(Debug, Clone, Copy, PartialEq)]
424/// Captured drag origin and previous position for delta generation.
425struct AffordanceDragState {
426    /// Move, edge, or corner affordance captured by the press.
427    kind: WindowAffordanceKind,
428    /// Logical window-coordinate pointer position at drag start.
429    start: Point,
430    /// Pointer position used as the next incremental-delta origin.
431    last: Point,
432}
433
434/// Retained builder snapshot rebuilt into the widget and its child views.
435struct WindowAffordanceFrameComponent<A> {
436    /// Outer logical sizing policy.
437    layout: LayoutStyle,
438    /// Parent-flex participation metadata.
439    flex_item: FlexItemStyle,
440    /// Logical host-window identity used by window commands.
441    logical_window_id: String,
442    /// User-visible title painted in the chrome row.
443    title: String,
444    /// Optional body view placed below the title bar.
445    content: Option<View<A>>,
446    /// Whether title-bar hit testing emits move gestures.
447    movable: bool,
448    /// Whether edge/corner hit testing emits resize gestures.
449    resizable: bool,
450    /// Whether window controls are painted and interactive.
451    show_controls: bool,
452    /// Chrome colors and logical-pixel geometry.
453    style: WindowAffordanceStyle,
454    /// Optional retained semantic-event callback.
455    on_affordance: Option<AffordanceHandler<A>>,
456}
457
458/// Builds the title/content children and persistent interaction signals.
459impl<A: 'static> ComponentNode<A> for WindowAffordanceFrameComponent<A> {
460    fn build(&self, context: &mut Context<A>) -> View<A> {
461        let mut children = Vec::new();
462        children.push(
463            Text::new(self.title.clone())
464                .style(TextStyle::new(
465                    FontId::Ui,
466                    15,
467                    Color::rgba(236, 243, 255, 0.96),
468                ))
469                .nowrap()
470                .into_view(),
471        );
472        if let Some(content) = self.content.clone() {
473            children.push(content);
474        }
475        let widget = WindowAffordanceFrameWidget {
476            layout: self.layout,
477            logical_window_id: self.logical_window_id.clone(),
478            movable: self.movable,
479            resizable: self.resizable,
480            show_controls: self.show_controls,
481            style: self.style,
482            on_affordance: self.on_affordance.clone(),
483            hover: context.signal(None),
484            press: context.signal(None),
485            drag: context.signal(None),
486        };
487        finish_view_sized(
488            View::node(widget, children),
489            self.flex_item,
490            LayoutSizeHint::from_layout(self.layout),
491        )
492    }
493}
494
495/// Layout, paint, and pointer-event implementation for the chrome frame.
496struct WindowAffordanceFrameWidget<A> {
497    /// Outer logical sizing policy.
498    layout: LayoutStyle,
499    /// Logical host-window identity used by built-in commands.
500    logical_window_id: String,
501    /// Whether title-bar hit testing emits move gestures.
502    movable: bool,
503    /// Whether edge/corner hit testing emits resize gestures.
504    resizable: bool,
505    /// Whether window controls are painted and interactive.
506    show_controls: bool,
507    /// Chrome colors and logical-pixel geometry.
508    style: WindowAffordanceStyle,
509    /// Optional retained semantic-event callback.
510    on_affordance: Option<AffordanceHandler<A>>,
511    /// Affordance currently under the pointer.
512    hover: Signal<Option<WindowAffordanceKind>>,
513    /// Affordance captured by the active press before dragging.
514    press: Signal<Option<WindowAffordanceKind>>,
515    /// Active move/resize gesture state.
516    drag: Signal<Option<AffordanceDragState>>,
517}
518
519/// Implements retained chrome geometry, painting, capture, and cursor roles.
520impl<A: 'static> Widget<A> for WindowAffordanceFrameWidget<A> {
521    fn debug_name(&self) -> &'static str {
522        "WindowAffordanceFrame"
523    }
524
525    fn layout(
526        &self,
527        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
528        ctx: &mut LayoutCtx<'_>,
529        children: &mut [LayoutChild],
530        constraints: Constraints,
531    ) -> LayoutResult {
532        let size = apply_layout_size(Size::new(520.0, 340.0), self.layout, constraints);
533        let titlebar_h = self.style.titlebar_height.min(size.h).max(0.0);
534        let content_h = (size.h - titlebar_h).max(0.0);
535        let mut child_layouts = Vec::new();
536
537        if let Some(title) = children.first_mut() {
538            let max_title_w = (size.w
539                - self.style.control_margin * 2.0
540                - self.style.control_size * 3.0
541                - self.style.control_gap * 2.0
542                - 20.0)
543                .max(0.0);
544            let title_layout = title.layout(
545                engine,
546                ctx,
547                Constraints {
548                    min_w: 0.0,
549                    max_w: max_title_w,
550                    min_h: 0.0,
551                    max_h: titlebar_h,
552                },
553            );
554            let title_y = ((titlebar_h - title_layout.size.h) * 0.5).max(0.0);
555            child_layouts.push(ChildLayout {
556                offset: Offset::new(16.0, title_y),
557                size: title_layout.size,
558                paint_bounds: Rect::new(16.0, title_y, title_layout.size.w, title_layout.size.h),
559                visual_bounds: Rect::new(16.0, title_y, title_layout.size.w, title_layout.size.h),
560            });
561        }
562
563        if let Some(content) = children.get_mut(1) {
564            let _ = content.layout(engine, ctx, Constraints::tight(size.w, content_h));
565            child_layouts.push(ChildLayout {
566                offset: Offset::new(0.0, titlebar_h),
567                size: Size::new(size.w, content_h),
568                paint_bounds: Rect::new(0.0, titlebar_h, size.w, content_h),
569                visual_bounds: Rect::new(0.0, titlebar_h, size.w, content_h),
570            });
571        }
572
573        let bounds = Rect::new(0.0, 0.0, size.w, size.h);
574        LayoutResult {
575            size,
576            children: child_layouts,
577            paint_bounds: bounds,
578            visual_bounds: self.style.shadow.paint_bounds(bounds),
579            overlay_hit_bounds: Vec::new(),
580            clip: Some(ClipShape::round_rect(bounds, self.style.radius)),
581            is_window_root_clip: true,
582            artifact: None,
583        }
584    }
585
586    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
587        if !self.style.shadow.inset && self.style.shadow.color.a > 0.0 {
588            ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
589                rect: bounds,
590                radius: Radius::uniform(self.style.radius),
591                shadow: self.style.shadow,
592            }));
593        }
594        ctx.push(DrawCmd::RRect(DrawRRect {
595            rect: bounds,
596            radius: self.style.radius,
597            color: self.style.background,
598        }));
599        ctx.push(DrawCmd::Rect(DrawRect {
600            rect: titlebar_rect(bounds, &self.style),
601            color: self.style.titlebar_background,
602        }));
603        ctx.push(DrawCmd::Border(DrawBorder {
604            rect: bounds,
605            radius: Radius::uniform(self.style.radius),
606            border: Border {
607                widths: ailloli_ui_core::EdgeInsets::all(1.0),
608                colors: ailloli_ui_core::style::EdgeColors::all(self.style.border),
609                style: BorderStyle::Solid,
610            },
611        }));
612
613        if self.show_controls {
614            for (kind, rect) in chrome_control_rects(bounds, &self.style) {
615                let state =
616                    affordance_state(kind, self.hover.read(), self.press.read(), self.drag.read());
617                let color = control_color(kind, state, &self.style);
618                ctx.push(DrawCmd::RRect(DrawRRect {
619                    rect,
620                    radius: 5.0,
621                    color,
622                }));
623            }
624        }
625
626        if self.resizable {
627            for (kind, rect) in resize_handle_rects(bounds, &self.style) {
628                let state =
629                    affordance_state(kind, self.hover.read(), self.press.read(), self.drag.read());
630                let color = match state {
631                    WindowAffordanceState::Active => self.style.handle_active,
632                    WindowAffordanceState::Hovered => self.style.handle_hover,
633                    WindowAffordanceState::Disabled => Color::TRANSPARENT,
634                    WindowAffordanceState::Idle => self.style.handle_idle,
635                };
636                if color.a > 0.0 {
637                    ctx.push(DrawCmd::RRect(DrawRRect {
638                        rect,
639                        radius: self.style.resize_handle_thickness,
640                        color,
641                    }));
642                }
643            }
644        }
645    }
646
647    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
648        match event {
649            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
650                if let Some(drag) = self.drag.read() {
651                    let event = drag_event(
652                        drag.kind,
653                        WindowAffordanceDragPhase::Drag,
654                        drag.start,
655                        drag.last,
656                        *pos,
657                    );
658                    self.emit(ctx, event);
659                    self.drag.set(Some(AffordanceDragState {
660                        kind: drag.kind,
661                        start: drag.start,
662                        last: *pos,
663                    }));
664                    ctx.request_repaint();
665                    ctx.stop_propagation();
666                    return;
667                }
668
669                let next = classify_window_affordance_hit(
670                    bounds,
671                    &self.style,
672                    *pos,
673                    self.movable,
674                    self.resizable,
675                    self.show_controls,
676                );
677                if self.hover.read() != next {
678                    self.hover.set(next);
679                    ctx.request_repaint();
680                }
681            }
682            Event::Pointer(PointerEvent::Button {
683                pos,
684                button: MouseButton::Left,
685                pressed: true,
686                ..
687            }) => {
688                let Some(kind) = classify_window_affordance_hit(
689                    bounds,
690                    &self.style,
691                    *pos,
692                    self.movable,
693                    self.resizable,
694                    self.show_controls,
695                ) else {
696                    return;
697                };
698                self.press.set(Some(kind));
699                match kind {
700                    WindowAffordanceKind::Move
701                    | WindowAffordanceKind::ResizeEdge(_)
702                    | WindowAffordanceKind::ResizeCorner(_) => {
703                        self.drag.set(Some(AffordanceDragState {
704                            kind,
705                            start: *pos,
706                            last: *pos,
707                        }));
708                        self.emit(
709                            ctx,
710                            drag_event(kind, WindowAffordanceDragPhase::Start, *pos, *pos, *pos),
711                        );
712                    }
713                    WindowAffordanceKind::Close
714                    | WindowAffordanceKind::Minimize
715                    | WindowAffordanceKind::Follow => {}
716                }
717                ctx.request_repaint();
718                ctx.stop_propagation();
719            }
720            Event::Pointer(PointerEvent::Button {
721                pos,
722                button: MouseButton::Left,
723                pressed: false,
724                ..
725            }) => {
726                if let Some(drag) = self.drag.read() {
727                    self.emit(
728                        ctx,
729                        drag_event(
730                            drag.kind,
731                            WindowAffordanceDragPhase::End,
732                            drag.start,
733                            drag.last,
734                            *pos,
735                        ),
736                    );
737                    self.drag.set(None);
738                    self.press.set(None);
739                    ctx.request_repaint();
740                    ctx.stop_propagation();
741                    return;
742                }
743
744                let pressed = self.press.read();
745                self.press.set(None);
746                if let Some(kind) = pressed {
747                    let released = classify_window_affordance_hit(
748                        bounds,
749                        &self.style,
750                        *pos,
751                        self.movable,
752                        self.resizable,
753                        self.show_controls,
754                    );
755                    if released == Some(kind) {
756                        self.default_chrome_action(ctx, kind);
757                        self.emit(
758                            ctx,
759                            WindowAffordanceEvent {
760                                kind,
761                                phase: WindowAffordanceDragPhase::Click,
762                                position: *pos,
763                                delta: Offset::new(0.0, 0.0),
764                                total_delta: Offset::new(0.0, 0.0),
765                            },
766                        );
767                    }
768                    ctx.request_repaint();
769                    ctx.stop_propagation();
770                }
771            }
772            _ => {}
773        }
774    }
775
776    fn hover_cursor_role_at(
777        &self,
778        bounds: Rect,
779        _layout: &LayoutResult,
780        pos: Point,
781    ) -> HoverCursorRole {
782        match classify_window_affordance_hit(
783            bounds,
784            &self.style,
785            pos,
786            self.movable,
787            self.resizable,
788            self.show_controls,
789        ) {
790            Some(WindowAffordanceKind::ResizeEdge(ResizeEdge::E | ResizeEdge::W))
791            | Some(WindowAffordanceKind::ResizeCorner(ResizeEdge::NE | ResizeEdge::SW)) => {
792                HoverCursorRole::ResizeX
793            }
794            Some(WindowAffordanceKind::ResizeEdge(ResizeEdge::N | ResizeEdge::S))
795            | Some(WindowAffordanceKind::ResizeCorner(ResizeEdge::NW | ResizeEdge::SE)) => {
796                HoverCursorRole::ResizeY
797            }
798            _ => HoverCursorRole::Inherit,
799        }
800    }
801}
802
803/// Callback dispatch and built-in host chrome actions.
804impl<A: 'static> WindowAffordanceFrameWidget<A> {
805    /// Forwards a semantic chrome event to the optional application callback.
806    fn emit(&self, ctx: &mut EventCtx<A>, event: WindowAffordanceEvent) {
807        if let Some(handler) = &self.on_affordance {
808            handler(ctx, event);
809        }
810    }
811
812    /// Executes close/minimize host commands when no custom behavior is needed.
813    fn default_chrome_action(&self, ctx: &EventCtx<A>, kind: WindowAffordanceKind) {
814        match kind {
815            WindowAffordanceKind::Close => ctx.request_close(),
816            WindowAffordanceKind::Minimize => {
817                ctx.request_minimize_window(self.logical_window_id.clone())
818            }
819            _ => {}
820        }
821    }
822}
823
824/// Resolves a point to the highest-priority enabled chrome affordance.
825///
826/// Points outside `bounds` return `None`. Visible controls win over resize
827/// regions, corners win over edges, and move is considered last. Dimensions
828/// are interpreted as screen logical pixels.
829///
830/// # Examples
831///
832/// ```
833/// use ailloli_ui_core::{Point, Rect};
834/// use ailloli_ui_widgets::chrome::{classify_window_affordance_hit, WindowAffordanceKind, WindowAffordanceStyle};
835/// let hit = classify_window_affordance_hit(
836///     Rect::new(0.0, 0.0, 320.0, 220.0),
837///     &WindowAffordanceStyle::default(),
838///     Point::new(80.0, 20.0),
839///     true,
840///     true,
841///     true,
842/// );
843/// assert_eq!(hit, Some(WindowAffordanceKind::Move));
844/// ```
845pub fn classify_window_affordance_hit(
846    bounds: Rect,
847    style: &WindowAffordanceStyle,
848    pos: Point,
849    movable: bool,
850    resizable: bool,
851    show_controls: bool,
852) -> Option<WindowAffordanceKind> {
853    if !bounds.contains(pos.x, pos.y) {
854        return None;
855    }
856    if show_controls {
857        for (kind, rect) in chrome_control_rects(bounds, style) {
858            if rect.contains(pos.x, pos.y) {
859                return Some(kind);
860            }
861        }
862    }
863    if let Some(edge) = hit_resize_frame(bounds, style.resize_hit_thickness, pos, resizable) {
864        return Some(match edge {
865            ResizeEdge::NE | ResizeEdge::NW | ResizeEdge::SE | ResizeEdge::SW => {
866                WindowAffordanceKind::ResizeCorner(edge)
867            }
868            edge => WindowAffordanceKind::ResizeEdge(edge),
869        });
870    }
871    if hit_window_drag_region(titlebar_rect(bounds, style), pos, movable) {
872        return Some(WindowAffordanceKind::Move);
873    }
874    None
875}
876
877/// Builds one event with incremental and start-relative pointer deltas.
878fn drag_event(
879    kind: WindowAffordanceKind,
880    phase: WindowAffordanceDragPhase,
881    start: Point,
882    last: Point,
883    pos: Point,
884) -> WindowAffordanceEvent {
885    WindowAffordanceEvent {
886        kind,
887        phase,
888        position: pos,
889        delta: Offset::new(pos.x - last.x, pos.y - last.y),
890        total_delta: Offset::new(pos.x - start.x, pos.y - start.y),
891    }
892}
893
894/// Resolves pressed/dragged state before hover and otherwise returns idle.
895fn affordance_state(
896    kind: WindowAffordanceKind,
897    hover: Option<WindowAffordanceKind>,
898    press: Option<WindowAffordanceKind>,
899    drag: Option<AffordanceDragState>,
900) -> WindowAffordanceState {
901    if drag.is_some_and(|state| state.kind == kind) || press == Some(kind) {
902        WindowAffordanceState::Active
903    } else if hover == Some(kind) {
904        WindowAffordanceState::Hovered
905    } else {
906        WindowAffordanceState::Idle
907    }
908}
909
910/// Selects a chrome-control fill from kind and interaction state.
911fn control_color(
912    kind: WindowAffordanceKind,
913    state: WindowAffordanceState,
914    style: &WindowAffordanceStyle,
915) -> Color {
916    match (kind, state) {
917        (_, WindowAffordanceState::Active) => style.control_active,
918        (WindowAffordanceKind::Close, WindowAffordanceState::Hovered) => style.close_hover,
919        (_, WindowAffordanceState::Hovered) => style.control_hover,
920        (_, WindowAffordanceState::Disabled) => Color::TRANSPARENT,
921        _ => style.control_idle,
922    }
923}
924
925/// Clamps title-bar height to the non-negative frame height.
926fn titlebar_rect(bounds: Rect, style: &WindowAffordanceStyle) -> Rect {
927    Rect::new(
928        bounds.x,
929        bounds.y,
930        bounds.w,
931        style.titlebar_height.min(bounds.h).max(0.0),
932    )
933}
934
935/// Places close, minimize, and follow controls from right to left.
936fn chrome_control_rects(
937    bounds: Rect,
938    style: &WindowAffordanceStyle,
939) -> [(WindowAffordanceKind, Rect); 3] {
940    let size = style
941        .control_size
942        .max(1.0)
943        .min(style.titlebar_height.max(1.0));
944    let y = bounds.y + (style.titlebar_height - size).max(0.0) * 0.5;
945    let right = bounds.right() - style.control_margin;
946    let step = size + style.control_gap.max(0.0);
947    [
948        (
949            WindowAffordanceKind::Close,
950            Rect::new(right - size, y, size, size),
951        ),
952        (
953            WindowAffordanceKind::Minimize,
954            Rect::new(right - size - step, y, size, size),
955        ),
956        (
957            WindowAffordanceKind::Follow,
958            Rect::new(right - size - step * 2.0, y, size, size),
959        ),
960    ]
961}
962
963/// Produces four edge and four corner indicator rectangles.
964fn resize_handle_rects(
965    bounds: Rect,
966    style: &WindowAffordanceStyle,
967) -> [(WindowAffordanceKind, Rect); 8] {
968    let l = style.resize_handle_length.min(bounds.w * 0.3).max(8.0);
969    let t = style.resize_handle_thickness.max(1.0);
970    let mid_x = bounds.x + (bounds.w - l) * 0.5;
971    let mid_y = bounds.y + (bounds.h - l) * 0.5;
972    [
973        (
974            WindowAffordanceKind::ResizeEdge(ResizeEdge::N),
975            Rect::new(mid_x, bounds.y + 2.0, l, t),
976        ),
977        (
978            WindowAffordanceKind::ResizeEdge(ResizeEdge::S),
979            Rect::new(mid_x, bounds.bottom() - t - 2.0, l, t),
980        ),
981        (
982            WindowAffordanceKind::ResizeEdge(ResizeEdge::W),
983            Rect::new(bounds.x + 2.0, mid_y, t, l),
984        ),
985        (
986            WindowAffordanceKind::ResizeEdge(ResizeEdge::E),
987            Rect::new(bounds.right() - t - 2.0, mid_y, t, l),
988        ),
989        (
990            WindowAffordanceKind::ResizeCorner(ResizeEdge::NW),
991            Rect::new(bounds.x + 2.0, bounds.y + 2.0, l * 0.45, t),
992        ),
993        (
994            WindowAffordanceKind::ResizeCorner(ResizeEdge::NE),
995            Rect::new(bounds.right() - l * 0.45 - 2.0, bounds.y + 2.0, l * 0.45, t),
996        ),
997        (
998            WindowAffordanceKind::ResizeCorner(ResizeEdge::SW),
999            Rect::new(bounds.x + 2.0, bounds.bottom() - t - 2.0, l * 0.45, t),
1000        ),
1001        (
1002            WindowAffordanceKind::ResizeCorner(ResizeEdge::SE),
1003            Rect::new(
1004                bounds.right() - l * 0.45 - 2.0,
1005                bounds.bottom() - t - 2.0,
1006                l * 0.45,
1007                t,
1008            ),
1009        ),
1010    ]
1011}
1012
1013#[cfg(test)]
1014/// Hit-priority and enablement regression scenarios for chrome geometry.
1015mod tests {
1016    use super::*;
1017
1018    /// Returns compact deterministic geometry shared by hit-test scenarios.
1019    fn style() -> WindowAffordanceStyle {
1020        WindowAffordanceStyle {
1021            titlebar_height: 40.0,
1022            control_size: 20.0,
1023            control_margin: 10.0,
1024            resize_hit_thickness: 10.0,
1025            ..Default::default()
1026        }
1027    }
1028
1029    #[test]
1030    fn window_affordance_hit_titlebar_move() {
1031        let hit = classify_window_affordance_hit(
1032            Rect::new(0.0, 0.0, 320.0, 220.0),
1033            &style(),
1034            Point::new(80.0, 20.0),
1035            true,
1036            true,
1037            true,
1038        );
1039        assert_eq!(hit, Some(WindowAffordanceKind::Move));
1040    }
1041
1042    #[test]
1043    fn window_affordance_controls_win_over_resize_border() {
1044        let bounds = Rect::new(0.0, 0.0, 320.0, 220.0);
1045        let close = chrome_control_rects(bounds, &style())[0].1;
1046        let hit = classify_window_affordance_hit(
1047            bounds,
1048            &style(),
1049            Point::new(close.x + 4.0, close.y + 4.0),
1050            true,
1051            true,
1052            true,
1053        );
1054        assert_eq!(hit, Some(WindowAffordanceKind::Close));
1055    }
1056
1057    #[test]
1058    fn window_affordance_hit_edges_and_corners() {
1059        let bounds = Rect::new(0.0, 0.0, 320.0, 220.0);
1060        let style = style();
1061        assert_eq!(
1062            classify_window_affordance_hit(bounds, &style, Point::new(3.0, 90.0), true, true, true,),
1063            Some(WindowAffordanceKind::ResizeEdge(ResizeEdge::W))
1064        );
1065        assert_eq!(
1066            classify_window_affordance_hit(bounds, &style, Point::new(3.0, 3.0), true, true, true,),
1067            Some(WindowAffordanceKind::ResizeCorner(ResizeEdge::NW))
1068        );
1069    }
1070
1071    #[test]
1072    fn window_affordance_content_has_no_frame_hit() {
1073        let hit = classify_window_affordance_hit(
1074            Rect::new(0.0, 0.0, 320.0, 220.0),
1075            &style(),
1076            Point::new(120.0, 80.0),
1077            true,
1078            true,
1079            true,
1080        );
1081        assert_eq!(hit, None);
1082    }
1083
1084    #[test]
1085    fn window_affordance_disable_move_or_resize() {
1086        let bounds = Rect::new(0.0, 0.0, 320.0, 220.0);
1087        let style = style();
1088        assert_eq!(
1089            classify_window_affordance_hit(
1090                bounds,
1091                &style,
1092                Point::new(80.0, 20.0),
1093                false,
1094                true,
1095                true,
1096            ),
1097            None
1098        );
1099        assert_eq!(
1100            classify_window_affordance_hit(
1101                bounds,
1102                &style,
1103                Point::new(3.0, 90.0),
1104                true,
1105                false,
1106                true,
1107            ),
1108            None
1109        );
1110    }
1111}