1use std::rc::Rc;
2
3use cranpose_ui_graphics::{CommandRecording, DrawPrimitive, DrawScope, DrawScopeDefault};
4
5use crate::{BackgroundDraw, modifier::Size, text::AppContextTextMeasurer};
6
7pub type DrawCommandFn = Rc<dyn Fn(&mut DrawScopeDefault)>;
13
14#[derive(Clone)]
16pub enum DrawCommand {
17 Behind(DrawCommandFn),
19 WithContent(DrawCommandFn),
22 Overlay(DrawCommandFn),
24 Background(BackgroundDraw),
26}
27
28impl DrawCommand {
29 pub fn draw(&self, scope: &mut DrawScopeDefault) {
32 match self {
33 Self::Behind(f) | Self::WithContent(f) | Self::Overlay(f) => f(scope),
34 Self::Background(background) => background.draw(scope),
35 }
36 }
37
38 pub(crate) fn same_as(&self, other: &Self) -> bool {
41 match (self, other) {
42 (Self::Behind(a), Self::Behind(b))
43 | (Self::WithContent(a), Self::WithContent(b))
44 | (Self::Overlay(a), Self::Overlay(b)) => Rc::ptr_eq(a, b),
45 (Self::Background(a), Self::Background(b)) => a.same_as(b),
46 _ => false,
47 }
48 }
49}
50
51pub fn command_draw_scope(size: Size, recording: &mut CommandRecording) -> DrawScopeDefault<'_> {
56 DrawScopeDefault::with_text_measurer(size, AppContextTextMeasurer::shared(), recording)
57}
58
59#[derive(Default, Clone)]
61pub struct DrawCacheBuilder {
62 behind: Vec<DrawCommandFn>,
63 with_content: Vec<DrawCommandFn>,
64 overlay: Vec<DrawCommandFn>,
65}
66
67impl DrawCacheBuilder {
68 pub fn on_draw_behind(&mut self, f: impl Fn(&mut dyn DrawScope) + 'static) {
70 self.behind
71 .push(Rc::new(move |scope: &mut DrawScopeDefault| f(scope)));
72 }
73
74 pub fn finish(self) -> Vec<DrawCommand> {
76 let mut commands = Vec::new();
77 commands.extend(self.behind.into_iter().map(DrawCommand::Behind));
78 commands.extend(self.with_content.into_iter().map(DrawCommand::WithContent));
79 commands.extend(self.overlay.into_iter().map(DrawCommand::Overlay));
80 commands
81 }
82}
83
84pub fn execute_draw_commands(commands: &[DrawCommand], size: Size) -> Vec<DrawPrimitive> {
86 let mut primitives = Vec::new();
87 let mut recording = CommandRecording::default();
88 for command in commands {
89 let mut scope = command_draw_scope(size, &mut recording);
90 command.draw(&mut scope);
91 primitives.extend(scope.into_primitives());
92 }
93 primitives
94}