1use egui::epaint::{Mesh, Vertex, WHITE_UV};
56use egui::{
57 Color32, Pos2, Rect, Response, Role, Sense, Shape, Stroke, StrokeKind, Ui, Vec2, Widget,
58 WidgetInfo, pos2, vec2,
59};
60use egui_pop_core::areas::{self, AreaSpec, Grip};
61use egui_pop_core::state::Slot;
62use egui_pop_core::strings::{self, Arg};
63use egui_pop_core::theme::Tokens;
64use serde_json::{Value as Json, json};
65
66use crate::change::{self, Cause, Change, Gesture, Hook, StepValue, Verdict};
67
68#[derive(Clone, Debug)]
70pub struct Channel<'a> {
71 pub name: &'a str,
72 pub bins: &'a [f32],
73 pub color: Color32,
74}
75
76impl<'a> Channel<'a> {
77 pub fn new(name: &'a str, bins: &'a [f32], color: Color32) -> Channel<'a> {
78 Channel { name, bins, color }
79 }
80}
81
82#[derive(Clone, Copy, Debug, Default, PartialEq)]
85pub struct Clipping {
86 pub shadows: f32,
87 pub highlights: f32,
88}
89
90#[derive(Clone, Copy, Debug, Default, PartialEq)]
94pub struct Drag {
95 pub at: Option<f32>,
96 pub delta: f32,
97}
98
99impl StepValue for Drag {
101 fn to_json(&self) -> Json {
102 json!({ "at": self.at, "delta": self.delta })
103 }
104
105 fn from_json(v: &Json) -> Option<Self> {
106 let at = match v.get("at") {
107 None | Some(Json::Null) => None,
108 Some(a) => Some(change::json_f32(a)?),
109 };
110 Some(Drag {
111 at,
112 delta: change::json_f32(v.get("delta")?)?,
113 })
114 }
115}
116
117#[derive(Clone, Copy, Debug, PartialEq)]
119pub struct HistogramTokens {
120 pub background: Color32,
121 pub grid: Color32,
122 pub clip_shadows: Color32,
123 pub clip_highlights: Color32,
124}
125
126impl HistogramTokens {
127 pub fn of(ctx: &egui::Context) -> HistogramTokens {
128 let t = Tokens::of(ctx);
129 let c = |path: &str, fallback: Color32| t.color(path).unwrap_or(fallback);
130 HistogramTokens {
131 background: c("histogram.background", t.surface.sunken),
132 grid: c("histogram.grid", t.border.default),
133 clip_shadows: c("histogram.clip-shadows", t.status.info),
134 clip_highlights: c("histogram.clip-highlights", t.status.danger),
135 }
136 }
137}
138
139#[derive(Debug)]
143pub struct Histogram<'a> {
144 channels: Vec<Channel<'a>>,
145 log: bool,
146 size: Option<Vec2>,
147 label: Option<String>,
148 clipping: Option<Clipping>,
149 draggable: bool,
150 step: f32,
151 hook: Option<Hook<'a, Drag>>,
152 edits: Option<(String, Option<String>)>,
153}
154
155#[derive(Debug)]
157pub struct HistogramOutput {
158 pub response: Response,
160 pub changes: Vec<Change<Drag>>,
162}
163
164impl HistogramOutput {
165 pub fn moved(&self) -> f32 {
169 self.changes.iter().map(|c| c.to.delta - c.from.delta).sum()
170 }
171
172 pub fn at(&self) -> Option<f32> {
174 self.changes.iter().find_map(|c| c.to.at)
175 }
176}
177
178impl<'a> Histogram<'a> {
179 pub fn new(channels: impl IntoIterator<Item = Channel<'a>>) -> Histogram<'a> {
180 Histogram {
181 channels: channels.into_iter().collect(),
182 log: false,
183 size: None,
184 label: None,
185 clipping: None,
186 draggable: false,
187 step: 0.01,
188 hook: None,
189 edits: None,
190 }
191 }
192
193 pub fn log(mut self, log: bool) -> Histogram<'a> {
195 self.log = log;
196 self
197 }
198
199 pub fn size(mut self, size: Vec2) -> Histogram<'a> {
202 self.size = Some(size);
203 self
204 }
205
206 pub fn label(mut self, label: impl Into<String>) -> Histogram<'a> {
208 self.label = Some(label.into());
209 self
210 }
211
212 pub fn clipping(mut self, clipping: Clipping) -> Histogram<'a> {
216 self.clipping = Some(clipping);
217 self
218 }
219
220 pub fn draggable(mut self, on: bool) -> Histogram<'a> {
223 self.draggable = on;
224 self
225 }
226
227 pub fn edits(mut self, control: impl Into<String>, value: impl Into<String>) -> Histogram<'a> {
233 let value: String = value.into();
234 self.edits = Some((control.into(), (!value.is_empty()).then_some(value)));
235 self
236 }
237
238 pub fn step(mut self, step: f32) -> Histogram<'a> {
241 self.step = step.abs();
242 self
243 }
244
245 pub fn on_change(
249 mut self,
250 hook: impl FnMut(&Change<Drag>) -> Verdict<Drag> + 'a,
251 ) -> Histogram<'a> {
252 self.hook = Some(Hook::new(hook));
253 self.draggable = true;
254 self
255 }
256
257 pub fn show(self, ui: &mut Ui) -> HistogramOutput {
259 let Histogram {
260 channels,
261 log,
262 size,
263 label,
264 clipping,
265 draggable,
266 step,
267 mut hook,
268 edits,
269 } = self;
270 let salt = ("histogram", &label);
275 let dragging = DRAG
276 .keyed(change::tool_id(ui, salt))
277 .get(ui.ctx())
278 .is_some();
279 let inert = draggable && areas::inert(ui) && !dragging;
280 let draggable = draggable && !inert;
281 let size = size.unwrap_or_else(|| {
282 let w = ui.available_width().clamp(120.0, 600.0);
283 vec2(w, (w / 3.0).round())
284 });
285 let sense = if draggable {
286 Sense::click_and_drag()
287 } else {
288 Sense::hover()
289 };
290 let (rect, mut response) = change::allocate(ui, size, sense, salt);
291 let mut changes = Vec::new();
292 if draggable {
293 drag(ui, &response, rect, step, &mut hook, &mut changes);
294 egui_pop_core::pointer::drag_cursor(
296 &response,
297 egui_pop_core::pointer::DragKind::ResizeHorizontal,
298 )
299 .clicks(false);
300 } else if inert {
301 give_up(ui, &response, &mut changes);
302 }
303 if !changes.is_empty() {
304 response.mark_changed();
305 }
306 paint(ui, rect, &response, &channels, log, clipping, draggable);
307 let names: Vec<&str> = channels.iter().map(|c| c.name).collect();
308 let bins = channels.first().map_or(0, |c| c.bins.len());
309 let label = label.unwrap_or_else(|| strings::tr(ui.ctx(), &crate::strings::HISTOGRAM));
310 let id = format!("histogram:{label}");
311 let area = if draggable || inert {
312 let (control, value) = edits.unwrap_or_else(|| (label.clone(), None));
315 let mut a = AreaSpec::edit(id, control).grip(Grip::horizontal(pos2(
316 rect.right() - GRIP_INSET,
317 rect.center().y,
318 )));
319 if let Some(v) = value {
320 a = a.value(v);
321 }
322 a
323 } else {
324 AreaSpec::display(id)
325 };
326 areas::register(ui, &response, area);
327 let value = value_text(ui.ctx(), &names, bins, log, clipping);
328 let kind = if draggable {
329 Role::Slider
330 } else {
331 Role::Unknown
332 };
333 let enabled = ui.is_enabled();
334 response.widget_info(move || {
335 let mut info = WidgetInfo::labeled(kind, enabled, &label);
336 info.current_text_value = Some(value.clone());
337 info
338 });
339 if draggable {
340 ui.ctx().accesskit_node_builder(response.id, |node| {
341 use egui::accesskit::Action;
342 node.add_action(Action::Increment);
343 node.add_action(Action::Decrement);
344 });
345 }
346 HistogramOutput { response, changes }
347 }
348}
349
350impl Widget for Histogram<'_> {
351 fn ui(self, ui: &mut Ui) -> Response {
352 self.show(ui).response
353 }
354}
355
356fn change_of(from: Drag, to: Drag, cause: Cause, done: bool) -> Change<Drag> {
357 Change {
358 from,
359 to,
360 cause,
361 done,
362 }
363}
364
365const GRIP_INSET: f32 = 6.0;
367
368const DRAG: Slot<Drag> = Slot::new("viewport.histogram.drag");
370
371fn give_up(ui: &Ui, response: &Response, changes: &mut Vec<Change<Drag>>) {
374 if let Some(total) = DRAG.keyed(response.id).remove(ui.ctx())
375 && total.delta != 0.0
376 {
377 let start = Drag {
378 delta: 0.0,
379 ..total
380 };
381 changes.push(change_of(total, start, Cause::Drag, true));
382 }
383}
384
385fn drag(
387 ui: &mut Ui,
388 response: &Response,
389 rect: Rect,
390 step: f32,
391 hook: &mut Option<Hook<'_, Drag>>,
392 changes: &mut Vec<Change<Drag>>,
393) {
394 let id = DRAG.keyed(response.id);
395 if response.drag_started() {
396 let at = response
397 .interact_pointer_pos()
398 .map(|p| ((p.x - rect.left()) / rect.width().max(1.0)).clamp(0.0, 1.0));
399 id.set(ui.ctx(), Drag { at, delta: 0.0 });
400 }
401 let current = id.get(ui.ctx());
402 match change::gesture(ui, response) {
403 Gesture::None => {}
404 Gesture::Moved(d) => {
405 if let Some(from) = current {
406 let to = Drag {
407 delta: from.delta + d.x / rect.width().max(1.0),
408 ..from
409 };
410 if let Some(c) = change::decide(hook, change_of(from, to, Cause::Drag, false)) {
411 id.set(ui.ctx(), c.to);
412 changes.push(c);
413 }
414 }
415 }
416 Gesture::Ended => {
417 id.remove(ui.ctx());
418 if let Some(total) = current.filter(|t| t.delta != 0.0) {
419 let start = Drag {
420 delta: 0.0,
421 ..total
422 };
423 let end = change::decide(hook, change_of(start, total, Cause::Drag, true))
426 .map_or(start, |c| c.to);
427 changes.push(change_of(total, end, Cause::Drag, true));
428 }
429 }
430 Gesture::Cancelled => {
431 id.remove(ui.ctx());
432 if let Some(total) = current.filter(|t| t.delta != 0.0) {
433 let start = Drag {
434 delta: 0.0,
435 ..total
436 };
437 changes.push(change_of(total, start, Cause::Drag, true));
438 }
439 }
440 }
441 if response.clicked() || response.drag_started() {
442 response.request_focus();
443 }
444 let mut keyed = |steps: f32, cause: Cause| {
445 if steps == 0.0 {
446 return;
447 }
448 let to = Drag {
449 at: None,
450 delta: steps * step,
451 };
452 if let Some(c) = change::decide(hook, change_of(Drag::default(), to, cause, true)) {
453 changes.push(c);
454 }
455 };
456 if response.has_focus() {
457 change::lock_arrows(ui, response.id);
458 let [x, _] = change::arrows(ui);
459 keyed(x * change::scale(ui), Cause::Key);
460 }
461 keyed(change::access_steps(ui, response.id), Cause::Access);
462}
463
464fn paint(
466 ui: &Ui,
467 rect: Rect,
468 response: &Response,
469 channels: &[Channel<'_>],
470 log: bool,
471 clipping: Option<Clipping>,
472 draggable: bool,
473) {
474 if !ui.is_rect_visible(rect) {
475 return;
476 }
477 let t = HistogramTokens::of(ui.ctx());
478 let tokens = Tokens::of(ui.ctx());
479 let radius = tokens.radius.widget;
480 let painter = ui.painter_at(rect);
481 painter.rect_filled(rect, radius, t.background);
482 let hair = 1.0 / ui.ctx().pixels_per_point();
483 for q in 1..4 {
484 let x = rect.left() + rect.width() * q as f32 / 4.0;
485 painter.line_segment(
486 [Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom())],
487 Stroke::new(hair, t.grid),
488 );
489 }
490 let max = channels
491 .iter()
492 .flat_map(|c| c.bins.iter().copied())
493 .fold(0.0f32, f32::max);
494 for c in channels {
495 let h = heights(c.bins, max, log);
496 if h.is_empty() {
497 continue;
498 }
499 let n = h.len() as f32;
500 let at = |i: usize, v: f32| {
501 Pos2::new(
502 rect.left() + rect.width() * (i as f32 + 0.5) / n,
503 rect.bottom() - rect.height() * v,
504 )
505 };
506 let fill = c.color.gamma_multiply(0.35);
509 let mut mesh = Mesh::default();
510 for (i, v) in h.iter().enumerate() {
511 let top = at(i, *v);
512 let base = mesh.vertices.len() as u32;
513 mesh.vertices.push(Vertex {
514 pos: top,
515 uv: WHITE_UV,
516 color: fill,
517 });
518 mesh.vertices.push(Vertex {
519 pos: Pos2::new(top.x, rect.bottom()),
520 uv: WHITE_UV,
521 color: fill,
522 });
523 if i > 0 {
524 mesh.add_triangle(base - 2, base - 1, base);
525 mesh.add_triangle(base - 1, base + 1, base);
526 }
527 }
528 painter.add(Shape::mesh(mesh));
529 let line: Vec<Pos2> = h.iter().enumerate().map(|(i, v)| at(i, *v)).collect();
530 painter.add(Shape::line(line, Stroke::new(1.0, c.color)));
531 }
532 if let Some(clip) = clipping {
533 let side = (rect.height() * 0.12).clamp(6.0, 12.0);
534 let inset = 2.0;
535 let marker = |corner: Pos2, inward: f32, color: Color32, lit: bool| {
536 let points = vec![
537 corner,
538 corner + vec2(0.0, -side),
539 corner + vec2(inward * side, 0.0),
540 ];
541 if lit {
542 painter.add(Shape::convex_polygon(points, color, Stroke::NONE));
543 } else {
544 painter.add(Shape::closed_line(points, Stroke::new(hair, t.grid)));
545 }
546 };
547 marker(
548 pos2(rect.left() + inset, rect.bottom() - inset),
549 1.0,
550 t.clip_shadows,
551 clip.shadows > 0.0,
552 );
553 marker(
554 pos2(rect.right() - inset, rect.bottom() - inset),
555 -1.0,
556 t.clip_highlights,
557 clip.highlights > 0.0,
558 );
559 }
560 if draggable {
561 if response.has_focus() {
562 egui_pop_core::focus::own_ring(&response.ctx, response.id);
563 }
564 if egui_pop_core::focus::shows_ring(response) {
565 painter.rect_stroke(
566 rect,
567 radius,
568 Stroke::new(2.0, tokens.focus_ring),
569 StrokeKind::Inside,
570 );
571 } else if response.hovered() {
572 let visuals = ui.style().interact(response);
573 painter.rect_stroke(rect, radius, visuals.bg_stroke, StrokeKind::Inside);
574 }
575 }
576}
577
578fn value_text(
580 ctx: &egui::Context,
581 names: &[&str],
582 bins: usize,
583 log: bool,
584 clipping: Option<Clipping>,
585) -> String {
586 let mut value = strings::tr_with(
587 ctx,
588 if log {
589 &crate::strings::HISTOGRAM_VALUE_LOG
590 } else {
591 &crate::strings::HISTOGRAM_VALUE
592 },
593 &[
594 ("channels", Arg::Str(&names.join(", "))),
595 ("bins", bins.into()),
596 ],
597 );
598 if let Some(clip) = clipping {
599 for (fraction, key) in [
600 (clip.shadows, &crate::strings::HISTOGRAM_CLIPPED_SHADOWS),
601 (
602 clip.highlights,
603 &crate::strings::HISTOGRAM_CLIPPED_HIGHLIGHTS,
604 ),
605 ] {
606 if fraction > 0.0 {
607 let percent = strings::number(ctx, f64::from(fraction) * 100.0, 1);
608 value.push_str(", ");
609 value.push_str(&strings::tr_args(ctx, key, &[("percent", &percent)]));
610 }
611 }
612 }
613 value
614}
615
616pub fn heights(bins: &[f32], max: f32, log: bool) -> Vec<f32> {
618 if max <= 0.0 {
619 return vec![0.0; bins.len()];
620 }
621 bins.iter()
622 .map(|b| {
623 let b = b.max(0.0);
624 if log {
625 (1.0 + b).ln() / (1.0 + max).ln()
626 } else {
627 b / max
628 }
629 })
630 .collect()
631}
632
633#[cfg(test)]
634mod tests {
635 use super::*;
636
637 #[test]
638 fn heights_are_normalised_linear_or_log() {
639 assert_eq!(heights(&[0.0, 5.0, 10.0], 10.0, false), vec![0.0, 0.5, 1.0]);
640 let l = heights(&[0.0, 1.0, 100.0], 100.0, true);
641 assert_eq!(l[0], 0.0);
642 assert!((l[2] - 1.0).abs() < 1e-6);
643 assert!(l[1] > 0.1, "small counts stay visible: {}", l[1]);
644 assert_eq!(heights(&[1.0], 0.0, false), vec![0.0]);
645 }
646
647 #[test]
648 fn a_drag_round_trips_through_json() {
649 for d in [
650 Drag {
651 at: Some(0.75),
652 delta: -0.25,
653 },
654 Drag {
655 at: None,
656 delta: 0.01,
657 },
658 ] {
659 assert_eq!(Drag::from_json(&d.to_json()), Some(d));
660 }
661 }
662}