1use std::{cell::RefCell, rc::Rc};
23
24use arc_motion::{is_reduced_motion, motion_now};
25use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
26use gpui_kit::{
27 App, Bounds, ClipboardItem, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
28 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels,
29 RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
30 base::Button as BaseButton, canvas, div, point, prelude::*, px, rgb,
31};
32
33pub const SIGNATURE_PAD_WIDTH: f32 = 600.0;
35pub const SIGNATURE_PAD_HEIGHT: f32 = 260.0;
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum InkColor {
40 Black,
41 Blue,
42 Violet,
43}
44
45impl InkColor {
46 pub fn label(self) -> &'static str {
47 match self {
48 Self::Black => "Black ink",
49 Self::Blue => "Blue ink",
50 Self::Violet => "Violet ink",
51 }
52 }
53
54 pub fn export(self) -> &'static str {
55 match self {
56 Self::Black => "#17171a",
57 Self::Blue => "#1d3fae",
58 Self::Violet => "#5b35c8",
59 }
60 }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum InkWidth {
66 Fine,
67 Medium,
68 Bold,
69}
70
71impl InkWidth {
72 pub fn label(self) -> &'static str {
73 match self {
74 Self::Fine => "Fine",
75 Self::Medium => "Medium",
76 Self::Bold => "Bold",
77 }
78 }
79
80 pub fn size(self) -> f32 {
81 match self {
82 Self::Fine => 3.4,
83 Self::Medium => 5.6,
84 Self::Bold => 8.4,
85 }
86 }
87}
88
89#[derive(Clone, Copy, Debug, PartialEq)]
92pub struct InkPoint {
93 pub x: f32,
94 pub y: f32,
95 pub p: f32,
96 pub t: f64,
97}
98
99#[derive(Clone, Debug)]
101pub struct InkStroke {
102 pub id: SharedString,
103 pub points: Vec<InkPoint>,
104 pub color: InkColor,
105 pub width: InkWidth,
106}
107
108pub fn signature_stroke_outline(
112 input: &[InkPoint],
113 size: f32,
114 thinning: f32,
115 streamline: f32,
116 last: bool,
117) -> Vec<(f32, f32)> {
118 let Some(head) = input.first() else {
119 return Vec::new();
120 };
121 let mut pts: Vec<(f32, f32, f32)> = Vec::new(); let mut prev = (head.x, head.y);
123 pts.push((head.x, head.y, 0.5));
124 for (i, sample) in input.iter().enumerate().skip(1) {
125 let raw = (sample.x, sample.y);
126 let at = if i == input.len() - 1 && last {
127 raw
128 } else {
129 (
130 prev.0 + (raw.0 - prev.0) * (1.0 - streamline),
131 prev.1 + (raw.1 - prev.1) * (1.0 - streamline),
132 )
133 };
134 let dx = at.0 - prev.0;
135 let dy = at.1 - prev.1;
136 let d = (dx * dx + dy * dy).sqrt();
137 if d < 0.4 {
138 continue;
139 }
140 pts.push((at.0, at.1, 0.5));
141 prev = at;
142 }
143 let _ = thinning;
144
145 if pts.len() == 1 {
147 let r = (size * 0.9).max(0.6);
148 let mut out = Vec::with_capacity(18);
149 for i in 0..18 {
150 let a = i as f32 / 18.0 * std::f32::consts::TAU;
151 out.push((pts[0].0 + a.cos() * r, pts[0].1 + a.sin() * r));
152 }
153 return out;
154 }
155
156 let mut left: Vec<(f32, f32)> = Vec::new();
158 let mut right: Vec<(f32, f32)> = Vec::new();
159 for (i, &(x, y, pressure)) in pts.iter().enumerate() {
160 let step = if i == 0 {
162 0.0
163 } else {
164 let (px0, py0, _) = pts[i - 1];
165 let dx = x - px0;
166 let dy = y - py0;
167 (dx * dx + dy * dy).sqrt()
168 };
169 let speed = (step / size).min(1.0);
170 let target_pressure = (1.0 - speed).min(1.0);
171 let pressure = pressure + (target_pressure - pressure) * speed * 0.3;
172 let radius = (size * (0.5 - 0.62 * (0.5 - pressure))).max(0.12 * size);
173 let (dx2, dy2) = if i == 0 {
175 let next_pt = pts[1];
176 (next_pt.0 - x, next_pt.1 - y)
177 } else if i == pts.len() - 1 {
178 let prev_pt = pts[i - 1];
179 (x - prev_pt.0, y - prev_pt.1)
180 } else {
181 let prev_pt = pts[i - 1];
182 let next_pt = pts[i + 1];
183 let in_dx = x - prev_pt.0;
184 let in_dy = y - prev_pt.1;
185 let in_len = (in_dx * in_dx + in_dy * in_dy).sqrt().max(1e-6);
186 let out_dx = next_pt.0 - x;
187 let out_dy = next_pt.1 - y;
188 let out_len = (out_dx * out_dx + out_dy * out_dy).sqrt().max(1e-6);
189 let bx = in_dx / in_len + out_dx / out_len;
190 let by = in_dy / in_len + out_dy / out_len;
191 if bx * bx + by * by > 1e-4 {
192 (bx, by)
193 } else {
194 (out_dx, out_dy)
195 }
196 };
197 let len2 = (dx2 * dx2 + dy2 * dy2).sqrt().max(1e-6);
198 let nx = -dy2 / len2 * radius;
199 let ny = dx2 / len2 * radius;
200 left.push((x - nx, y - ny));
201 right.push((x + nx, y + ny));
202 }
203
204 let cap = |center: (f32, f32), from: (f32, f32), to: (f32, f32)| -> Vec<(f32, f32)> {
206 let mut out = Vec::with_capacity(12);
207 let dx = from.0 - center.0;
208 let dy = from.1 - center.1;
209 let r = (dx * dx + dy * dy).sqrt();
210 let start = dy.atan2(dx);
211 for k in 1..12 {
212 let a = start + std::f32::consts::PI * k as f32 / 12.0;
213 out.push((center.0 + a.cos() * r, center.1 + a.sin() * r));
214 }
215 out.push(to);
216 out
217 };
218 let end = *pts.last().expect("pts is non-empty");
219 let end_cap = cap((end.0, end.1), left[left.len() - 1], right[right.len() - 1]);
220 let start_cap = cap((pts[0].0, pts[0].1), right[0], left[0]);
221 let mut out = left;
222 out.extend(end_cap);
223 out.extend(right.into_iter().rev());
224 out.extend(start_cap);
225 out
226}
227
228pub fn signature_outline_to_path(points: &[(f32, f32)]) -> String {
231 if points.len() < 3 {
232 return String::new();
233 }
234 let round = |v: f32| (v * 100.0).round() / 100.0;
235 let mut d = format!("M{} {} Q", round(points[0].0), round(points[0].1));
236 for i in 0..points.len() {
237 let (x0, y0) = points[i];
238 let (x1, y1) = points[(i + 1) % points.len()];
239 d += &format!(
240 "{} {} {} {} ",
241 round(x0),
242 round(y0),
243 round((x0 + x1) / 2.0),
244 round((y0 + y1) / 2.0)
245 );
246 }
247 format!("{d}Z")
248}
249
250pub fn signature_stroke_path(stroke: &InkStroke, up_to_ms: Option<f64>) -> String {
252 let last = up_to_ms.is_none();
253 let points: Vec<InkPoint> = match up_to_ms {
254 None => stroke.points.clone(),
255 Some(up_to) => stroke
256 .points
257 .iter()
258 .copied()
259 .take_while(|p| p.t <= up_to)
260 .collect(),
261 };
262 if points.len() < 2 {
263 return String::new();
264 }
265 let outline = signature_stroke_outline(&points, stroke.width.size(), 0.62, 0.42, last);
266 signature_outline_to_path(&outline)
267}
268
269pub fn signature_to_svg(strokes: &[InkStroke], width: f32, height: f32) -> String {
271 let mut paths = String::new();
272 for stroke in strokes {
273 let d = signature_stroke_path(stroke, None);
274 if d.is_empty() {
275 continue;
276 }
277 paths += &format!(
278 "<path d=\"{}\" fill=\"none\" stroke=\"{}\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n",
279 d,
280 stroke.color.export()
281 );
282 }
283 format!(
284 "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"0 0 {width} {height}\">\n{paths}</svg>"
285 )
286}
287
288const MAX_HISTORY: usize = 60;
289
290impl InkColor {
291 pub const ALL: [InkColor; 3] = [InkColor::Black, InkColor::Blue, InkColor::Violet];
292
293 pub fn display_hsla(self, is_dark: bool, foreground: Hsla) -> Hsla {
294 match self {
295 Self::Black => foreground,
296 Self::Blue => {
297 let base: Hsla = rgb(0x1d3fae).into();
298 if is_dark {
299 oklab_mix(base, foreground, 0.42)
300 } else {
301 base
302 }
303 }
304 Self::Violet => {
305 let base: Hsla = rgb(0x5b35c8).into();
306 if is_dark {
307 oklab_mix(base, foreground, 0.42)
308 } else {
309 base
310 }
311 }
312 }
313 }
314}
315
316impl InkWidth {
317 pub const ALL: [InkWidth; 3] = [InkWidth::Fine, InkWidth::Medium, InkWidth::Bold];
318}
319
320#[derive(Clone)]
322struct InkHistory {
323 past: Vec<Vec<InkStroke>>,
324 present: Vec<InkStroke>,
325 future: Vec<Vec<InkStroke>>,
326}
327
328impl InkHistory {
329 fn new(initial: Vec<InkStroke>) -> Self {
330 Self {
331 past: Vec::new(),
332 present: initial,
333 future: Vec::new(),
334 }
335 }
336
337 fn commit(&mut self, next: Vec<InkStroke>) {
338 self.past.push(std::mem::replace(&mut self.present, next));
339 if self.past.len() > MAX_HISTORY {
340 let overflow = self.past.len() - MAX_HISTORY;
341 self.past.drain(0..overflow);
342 }
343 self.future.clear();
344 }
345
346 fn undo(&mut self) -> bool {
347 let Some(prev) = self.past.pop() else {
348 return false;
349 };
350 let curr = std::mem::replace(&mut self.present, prev);
351 self.future.insert(0, curr);
352 true
353 }
354
355 fn redo(&mut self) -> bool {
356 if self.future.is_empty() {
357 return false;
358 }
359 let next = self.future.remove(0);
360 let curr = std::mem::replace(&mut self.present, next);
361 self.past.push(curr);
362 true
363 }
364}
365
366#[derive(Clone)]
367struct LiveStroke {
368 stroke: InkStroke,
369 started_ms: f64,
370}
371
372#[derive(Clone)]
373struct ReplayState {
374 started_ms: f64,
375 offsets: Vec<f64>,
376 speed: f64,
377 total_ms: f64,
378}
379
380#[derive(Clone)]
381struct SignaturePadInternal {
382 history: InkHistory,
383 ink: InkColor,
384 width: InkWidth,
385 live: Option<LiveStroke>,
386 replay: Option<ReplayState>,
387 next_stroke_id: usize,
388 saved_svg_until_ms: Option<f64>,
389 pad_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
390 focus_handle: FocusHandle,
391}
392
393impl SignaturePadInternal {
394 fn new(initial_strokes: Vec<InkStroke>, ink: InkColor, width: InkWidth, cx: &mut App) -> Self {
395 Self {
396 next_stroke_id: initial_strokes.len() + 1,
397 history: InkHistory::new(initial_strokes),
398 ink,
399 width,
400 live: None,
401 replay: None,
402 saved_svg_until_ms: None,
403 pad_bounds: Rc::new(RefCell::new(None)),
404 focus_handle: cx.focus_handle(),
405 }
406 }
407
408 fn to_pad(&self, pos: gpui_kit::Point<Pixels>) -> Option<(f32, f32)> {
409 let bounds = (*self.pad_bounds.borrow())?;
410 let w = f32::from(bounds.size.width).max(1.0);
411 let h = f32::from(bounds.size.height).max(1.0);
412 let x = ((f32::from(pos.x) - f32::from(bounds.origin.x)) / w * SIGNATURE_PAD_WIDTH)
413 .clamp(0.0, SIGNATURE_PAD_WIDTH);
414 let y = ((f32::from(pos.y) - f32::from(bounds.origin.y)) / h * SIGNATURE_PAD_HEIGHT)
415 .clamp(0.0, SIGNATURE_PAD_HEIGHT);
416 Some((x, y))
417 }
418
419 fn start_replay(&mut self, now_ms: f64) {
420 if self.history.present.is_empty() || self.live.is_some() {
421 return;
422 }
423 let mut offsets = Vec::with_capacity(self.history.present.len());
424 let mut cursor = 0.0_f64;
425 for (index, stroke) in self.history.present.iter().enumerate() {
426 if index > 0 {
427 cursor += 120.0;
428 }
429 offsets.push(cursor);
430 let dur = stroke
431 .points
432 .last()
433 .map(|p| p.t.max(160.0))
434 .unwrap_or(160.0);
435 cursor += dur;
436 }
437 let speed = (cursor / 3200.0).max(1.0);
438 let total_ms = cursor + 120.0;
439 self.replay = Some(ReplayState {
440 started_ms: now_ms,
441 offsets,
442 speed,
443 total_ms,
444 });
445 }
446}
447
448#[derive(IntoElement)]
451pub struct SignaturePad {
452 id: ElementId,
453 label: SharedString,
454 signer: Option<SharedString>,
455 hint: SharedString,
456 strokes: Vec<InkStroke>,
457 ink: InkColor,
458 width: InkWidth,
459 disabled: bool,
460 width_px: Option<Pixels>,
461 #[allow(clippy::type_complexity)]
462 on_strokes_change: Option<Rc<dyn Fn(&[InkStroke], &mut Window, &mut App)>>,
463}
464
465#[derive(Clone, Debug)]
467pub struct InkStrokeDrawn {
468 pub stroke: InkStroke,
469}
470
471#[derive(Clone, Copy, Debug, PartialEq, Eq)]
473pub enum InkOption {
474 Color(InkColor),
475 Width(InkWidth),
476}
477
478impl SignaturePad {
479 pub fn new(id: impl Into<ElementId>) -> Self {
480 Self {
481 id: id.into(),
482 label: "Signature".into(),
483 signer: None,
484 hint: "Sign here".into(),
485 strokes: Vec::new(),
486 ink: InkColor::Black,
487 width: InkWidth::Medium,
488 disabled: false,
489 width_px: None,
490 on_strokes_change: None,
491 }
492 }
493
494 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
495 self.label = label.into();
496 self
497 }
498
499 pub fn signer(mut self, signer: impl Into<SharedString>) -> Self {
500 self.signer = Some(signer.into());
501 self
502 }
503
504 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
505 self.hint = hint.into();
506 self
507 }
508
509 pub fn strokes(mut self, strokes: Vec<InkStroke>) -> Self {
510 self.strokes = strokes;
511 self
512 }
513
514 pub fn ink(mut self, ink: InkColor) -> Self {
515 self.ink = ink;
516 self
517 }
518
519 pub fn stroke_width(mut self, width: InkWidth) -> Self {
520 self.width = width;
521 self
522 }
523
524 pub fn disabled(mut self, disabled: bool) -> Self {
525 self.disabled = disabled;
526 self
527 }
528
529 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
530 self.width_px = Some(width.into());
531 self
532 }
533
534 pub fn on_strokes_change(
535 mut self,
536 handler: impl Fn(&[InkStroke], &mut Window, &mut App) + 'static,
537 ) -> Self {
538 self.on_strokes_change = Some(Rc::new(handler));
539 self
540 }
541}
542
543fn paint_outline_polygon(
544 outline: &[(f32, f32)],
545 bounds: Bounds<Pixels>,
546 fill: Hsla,
547 window: &mut Window,
548) {
549 if outline.len() < 3 {
550 return;
551 }
552 let scale_x = f32::from(bounds.size.width) / SIGNATURE_PAD_WIDTH;
553 let scale_y = f32::from(bounds.size.height) / SIGNATURE_PAD_HEIGHT;
554 let ox = f32::from(bounds.origin.x);
555 let oy = f32::from(bounds.origin.y);
556
557 let mut builder = PathBuilder::fill();
558 let n = outline.len();
559 let mid0 = (
560 (outline[0].0 + outline[1].0) * 0.5,
561 (outline[0].1 + outline[1].1) * 0.5,
562 );
563 builder.move_to(point(px(ox + mid0.0 * scale_x), px(oy + mid0.1 * scale_y)));
564 for i in 1..=n {
565 let p0 = outline[i % n];
566 let p1 = outline[(i + 1) % n];
567 let mid = ((p0.0 + p1.0) * 0.5, (p0.1 + p1.1) * 0.5);
568 builder.curve_to(
569 point(px(ox + mid.0 * scale_x), px(oy + mid.1 * scale_y)),
570 point(px(ox + p0.0 * scale_x), px(oy + p0.1 * scale_y)),
571 );
572 }
573 builder.close();
574 if let Ok(path) = builder.build() {
575 window.paint_path(path, fill);
576 }
577}
578
579impl RenderOnce for SignaturePad {
580 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
581 let theme = cx.arc_theme().clone();
582 let colors = theme.colors;
583 let is_dark = theme.mode.is_dark();
584 let now_ms = motion_now(cx) * 1000.0;
585 let reduced = is_reduced_motion(cx);
586
587 let state_id =
588 ElementId::NamedChild(self.id.clone().into(), "__arc-signature-pad-state".into());
589 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
590 SignaturePadInternal::new(self.strokes.clone(), self.ink, self.width, cx)
591 });
592
593 let mut needs_frame = false;
595 let mut replay_at: Option<(f64, Vec<f64>)> = None;
596 internal.update(cx, |s, _| {
597 if let Some(ref replay) = s.replay {
598 let at = if reduced {
599 replay.total_ms
600 } else {
601 (now_ms - replay.started_ms) * replay.speed
602 };
603 if at >= replay.total_ms {
604 s.replay = None;
605 } else {
606 replay_at = Some((at, replay.offsets.clone()));
607 needs_frame = true;
608 }
609 }
610 if let Some(until) = s.saved_svg_until_ms {
611 if now_ms >= until {
612 s.saved_svg_until_ms = None;
613 } else {
614 needs_frame = true;
615 }
616 }
617 });
618 if needs_frame {
619 window.request_animation_frame();
620 }
621
622 let snap = internal.read(cx).clone();
623 let strokes = snap.history.present.clone();
624 let live_stroke = snap.live.as_ref().map(|l| l.stroke.clone());
625 let can_undo = !snap.history.past.is_empty();
626 let can_redo = !snap.history.future.is_empty();
627 let is_empty = strokes.is_empty();
628 let is_drawing = live_stroke.is_some();
629 let is_replaying = replay_at.is_some();
630 let saved_svg = snap.saved_svg_until_ms.is_some();
631 let show_hint = is_empty && !is_drawing;
632 let active_ink = snap.ink;
633 let active_width = snap.width;
634 let focus_handle = snap.focus_handle.clone();
635 let pad_bounds_ref = snap.pad_bounds.clone();
636
637 let mut paint_list: Vec<(Vec<(f32, f32)>, Hsla)> = Vec::new();
639 let mut replay_nib: Option<(f32, f32, f32, Hsla)> = None;
640 for (idx, stroke) in strokes.iter().enumerate() {
641 let stroke_color = stroke.color.display_hsla(is_dark, colors.foreground);
642 if let Some((at_ms, ref offsets)) = replay_at {
643 let local = at_ms - offsets.get(idx).copied().unwrap_or(0.0);
644 if local < 0.0 {
645 continue;
646 }
647 let last_t = stroke.points.last().map(|p| p.t).unwrap_or(0.0);
648 if local >= last_t {
649 let outline = signature_stroke_outline(
650 &stroke.points,
651 stroke.width.size(),
652 0.62,
653 0.42,
654 true,
655 );
656 paint_list.push((outline, stroke_color));
657 } else {
658 let partial: Vec<InkPoint> = stroke
659 .points
660 .iter()
661 .copied()
662 .take_while(|p| p.t <= local)
663 .collect();
664 if let Some(tip) = partial
665 .last()
666 .copied()
667 .or_else(|| stroke.points.first().copied())
668 {
669 replay_nib = Some((tip.x, tip.y, stroke.width.size() * 0.9, stroke_color));
670 }
671 if partial.len() >= 2 {
672 let outline = signature_stroke_outline(
673 &partial,
674 stroke.width.size(),
675 0.62,
676 0.42,
677 false,
678 );
679 paint_list.push((outline, stroke_color));
680 }
681 }
682 } else {
683 let outline =
684 signature_stroke_outline(&stroke.points, stroke.width.size(), 0.62, 0.42, true);
685 paint_list.push((outline, stroke_color));
686 }
687 }
688 if let Some(ref live) = live_stroke {
689 let outline =
690 signature_stroke_outline(&live.points, live.width.size(), 0.62, 0.42, false);
691 paint_list.push((outline, live.color.display_hsla(is_dark, colors.foreground)));
692 }
693
694 let st_paint_up = internal.clone();
695 let cb_paint_up = self.on_strokes_change.clone();
696 let disabled_paint = self.disabled;
697 let ink_canvas = canvas(
698 {
699 let bounds_cell = pad_bounds_ref.clone();
700 move |bounds, _, _| {
701 *bounds_cell.borrow_mut() = Some(bounds);
702 bounds
703 }
704 },
705 move |bounds, _, window, cx| {
706 for (outline, color) in &paint_list {
707 paint_outline_polygon(outline, bounds, *color, window);
708 }
709 if let Some((nx, ny, nr, color)) = replay_nib {
710 let mut circle = Vec::with_capacity(16);
711 for i in 0..16 {
712 let a = i as f32 / 16.0 * std::f32::consts::TAU;
713 circle.push((nx + a.cos() * nr, ny + a.sin() * nr));
714 }
715 paint_outline_polygon(&circle, bounds, color, window);
716 }
717 if !disabled_paint && st_paint_up.read(cx).live.is_some() {
718 let st_w = st_paint_up.clone();
719 let cb_w = cb_paint_up.clone();
720 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
721 if !phase.bubble() || event.button != MouseButton::Left {
722 return;
723 }
724 let mut committed: Option<Vec<InkStroke>> = None;
725 st_w.update(cx, |s, _| {
726 if let Some(live) = s.live.take() {
727 let mut next = s.history.present.clone();
728 next.push(live.stroke);
729 s.history.commit(next.clone());
730 committed = Some(next);
731 }
732 });
733 if let Some(strokes) = committed {
734 if let Some(ref cb) = cb_w {
735 cb(&strokes, window, cx);
736 }
737 window.refresh();
738 }
739 });
740 }
741 },
742 )
743 .size_full();
744
745 let pad_aria = SharedString::from(format!(
746 "{}. {}",
747 self.label,
748 if is_empty {
749 "Empty.".to_string()
750 } else if strokes.len() == 1 {
751 "1 stroke.".to_string()
752 } else {
753 format!("{} strokes.", strokes.len())
754 }
755 ));
756
757 let st_down = internal.clone();
758 let st_move = internal.clone();
759 let st_up = internal.clone();
760 let st_key = internal.clone();
761 let cb_up = self.on_strokes_change.clone();
762 let cb_key = self.on_strokes_change.clone();
763 let disabled = self.disabled;
764
765 let pad = div()
766 .id(ElementId::NamedChild(self.id.clone().into(), "pad".into()))
767 .test_support()
768 .track_focus(&focus_handle)
769 .role(Role::Group)
770 .aria_label(pad_aria)
771 .relative()
772 .w_full()
773 .h(px(210.0))
774 .overflow_hidden()
775 .rounded(Radii::PANEL)
776 .border_1()
777 .border_color(if is_drawing {
778 colors.control_fill
779 } else {
780 colors.border
781 })
782 .bg(colors.surface)
783 .when(!disabled, |this| this.cursor_crosshair())
784 .on_mouse_down(
785 MouseButton::Left,
786 move |event: &MouseDownEvent, window, cx| {
787 if disabled {
788 return;
789 }
790 let t0 = motion_now(cx) * 1000.0;
791 st_down.update(cx, |s, _| {
792 s.replay = None;
793 let (x, y) = s
794 .to_pad(event.position)
795 .unwrap_or((SIGNATURE_PAD_WIDTH * 0.5, SIGNATURE_PAD_HEIGHT * 0.5));
796 let id = SharedString::from(format!("stroke-{}", s.next_stroke_id));
797 s.next_stroke_id += 1;
798 s.live = Some(LiveStroke {
799 stroke: InkStroke {
800 id,
801 points: vec![InkPoint {
802 x,
803 y,
804 p: -1.0,
805 t: 0.0,
806 }],
807 color: s.ink,
808 width: s.width,
809 },
810 started_ms: t0,
811 });
812 });
813 focus_handle.focus(window, cx);
814 window.refresh();
815 },
816 )
817 .on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
818 if disabled {
819 return;
820 }
821 if event.pressed_button != Some(MouseButton::Left) {
822 if st_move.read(cx).live.is_some() {
823 let mut committed: Option<Vec<InkStroke>> = None;
824 st_move.update(cx, |s, _| {
825 if let Some(live) = s.live.take() {
826 let mut next = s.history.present.clone();
827 next.push(live.stroke);
828 s.history.commit(next.clone());
829 committed = Some(next);
830 }
831 });
832 if committed.is_some() {
833 window.refresh();
834 }
835 }
836 return;
837 }
838 let now = motion_now(cx) * 1000.0;
839 let mut moved = false;
840 st_move.update(cx, |s, _| {
841 let Some((x, y)) = s.to_pad(event.position) else {
842 return;
843 };
844 if let Some(ref mut live) = s.live {
845 let elapsed = (now - live.started_ms).max(0.0);
846 let last_t = live.stroke.points.last().map(|p| p.t).unwrap_or(0.0);
847 live.stroke.points.push(InkPoint {
848 x,
849 y,
850 p: -1.0,
851 t: elapsed.max(last_t),
852 });
853 moved = true;
854 }
855 });
856 if moved {
857 window.refresh();
858 }
859 })
860 .on_mouse_up(
861 MouseButton::Left,
862 move |_event: &MouseUpEvent, window, cx| {
863 if disabled {
864 return;
865 }
866 let mut committed: Option<Vec<InkStroke>> = None;
867 st_up.update(cx, |s, _| {
868 if let Some(live) = s.live.take() {
869 let mut next = s.history.present.clone();
870 next.push(live.stroke);
871 s.history.commit(next.clone());
872 committed = Some(next);
873 }
874 });
875 if let Some(strokes) = committed {
876 if let Some(ref cb) = cb_up {
877 cb(&strokes, window, cx);
878 }
879 window.refresh();
880 }
881 },
882 )
883 .on_key_down(move |event: &KeyDownEvent, window, cx| {
884 if disabled {
885 return;
886 }
887 let mods = event.keystroke.modifiers;
888 let cmd = mods.platform || mods.control;
889 let key = event.keystroke.key.as_str();
890 let mut changed: Option<Vec<InkStroke>> = None;
891 st_key.update(cx, |s, _| {
892 if cmd && key.eq_ignore_ascii_case("z") {
893 s.replay = None;
894 let ok = if mods.shift {
895 s.history.redo()
896 } else {
897 s.history.undo()
898 };
899 if ok {
900 changed = Some(s.history.present.clone());
901 }
902 } else if cmd && key.eq_ignore_ascii_case("y") {
903 s.replay = None;
904 if s.history.redo() {
905 changed = Some(s.history.present.clone());
906 }
907 } else if !cmd && (key == "delete" || key == "backspace") {
908 s.replay = None;
909 if !s.history.present.is_empty() {
910 s.history.commit(Vec::new());
911 changed = Some(Vec::new());
912 }
913 } else if key == "escape" && s.replay.is_some() {
914 s.replay = None;
915 }
916 });
917 if let Some(strokes) = changed
918 && let Some(ref cb) = cb_key
919 {
920 cb(&strokes, window, cx);
921 }
922 window.refresh();
923 })
924 .child(
926 div()
927 .absolute()
928 .left(px(28.0))
929 .right(px(28.0))
930 .bottom(px(24.0))
931 .flex()
932 .flex_col()
933 .gap(px(4.0))
934 .child(
935 div()
936 .w_full()
937 .flex()
938 .items_center()
939 .gap(px(8.0))
940 .child(
941 div()
942 .text_size(Typography::TEXT_SM)
943 .text_color(colors.text_muted)
944 .child("×"),
945 )
946 .child(div().flex_1().h(px(1.0)).bg(colors.border)),
947 )
948 .when_some(self.signer.clone(), |this, signer| {
949 this.child(
950 div()
951 .pl(px(18.0))
952 .text_size(Typography::TEXT_XS)
953 .text_color(colors.text_muted)
954 .child(signer),
955 )
956 }),
957 )
958 .when(show_hint, |this| {
960 this.child(
961 div()
962 .absolute()
963 .inset_0()
964 .pb(px(48.0))
965 .flex()
966 .items_center()
967 .justify_center()
968 .text_size(Typography::TEXT_SM)
969 .text_color(colors.text_muted)
970 .child(self.hint.clone()),
971 )
972 })
973 .child(div().absolute().inset_0().child(ink_canvas));
975
976 let color_buttons = InkColor::ALL.into_iter().map(|opt| {
978 let selected = opt == active_ink;
979 let st_c = internal.clone();
980 let swatch = opt.display_hsla(is_dark, colors.foreground);
981 BaseButton::new(ElementId::NamedChild(
982 self.id.clone().into(),
983 SharedString::from(format!("ink-{}", opt.label())),
984 ))
985 .accessibility_label(SharedString::from(opt.label()))
986 .disabled(disabled)
987 .on_click(move |_, window, cx| {
988 st_c.update(cx, |s, _| {
989 s.ink = opt;
990 });
991 window.refresh();
992 })
993 .w(px(30.0))
994 .h(px(30.0))
995 .flex()
996 .items_center()
997 .justify_center()
998 .rounded_full()
999 .border_1()
1000 .border_color(if selected {
1001 colors.control_fill
1002 } else {
1003 Hsla::transparent_black()
1004 })
1005 .bg(if selected {
1006 colors.surface_muted
1007 } else {
1008 Hsla::transparent_black()
1009 })
1010 .cursor_pointer()
1011 .child(div().w(px(14.0)).h(px(14.0)).rounded_full().bg(swatch))
1012 });
1013
1014 let width_buttons = InkWidth::ALL.into_iter().map(|opt| {
1016 let selected = opt == active_width;
1017 let st_w = internal.clone();
1018 let dot_px = opt.size() + 2.0;
1019 BaseButton::new(ElementId::NamedChild(
1020 self.id.clone().into(),
1021 SharedString::from(format!("width-{}", opt.label())),
1022 ))
1023 .accessibility_label(SharedString::from(opt.label()))
1024 .disabled(disabled)
1025 .on_click(move |_, window, cx| {
1026 st_w.update(cx, |s, _| {
1027 s.width = opt;
1028 });
1029 window.refresh();
1030 })
1031 .w(px(30.0))
1032 .h(px(30.0))
1033 .flex()
1034 .items_center()
1035 .justify_center()
1036 .rounded_full()
1037 .border_1()
1038 .border_color(if selected {
1039 colors.control_fill
1040 } else {
1041 Hsla::transparent_black()
1042 })
1043 .bg(if selected {
1044 colors.surface_muted
1045 } else {
1046 Hsla::transparent_black()
1047 })
1048 .cursor_pointer()
1049 .child(
1050 div()
1051 .w(px(dot_px))
1052 .h(px(dot_px))
1053 .rounded_full()
1054 .bg(colors.foreground),
1055 )
1056 });
1057
1058 let st_undo = internal.clone();
1059 let cb_undo = self.on_strokes_change.clone();
1060 let st_redo = internal.clone();
1061 let cb_redo = self.on_strokes_change.clone();
1062 let st_replay = internal.clone();
1063 let st_clear = internal.clone();
1064 let cb_clear = self.on_strokes_change.clone();
1065 let st_svg = internal.clone();
1066 let strokes_for_svg = strokes.clone();
1067
1068 let action_btn = |id_suffix: &'static str,
1069 aria: &'static str,
1070 text: &'static str,
1071 is_disabled: bool,
1072 pressed: bool| {
1073 BaseButton::new(ElementId::NamedChild(
1074 self.id.clone().into(),
1075 id_suffix.into(),
1076 ))
1077 .accessibility_label(SharedString::from(aria))
1078 .disabled(is_disabled)
1079 .h(px(30.0))
1080 .px(px(10.0))
1081 .flex()
1082 .items_center()
1083 .justify_center()
1084 .rounded(Radii::CONTROL)
1085 .border_1()
1086 .border_color(if pressed {
1087 colors.control_fill
1088 } else {
1089 colors.border
1090 })
1091 .bg(if pressed {
1092 colors.accent_subtle
1093 } else {
1094 colors.surface
1095 })
1096 .text_size(Typography::TEXT_XS)
1097 .text_color(if is_disabled {
1098 colors.text_muted
1099 } else if pressed {
1100 colors.accent_strong
1101 } else {
1102 colors.foreground
1103 })
1104 .when(!is_disabled, |b| b.cursor_pointer())
1105 .child(SharedString::from(text))
1106 };
1107
1108 let toolbar =
1109 div()
1110 .w_full()
1111 .flex()
1112 .flex_wrap()
1113 .items_center()
1114 .justify_between()
1115 .gap(Spacing::S2)
1116 .child(
1117 div()
1118 .flex()
1119 .items_center()
1120 .gap(px(4.0))
1121 .children(color_buttons)
1122 .child(div().w(px(1.0)).h(px(18.0)).mx(px(4.0)).bg(colors.border))
1123 .children(width_buttons),
1124 )
1125 .child(
1126 div()
1127 .flex()
1128 .items_center()
1129 .gap(px(6.0))
1130 .child(
1131 action_btn("undo", "Undo", "Undo", disabled || !can_undo, false)
1132 .on_click(move |_, window, cx| {
1133 let mut next = None;
1134 st_undo.update(cx, |s, _| {
1135 s.replay = None;
1136 if s.history.undo() {
1137 next = Some(s.history.present.clone());
1138 }
1139 });
1140 if let Some(strokes) = next {
1141 if let Some(ref cb) = cb_undo {
1142 cb(&strokes, window, cx);
1143 }
1144 window.refresh();
1145 }
1146 }),
1147 )
1148 .child(
1149 action_btn("redo", "Redo", "Redo", disabled || !can_redo, false)
1150 .on_click(move |_, window, cx| {
1151 let mut next = None;
1152 st_redo.update(cx, |s, _| {
1153 s.replay = None;
1154 if s.history.redo() {
1155 next = Some(s.history.present.clone());
1156 }
1157 });
1158 if let Some(strokes) = next {
1159 if let Some(ref cb) = cb_redo {
1160 cb(&strokes, window, cx);
1161 }
1162 window.refresh();
1163 }
1164 }),
1165 )
1166 .child(
1167 action_btn(
1168 "replay",
1169 if is_replaying {
1170 "Stop replay"
1171 } else {
1172 "Replay signature"
1173 },
1174 if is_replaying { "Stop" } else { "Replay" },
1175 disabled || is_empty,
1176 is_replaying,
1177 )
1178 .on_click(move |_, window, cx| {
1179 let now = motion_now(cx) * 1000.0;
1180 st_replay.update(cx, |s, _| {
1181 if s.replay.is_some() {
1182 s.replay = None;
1183 } else {
1184 s.start_replay(now);
1185 }
1186 });
1187 window.refresh();
1188 }),
1189 )
1190 .child(
1191 action_btn(
1192 "clear",
1193 "Clear signature",
1194 "Clear",
1195 disabled || is_empty,
1196 false,
1197 )
1198 .on_click(move |_, window, cx| {
1199 let mut cleared = false;
1200 st_clear.update(cx, |s, _| {
1201 s.replay = None;
1202 if !s.history.present.is_empty() {
1203 s.history.commit(Vec::new());
1204 cleared = true;
1205 }
1206 });
1207 if cleared {
1208 if let Some(ref cb) = cb_clear {
1209 cb(&[], window, cx);
1210 }
1211 window.refresh();
1212 }
1213 }),
1214 ),
1215 );
1216
1217 let export_row = div()
1218 .w_full()
1219 .flex()
1220 .items_center()
1221 .justify_end()
1222 .gap(Spacing::S2)
1223 .child(
1224 div()
1225 .text_size(Typography::TEXT_XS)
1226 .text_color(colors.text_muted)
1227 .child(SharedString::from("Export")),
1228 )
1229 .child(
1230 action_btn(
1231 "export-svg",
1232 "Copy SVG",
1233 if saved_svg { "Copied SVG" } else { "Copy SVG" },
1234 disabled || is_empty,
1235 saved_svg,
1236 )
1237 .on_click(move |_, window, cx| {
1238 let svg = signature_to_svg(
1239 &strokes_for_svg,
1240 SIGNATURE_PAD_WIDTH,
1241 SIGNATURE_PAD_HEIGHT,
1242 );
1243 cx.write_to_clipboard(ClipboardItem::new_string(svg));
1244 let until = motion_now(cx) * 1000.0 + 1800.0;
1245 st_svg.update(cx, |s, _| {
1246 s.saved_svg_until_ms = Some(until);
1247 });
1248 window.refresh();
1249 }),
1250 );
1251
1252 div()
1253 .id(self.id.clone())
1254 .test_support()
1255 .when_some(self.width_px, |this, w| this.w(w))
1256 .when(self.width_px.is_none(), |this| this.w_full())
1257 .flex()
1258 .flex_col()
1259 .gap(Spacing::S3)
1260 .child(pad)
1261 .child(toolbar)
1262 .child(export_row)
1263 }
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1269 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
1270
1271 use super::*;
1272
1273 #[test]
1274 fn signature_outline_round_trips_through_path() {
1275 let points = vec![(0.0, 0.0), (10.0, 10.0), (20.0, 0.0), (30.0, 10.0)];
1276 let path = signature_outline_to_path(&points);
1277 assert!(path.starts_with("M"));
1278 assert!(path.ends_with("Z"));
1279 assert!(path.contains('Q'));
1280 }
1281
1282 #[test]
1283 fn signature_stroke_outline_closes_around_points() {
1284 let points = vec![
1285 InkPoint {
1286 x: 0.0,
1287 y: 0.0,
1288 p: 0.5,
1289 t: 0.0,
1290 },
1291 InkPoint {
1292 x: 10.0,
1293 y: 10.0,
1294 p: 0.5,
1295 t: 16.0,
1296 },
1297 InkPoint {
1298 x: 20.0,
1299 y: 0.0,
1300 p: 0.5,
1301 t: 32.0,
1302 },
1303 InkPoint {
1304 x: 30.0,
1305 y: 10.0,
1306 p: 0.5,
1307 t: 48.0,
1308 },
1309 ];
1310 let outline = signature_stroke_outline(&points, 5.6, 0.62, 0.42, true);
1311 assert!(!outline.is_empty());
1312 assert!(outline.len() >= points.len() * 2);
1314 }
1315
1316 #[test]
1317 fn signature_to_svg_round_trips() {
1318 let stroke = InkStroke {
1319 id: "s1".into(),
1320 points: vec![
1321 InkPoint {
1322 x: 0.0,
1323 y: 0.0,
1324 p: 0.5,
1325 t: 0.0,
1326 },
1327 InkPoint {
1328 x: 10.0,
1329 y: 10.0,
1330 p: 0.5,
1331 t: 16.0,
1332 },
1333 ],
1334 color: InkColor::Black,
1335 width: InkWidth::Medium,
1336 };
1337 let svg = signature_to_svg(&[stroke], SIGNATURE_PAD_WIDTH, SIGNATURE_PAD_HEIGHT);
1338 assert!(svg.starts_with("<svg"));
1339 assert!(svg.ends_with("</svg>"));
1340 assert!(svg.contains("<path"));
1341 }
1342
1343 #[test]
1344 fn signature_stroke_path_slices_by_up_to_ms() {
1345 let stroke = InkStroke {
1346 id: "s1".into(),
1347 points: vec![
1348 InkPoint {
1349 x: 0.0,
1350 y: 0.0,
1351 p: 0.5,
1352 t: 0.0,
1353 },
1354 InkPoint {
1355 x: 10.0,
1356 y: 10.0,
1357 p: 0.5,
1358 t: 16.0,
1359 },
1360 InkPoint {
1361 x: 20.0,
1362 y: 0.0,
1363 p: 0.5,
1364 t: 32.0,
1365 },
1366 ],
1367 color: InkColor::Black,
1368 width: InkWidth::Medium,
1369 };
1370 let path = signature_stroke_path(&stroke, Some(16.0));
1372 assert!(path.contains("Q"));
1373 let path = signature_stroke_path(&stroke, Some(0.0));
1375 assert!(path.is_empty());
1376 let path = signature_stroke_path(&stroke, Some(32.0));
1378 assert!(path.contains("Q"));
1379 }
1380
1381 #[test]
1382 fn signature_stroke_outline_handles_a_dot() {
1383 let points = vec![InkPoint {
1384 x: 0.0,
1385 y: 0.0,
1386 p: 0.5,
1387 t: 0.0,
1388 }];
1389 let outline = signature_stroke_outline(&points, 5.6, 0.62, 0.42, true);
1390 assert_eq!(outline.len(), 18);
1391 }
1392
1393 #[test]
1394 fn ink_history_undo_and_redo_round_trip() {
1395 let s1 = InkStroke {
1396 id: "s1".into(),
1397 points: vec![
1398 InkPoint {
1399 x: 10.0,
1400 y: 20.0,
1401 p: -1.0,
1402 t: 0.0,
1403 },
1404 InkPoint {
1405 x: 40.0,
1406 y: 30.0,
1407 p: -1.0,
1408 t: 24.0,
1409 },
1410 ],
1411 color: InkColor::Blue,
1412 width: InkWidth::Fine,
1413 };
1414 let mut history = InkHistory::new(Vec::new());
1415 assert!(!history.undo());
1416 history.commit(vec![s1.clone()]);
1417 assert_eq!(history.present.len(), 1);
1418 assert!(history.undo());
1419 assert!(history.present.is_empty());
1420 assert!(history.redo());
1421 assert_eq!(history.present.len(), 1);
1422 }
1423
1424 struct PadHost;
1425
1426 impl Render for PadHost {
1427 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1428 div().w(px(560.0)).p(px(16.0)).child(
1429 SignaturePad::new("sig-test")
1430 .label("Contract signature")
1431 .signer("Ada Lovelace")
1432 .strokes(vec![InkStroke {
1433 id: "seed-1".into(),
1434 points: vec![
1435 InkPoint {
1436 x: 80.0,
1437 y: 130.0,
1438 p: -1.0,
1439 t: 0.0,
1440 },
1441 InkPoint {
1442 x: 140.0,
1443 y: 90.0,
1444 p: -1.0,
1445 t: 40.0,
1446 },
1447 InkPoint {
1448 x: 210.0,
1449 y: 145.0,
1450 p: -1.0,
1451 t: 85.0,
1452 },
1453 ],
1454 color: InkColor::Blue,
1455 width: InkWidth::Medium,
1456 }]),
1457 )
1458 }
1459 }
1460
1461 #[gpui_kit::test]
1462 fn signature_pad_renders_pad_and_controls(cx: &mut TestAppContext) {
1463 cx.update(|cx| {
1464 gpui_kit::init(cx);
1465 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1466 });
1467
1468 let (_view, cx) = cx.add_window_view(|_, _| PadHost);
1469 cx.update(|window, cx| {
1470 window.render_frame(cx);
1471 let pad_id =
1472 ElementId::NamedChild(ElementId::Name("sig-test".into()).into(), "pad".into());
1473 let pad = window.find(pad_id);
1474 assert_eq!(pad.role(), Some(Role::Group));
1475 assert!(
1476 window
1477 .try_find(ElementId::NamedChild(
1478 ElementId::Name("sig-test".into()).into(),
1479 "clear".into(),
1480 ))
1481 .is_some()
1482 );
1483 });
1484 }
1485}