Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Paint a pen tap at its own pressure, not full or zero (#1798) (#2757)

Fabio Lussi994a042123cc
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index c834c4fbe..7fdeb2a4d 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -505,6 +505,19 @@ fn feed_live_stroke(app: &mut PhotocraftApp) {
}
}
+/// A pen tap (a drag still at its one press point when released) paints its dab at the highest
+/// pressure the pen reached during the contact, not just the first sample's (#1798). A mouse is
+/// unchanged at full pressure.
+fn tap_at_peak_pressure(app: &mut PhotocraftApp) {
+ if app.stylus.sample().is_none() {
+ return;
+ }
+ let peak = f64::from(app.stylus.tap_pressure());
+ if let Some(p) = app.drag.as_mut().filter(|d| d.points.len() == 1).and_then(|d| d.points.first_mut()) {
+ p[2] = p[2].max(peak);
+ }
+}
+
/// While a stroke is held still, its point repeats this often (in ms) so time-based brush
/// features (airbrush build-up, smoothing catch-up) keep going, as when the pen moves.
const HOLD_REPEAT_MS: f64 = 16.0;
@@ -2815,6 +2828,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
let p = response.interact_pointer_pos().map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]])));
if let Some(d) = p {
+ tap_at_peak_pressure(app);
tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods);
}
}
@@ -2826,6 +2840,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if let Some(d) = p
&& app.drag.is_some()
{
+ tap_at_peak_pressure(app);
tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods);
}
}
@@ -2859,6 +2874,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// If this tool was not handled on pointer-down, fall back to a
// click-sized gesture while preserving pen pressure (mouse stays at 1).
tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods);
+ tap_at_peak_pressure(app);
tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods);
}
}
diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs
index 94dfe9f1c..bd6b830e4 100644
--- a/crates/ui-egui/src/stroke_timing_tests.rs
+++ b/crates/ui-egui/src/stroke_timing_tests.rs
@@ -181,3 +181,120 @@ fn the_pressure_curve_shapes_the_committed_stroke() {
let pts = committed_points(&h);
assert!(pts.iter().all(|p| (p[2] - 0.6).abs() < 1e-3), "pen 0.3 through the curve is 0.6: {pts:?}");
}
+
+/// A Brush whose size follows pen pressure, painting on a new empty layer.
+fn pressure_sized_brush(h: &mut Harness<'static, PhotocraftApp>) {
+ let app = h.state_mut();
+ app.run("layer.new.layer", json!({})).unwrap();
+ let brush = json!({"size": 40, "hardness": 1.0, "smoothing": {"amount": 0.0}, "shapeDynamics": {"enabled": true, "size": {"control": "penPressure"}}});
+ app.run("tools.setBrush", json!({ "brush": brush })).unwrap();
+ h.run_steps(1);
+}
+
+/// Width in pixels of the paint on the active layer along row `y`.
+fn painted_width(h: &Harness<'static, PhotocraftApp>, y: i32) -> usize {
+ let st = h.state().session.active().expect("a document");
+ let s = st.doc.layer(st.active_layer.expect("an active layer")).and_then(|l| l.surface()).expect("a raster layer");
+ (0..200).filter(|x| s.rgba(*x, y)[3] > 0.5).count()
+}
+
+/// Press and release at (`x`, 50) in one frame, the pen reporting `samples` (`None`: cleared, as
+/// a lifting pen or a mouse leaves it) before the UI runs: a tap shorter than a frame.
+fn tap(h: &mut Harness<'static, PhotocraftApp>, x: f32, samples: &[Option<f32>]) {
+ use crate::stylus::PenSample;
+ move_to(h, x, 50.0);
+ for p in samples {
+ h.state().stylus.feed.set(p.map(|pressure| PenSample { pressure, ..Default::default() }));
+ }
+ let q = screen(h, x, 50.0);
+ for pressed in [true, false] {
+ h.input_mut().events.push(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
+ }
+ h.run_steps(3);
+}
+
+#[test]
+fn a_tap_shorter_than_a_frame_paints_at_the_pens_pressure() {
+ // #1798: the pen lifted (its sample cleared) before the UI ran, so the tap read as a mouse
+ // and painted a full-size dab whatever the pressure.
+ let mut h = harness();
+ pressure_sized_brush(&mut h);
+ tap(&mut h, 50.0, &[Some(0.2), None]);
+ assert!((committed_points(&h)[0][2] - 0.2).abs() < 1e-3, "{:?}", committed_points(&h));
+ tap(&mut h, 150.0, &[Some(0.9), None]);
+ assert!((committed_points(&h)[0][2] - 0.9).abs() < 1e-3, "{:?}", committed_points(&h));
+ let st = h.state().session.active().unwrap();
+ let s = st.doc.layer(st.active_layer.unwrap()).and_then(|l| l.surface()).unwrap();
+ let width = |x0: i32, x1: i32| (x0..x1).filter(|x| s.rgba(*x, 50)[3] > 0.5).count() as f64;
+ let (light, firm) = (width(0, 100), width(100, 200));
+ assert!((light / 40.0 - 0.2).abs() < 0.1, "a light tap is a small dab: {light} px");
+ assert!((firm / 40.0 - 0.9).abs() < 0.1, "a firm tap is a large dab: {firm} px");
+}
+
+#[test]
+fn a_tap_never_paints_at_the_lifts_zero_pressure() {
+ // X11 and a hovering macOS pen report pressure 0 around the contact.
+ let mut h = harness();
+ pressure_sized_brush(&mut h);
+ tap(&mut h, 50.0, &[Some(0.0), Some(0.6), Some(0.0)]);
+ assert!((committed_points(&h)[0][2] - 0.6).abs() < 1e-3, "{:?}", committed_points(&h));
+}
+
+#[test]
+fn a_tap_over_two_frames_paints_at_the_pressure_it_reached() {
+ use crate::stylus::PenSample;
+ let mut h = harness();
+ pressure_sized_brush(&mut h);
+ let pen = |p: f32| Some(PenSample { pressure: p, ..Default::default() });
+ move_to(&mut h, 50.0, 50.0);
+ h.state().stylus.feed.set(pen(0.1));
+ button(&mut h, 50.0, 50.0, true);
+ h.state().stylus.feed.set(pen(0.5));
+ h.state().stylus.feed.set(pen(0.0));
+ button(&mut h, 50.0, 50.0, false);
+ h.run_steps(2);
+ let pts = committed_points(&h);
+ assert_eq!(pts.len(), 1, "{pts:?}");
+ assert!((pts[0][2] - 0.5).abs() < 1e-3, "the tap's peak, not its first touch: {pts:?}");
+}
+
+#[test]
+fn a_mouse_tap_paints_a_full_dab() {
+ let mut h = harness();
+ pressure_sized_brush(&mut h);
+ tap(&mut h, 50.0, &[]);
+ assert_eq!(committed_points(&h)[0][2], 1.0);
+ let w = painted_width(&h, 50) as f64;
+ assert!((w - 40.0).abs() <= 3.0, "full size: {w} px");
+}
+
+#[test]
+fn a_stroke_ends_at_the_last_pressure_the_pen_drew_with() {
+ use crate::stylus::PenSample;
+ // The lift either clears the pen (macOS proximity, a non-tablet button-up) or reports 0
+ // (X11) before the UI runs the frame with the stroke's last moves.
+ for lift in [None, Some(0.0)] {
+ let mut h = harness();
+ pressure_sized_brush(&mut h);
+ let pen = |p: f32| Some(PenSample { pressure: p, ..Default::default() });
+ h.state().stylus.feed.set(pen(0.4));
+ move_to(&mut h, 20.0, 50.0);
+ button(&mut h, 20.0, 50.0, true);
+ for x in [30.0, 40.0] {
+ h.state().stylus.feed.set(pen(0.4));
+ move_to(&mut h, x, 50.0);
+ }
+ // One frame: the last moves, then the lift.
+ for x in [50.0, 60.0] {
+ h.state().stylus.feed.set(pen(0.4));
+ let q = screen(&h, x, 50.0);
+ h.input_mut().events.push(egui::Event::PointerMoved(q));
+ }
+ h.state().stylus.feed.set(lift.map(|p| PenSample { pressure: p, ..Default::default() }));
+ let q = screen(&h, 60.0, 50.0);
+ h.input_mut().events.push(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+ h.run_steps(3);
+ let pts = committed_points(&h);
+ assert!(pts.iter().all(|p| (p[2] - 0.4).abs() < 1e-3), "lift {lift:?}: no full or zero pressure dab at the end: {pts:?}");
+ }
+}
diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs
index f30141470..6bee70514 100644
--- a/crates/ui-egui/src/stylus.rs
+++ b/crates/ui-egui/src/stylus.rs
@@ -128,6 +128,8 @@ pub struct Stylus {
prev: Option<PenSample>,
/// The sample [`Self::select`] interpolated for the pointer move being processed.
current: Option<PenSample>,
+ /// The highest pen pressure (before the curve) since the drag began, for a tap's one dab.
+ peak: f32,
/// The egui frame [`Self::update_for_frame`] last ran in.
updated_frame: Option<u64>,
/// Tilt X, tilt Y, rotation of each point of the current drag (parallel to its points).
@@ -154,6 +156,7 @@ impl Default for Stylus {
frame: Vec::new(),
prev: None,
current: None,
+ peak: 0.0,
updated_frame: None,
stroke: Vec::new(),
times: Vec::new(),
@@ -195,6 +198,25 @@ impl Stylus {
}
}
}
+ // A pen reports pressure 0 while it hovers and as it lifts (X11, macOS): that is no
+ // contact, so a frame that also touched keeps only its contact samples. A stroke's last
+ // moves then keep the pressure the pen left with, and a tap its own (#1798).
+ if self.frame.iter().any(|s| s.pressure > 0.0) {
+ self.frame.retain(|s| s.pressure > 0.0);
+ }
+ self.peak = self.frame.iter().fold(self.peak, |m, s| m.max(s.pressure));
+ }
+
+ /// The pen's current sample. When the pen touched during this frame but has lifted since
+ /// (the feed is cleared or back at pressure 0 by the time the UI runs, as for a tap shorter
+ /// than a frame), the frame's last contact sample: never full pressure as for a mouse, and
+ /// never the lift's 0.
+ fn latest(&self) -> Option<PenSample> {
+ let feed = self.feed.get();
+ match self.frame.last() {
+ Some(s) if s.pressure > 0.0 && feed.is_none_or(|f| f.pressure <= 0.0) => Some(*s),
+ _ => feed,
+ }
}
/// The current pen sample, `None` for a mouse (and for any pen while Use Tablet Pressure is
@@ -203,7 +225,7 @@ impl Stylus {
if !self.use_pressure {
return None;
}
- let s = self.current.or_else(|| self.feed.get()).or(self.touch.map(|pressure| PenSample { pressure, ..Default::default() }))?;
+ let s = self.current.or_else(|| self.latest()).or(self.touch.map(|pressure| PenSample { pressure, ..Default::default() }))?;
// The pen's pressure through Preferences › Tools › Pressure Curve, before any brush sees it.
Some(match &self.pressure_curve {
Some(c) => PenSample { pressure: c.eval(s.pressure), ..s },
@@ -293,11 +315,24 @@ impl Stylus {
self.sample().map_or(1.0, |s| s.pressure)
}
+ /// Pressure for a tap, a drag released where it was pressed: the highest the pen pressed
+ /// since the drag began (through the pressure curve), as the first sample of a contact is
+ /// often far lighter than the tap. 1 for a mouse.
+ pub(crate) fn tap_pressure(&self) -> f32 {
+ let Some(s) = self.sample() else { return 1.0 };
+ let peak = match &self.pressure_curve {
+ Some(c) => c.eval(self.peak),
+ None => self.peak,
+ };
+ if self.peak > 0.0 { peak.max(s.pressure) } else { s.pressure }
+ }
+
/// Start recording a drag's tilt/rotation.
pub(crate) fn begin_stroke(&mut self) {
// A new stroke's first moves interpolate from this frame's samples, never from a sample
// left over from an earlier stroke.
self.prev = None;
+ self.peak = self.frame.iter().fold(0.0, |m, s| m.max(s.pressure));
self.stroke.clear();
self.times.clear();
self.record_point();