Skip to main content

fc_ui/capabilities/media/
crop_area.rs

1//! Image crop tool with draggable/resizable selection.
2
3use gpui::{prelude::FluentBuilder as _, *};
4
5use crate::capabilities::foundation::theme::use_theme;
6
7#[derive(Copy, Clone, Debug, PartialEq)]
8pub enum DragHandle {
9    None,
10    Move,
11    TopLeft,
12    TopRight,
13    BottomLeft,
14    BottomRight,
15    Top,
16    Bottom,
17    Left,
18    Right,
19}
20
21pub struct CropAreaState {
22    pub selection: Bounds<f32>,
23    is_dragging: bool,
24    drag_handle: DragHandle,
25    drag_start: Point<f32>,
26    selection_start: Bounds<f32>,
27    bounds: Option<Bounds<Pixels>>,
28}
29
30impl CropAreaState {
31    pub fn new(_cx: &mut Context<Self>) -> Self {
32        Self {
33            selection: Bounds::new(point(0.1, 0.1), size(0.8, 0.8)),
34            is_dragging: false,
35            drag_handle: DragHandle::None,
36            drag_start: Point::default(),
37            selection_start: Bounds::new(point(0.1, 0.1), size(0.8, 0.8)),
38            bounds: None,
39        }
40    }
41
42    pub fn get_selection(&self) -> Bounds<f32> {
43        self.selection
44    }
45
46    fn to_normalized(&self, pos: Point<Pixels>) -> Point<f32> {
47        if let Some(bounds) = self.bounds {
48            let x = (pos.x - bounds.left()) / bounds.size.width;
49            let y = (pos.y - bounds.top()) / bounds.size.height;
50            point(x, y)
51        } else {
52            Point::default()
53        }
54    }
55
56    fn hit_test(&self, norm: Point<f32>) -> DragHandle {
57        let sel = &self.selection;
58        let handle_size = 0.03;
59
60        let left = sel.origin.x;
61        let top = sel.origin.y;
62        let right = sel.origin.x + sel.size.width;
63        let bottom = sel.origin.y + sel.size.height;
64
65        if (norm.x - left).abs() < handle_size && (norm.y - top).abs() < handle_size {
66            return DragHandle::TopLeft;
67        }
68        if (norm.x - right).abs() < handle_size && (norm.y - top).abs() < handle_size {
69            return DragHandle::TopRight;
70        }
71        if (norm.x - left).abs() < handle_size && (norm.y - bottom).abs() < handle_size {
72            return DragHandle::BottomLeft;
73        }
74        if (norm.x - right).abs() < handle_size && (norm.y - bottom).abs() < handle_size {
75            return DragHandle::BottomRight;
76        }
77
78        if (norm.y - top).abs() < handle_size && norm.x > left && norm.x < right {
79            return DragHandle::Top;
80        }
81        if (norm.y - bottom).abs() < handle_size && norm.x > left && norm.x < right {
82            return DragHandle::Bottom;
83        }
84        if (norm.x - left).abs() < handle_size && norm.y > top && norm.y < bottom {
85            return DragHandle::Left;
86        }
87        if (norm.x - right).abs() < handle_size && norm.y > top && norm.y < bottom {
88            return DragHandle::Right;
89        }
90
91        if norm.x > left && norm.x < right && norm.y > top && norm.y < bottom {
92            return DragHandle::Move;
93        }
94
95        DragHandle::None
96    }
97
98    fn apply_drag(&mut self, norm: Point<f32>, min_size: f32, aspect_ratio: Option<f32>) {
99        let dx = norm.x - self.drag_start.x;
100        let dy = norm.y - self.drag_start.y;
101        let start = &self.selection_start;
102
103        match self.drag_handle {
104            DragHandle::Move => {
105                let new_x = (start.origin.x + dx).clamp(0.0, 1.0 - start.size.width);
106                let new_y = (start.origin.y + dy).clamp(0.0, 1.0 - start.size.height);
107                self.selection.origin.x = new_x;
108                self.selection.origin.y = new_y;
109            }
110            DragHandle::BottomRight => {
111                let mut new_w = (start.size.width + dx).max(min_size);
112                let mut new_h = (start.size.height + dy).max(min_size);
113                if let Some(ratio) = aspect_ratio {
114                    new_h = new_w / ratio;
115                }
116                new_w = new_w.min(1.0 - start.origin.x);
117                new_h = new_h.min(1.0 - start.origin.y);
118                self.selection.size.width = new_w;
119                self.selection.size.height = new_h;
120            }
121            DragHandle::TopLeft => {
122                let mut new_x = start.origin.x + dx;
123                let mut new_y = start.origin.y + dy;
124                let max_x = start.origin.x + start.size.width - min_size;
125                let max_y = start.origin.y + start.size.height - min_size;
126                new_x = new_x.clamp(0.0, max_x);
127                new_y = new_y.clamp(0.0, max_y);
128                let new_w = start.origin.x + start.size.width - new_x;
129                let new_h = start.origin.y + start.size.height - new_y;
130                if let Some(ratio) = aspect_ratio {
131                    let adj_h = new_w / ratio;
132                    self.selection = Bounds::new(
133                        point(new_x, start.origin.y + start.size.height - adj_h),
134                        size(new_w, adj_h),
135                    );
136                } else {
137                    self.selection = Bounds::new(point(new_x, new_y), size(new_w, new_h));
138                }
139            }
140            DragHandle::TopRight => {
141                let new_w = (start.size.width + dx)
142                    .max(min_size)
143                    .min(1.0 - start.origin.x);
144                let mut new_y = start.origin.y + dy;
145                let max_y = start.origin.y + start.size.height - min_size;
146                new_y = new_y.clamp(0.0, max_y);
147                let new_h = start.origin.y + start.size.height - new_y;
148                if let Some(ratio) = aspect_ratio {
149                    let adj_h = new_w / ratio;
150                    self.selection = Bounds::new(
151                        point(start.origin.x, start.origin.y + start.size.height - adj_h),
152                        size(new_w, adj_h),
153                    );
154                } else {
155                    self.selection = Bounds::new(point(start.origin.x, new_y), size(new_w, new_h));
156                }
157            }
158            DragHandle::BottomLeft => {
159                let mut new_x = start.origin.x + dx;
160                let max_x = start.origin.x + start.size.width - min_size;
161                new_x = new_x.clamp(0.0, max_x);
162                let new_w = start.origin.x + start.size.width - new_x;
163                let mut new_h = (start.size.height + dy)
164                    .max(min_size)
165                    .min(1.0 - start.origin.y);
166                if let Some(ratio) = aspect_ratio {
167                    new_h = new_w / ratio;
168                }
169                self.selection = Bounds::new(point(new_x, start.origin.y), size(new_w, new_h));
170            }
171            DragHandle::Top => {
172                let mut new_y = start.origin.y + dy;
173                let max_y = start.origin.y + start.size.height - min_size;
174                new_y = new_y.clamp(0.0, max_y);
175                let new_h = start.origin.y + start.size.height - new_y;
176                self.selection.origin.y = new_y;
177                self.selection.size.height = new_h;
178            }
179            DragHandle::Bottom => {
180                let new_h = (start.size.height + dy)
181                    .max(min_size)
182                    .min(1.0 - start.origin.y);
183                self.selection.size.height = new_h;
184            }
185            DragHandle::Left => {
186                let mut new_x = start.origin.x + dx;
187                let max_x = start.origin.x + start.size.width - min_size;
188                new_x = new_x.clamp(0.0, max_x);
189                let new_w = start.origin.x + start.size.width - new_x;
190                self.selection.origin.x = new_x;
191                self.selection.size.width = new_w;
192            }
193            DragHandle::Right => {
194                let new_w = (start.size.width + dx)
195                    .max(min_size)
196                    .min(1.0 - start.origin.x);
197                self.selection.size.width = new_w;
198            }
199            DragHandle::None => {}
200        }
201    }
202}
203
204impl Render for CropAreaState {
205    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
206        Empty
207    }
208}
209
210#[derive(Clone)]
211struct CropPaintData {
212    selection: Bounds<f32>,
213    dim_color: Hsla,
214    border_color: Hsla,
215    handle_color: Hsla,
216}
217
218#[derive(IntoElement)]
219pub struct CropArea {
220    id: ElementId,
221    state: Entity<CropAreaState>,
222    aspect_ratio: Option<f32>,
223    min_size: f32,
224    style: StyleRefinement,
225    children: Vec<AnyElement>,
226}
227
228impl CropArea {
229    pub fn new(id: impl Into<ElementId>, state: Entity<CropAreaState>) -> Self {
230        Self {
231            id: id.into(),
232            state,
233            aspect_ratio: None,
234            min_size: 0.05,
235            style: StyleRefinement::default(),
236            children: Vec::new(),
237        }
238    }
239
240    pub fn aspect_ratio(mut self, ratio: f32) -> Self {
241        self.aspect_ratio = Some(ratio);
242        self
243    }
244
245    pub fn min_size(mut self, min: f32) -> Self {
246        self.min_size = min.clamp(0.01, 0.5);
247        self
248    }
249}
250
251impl Styled for CropArea {
252    fn style(&mut self) -> &mut StyleRefinement {
253        &mut self.style
254    }
255}
256
257impl ParentElement for CropArea {
258    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
259        self.children.extend(elements);
260    }
261}
262
263impl RenderOnce for CropArea {
264    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
265        let theme = use_theme(cx);
266        let user_style = self.style;
267        let selection = self.state.read(cx).selection;
268
269        let dim_color = hsla(0.0, 0.0, 0.0, 0.5);
270        let border_color = theme.tokens.primary;
271        let handle_color = theme.tokens.background;
272
273        let paint_data = CropPaintData {
274            selection,
275            dim_color,
276            border_color,
277            handle_color,
278        };
279
280        let state_down = self.state.clone();
281        let state_move = self.state.clone();
282        let state_up = self.state.clone();
283        let state_up_out = self.state.clone();
284        let min_size = self.min_size;
285        let aspect_ratio = self.aspect_ratio;
286
287        div()
288            .id(self.id)
289            .relative()
290            .overflow_hidden()
291            .cursor_crosshair()
292            .children(self.children)
293            .child(
294                canvas(
295                    move |_, _, _| paint_data,
296                    move |bounds, data, window, _cx| {
297                        let sel = &data.selection;
298                        let bw = bounds.size.width;
299                        let bh = bounds.size.height;
300
301                        let sel_left = bounds.left() + bw * sel.origin.x;
302                        let sel_top = bounds.top() + bh * sel.origin.y;
303                        let sel_w = bw * sel.size.width;
304                        let sel_h = bh * sel.size.height;
305
306                        let top_dim = Bounds::new(bounds.origin, size(bw, sel_top - bounds.top()));
307                        window.paint_quad(fill(top_dim, data.dim_color));
308
309                        let bottom_dim = Bounds::new(
310                            point(bounds.left(), sel_top + sel_h),
311                            size(bw, bounds.bottom() - (sel_top + sel_h)),
312                        );
313                        window.paint_quad(fill(bottom_dim, data.dim_color));
314
315                        let left_dim = Bounds::new(
316                            point(bounds.left(), sel_top),
317                            size(sel_left - bounds.left(), sel_h),
318                        );
319                        window.paint_quad(fill(left_dim, data.dim_color));
320
321                        let right_dim = Bounds::new(
322                            point(sel_left + sel_w, sel_top),
323                            size(bounds.right() - (sel_left + sel_w), sel_h),
324                        );
325                        window.paint_quad(fill(right_dim, data.dim_color));
326
327                        let border_w = px(2.0);
328                        window.paint_quad(PaintQuad {
329                            bounds: Bounds::new(point(sel_left, sel_top), size(sel_w, sel_h)),
330                            corner_radii: Corners::default(),
331                            background: gpui::transparent_black().into(),
332                            border_widths: Edges::all(border_w),
333                            border_color: data.border_color,
334                            border_style: BorderStyle::default(),
335                            continuous_corners: false,
336                            transform: Default::default(),
337                            blend_mode: Default::default(),
338                        });
339
340                        let handle_sz = px(8.0);
341                        let half = handle_sz * 0.5;
342                        let handle_corners: [(Pixels, Pixels); 4] = [
343                            (sel_left, sel_top),
344                            (sel_left + sel_w, sel_top),
345                            (sel_left, sel_top + sel_h),
346                            (sel_left + sel_w, sel_top + sel_h),
347                        ];
348
349                        for (hx, hy) in handle_corners {
350                            window.paint_quad(PaintQuad {
351                                bounds: Bounds::new(
352                                    point(hx - half, hy - half),
353                                    size(handle_sz, handle_sz),
354                                ),
355                                corner_radii: Corners::all(px(2.0)),
356                                background: data.handle_color.into(),
357                                border_widths: Edges::all(px(1.5)),
358                                border_color: data.border_color,
359                                border_style: BorderStyle::default(),
360                                continuous_corners: false,
361                                transform: Default::default(),
362                                blend_mode: Default::default(),
363                            });
364                        }
365                    },
366                )
367                .absolute()
368                .inset_0()
369                .size_full(),
370            )
371            .on_mouse_down(
372                MouseButton::Left,
373                move |event: &MouseDownEvent, _window, cx| {
374                    state_down.update(cx, |s, cx| {
375                        let norm = s.to_normalized(event.position);
376                        let handle = s.hit_test(norm);
377                        if handle != DragHandle::None {
378                            s.is_dragging = true;
379                            s.drag_handle = handle;
380                            s.drag_start = norm;
381                            s.selection_start = s.selection;
382                            cx.notify();
383                        }
384                    });
385                },
386            )
387            .on_mouse_move(move |event: &MouseMoveEvent, _window, cx| {
388                state_move.update(cx, |s, cx| {
389                    if s.is_dragging {
390                        let norm = s.to_normalized(event.position);
391                        s.apply_drag(norm, min_size, aspect_ratio);
392                        cx.notify();
393                    }
394                });
395            })
396            .on_mouse_up(
397                MouseButton::Left,
398                move |_event: &MouseUpEvent, _window, cx| {
399                    state_up.update(cx, |s, cx| {
400                        s.is_dragging = false;
401                        s.drag_handle = DragHandle::None;
402                        cx.notify();
403                    });
404                },
405            )
406            .on_mouse_up_out(
407                MouseButton::Left,
408                move |_event: &MouseUpEvent, _window, cx| {
409                    state_up_out.update(cx, |s, cx| {
410                        s.is_dragging = false;
411                        s.drag_handle = DragHandle::None;
412                        cx.notify();
413                    });
414                },
415            )
416            .map(|this: Stateful<Div>| {
417                let mut el = this;
418                el.style().refine(&user_style);
419                el
420            })
421    }
422}