1use std::rc::Rc;
2
3use cranpose_ui_graphics::{CommandRecording, DrawPrimitive, DrawScope, DrawScopeDefault};
4
5use crate::{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}
25
26pub fn command_draw_scope(size: Size) -> DrawScopeDefault {
29 DrawScopeDefault::with_text_measurer(size, AppContextTextMeasurer::shared())
30}
31
32pub fn command_draw_scope_reusing(size: Size, storage: CommandRecording) -> DrawScopeDefault {
36 DrawScopeDefault::with_text_measurer_reusing(size, AppContextTextMeasurer::shared(), storage)
37}
38
39#[derive(Default, Clone)]
41pub struct DrawCacheBuilder {
42 behind: Vec<DrawCommandFn>,
43 with_content: Vec<DrawCommandFn>,
44 overlay: Vec<DrawCommandFn>,
45}
46
47impl DrawCacheBuilder {
48 pub fn on_draw_behind(&mut self, f: impl Fn(&mut dyn DrawScope) + 'static) {
50 self.behind
51 .push(Rc::new(move |scope: &mut DrawScopeDefault| f(scope)));
52 }
53
54 pub fn finish(self) -> Vec<DrawCommand> {
56 let mut commands = Vec::new();
57 commands.extend(self.behind.into_iter().map(DrawCommand::Behind));
58 commands.extend(self.with_content.into_iter().map(DrawCommand::WithContent));
59 commands.extend(self.overlay.into_iter().map(DrawCommand::Overlay));
60 commands
61 }
62}
63
64pub fn execute_draw_commands(commands: &[DrawCommand], size: Size) -> Vec<DrawPrimitive> {
66 let mut primitives = Vec::new();
67 for command in commands {
68 match command {
69 DrawCommand::Behind(f) | DrawCommand::WithContent(f) | DrawCommand::Overlay(f) => {
70 let mut scope = command_draw_scope(size);
71 f(&mut scope);
72 primitives.extend(scope.into_primitives());
73 }
74 }
75 }
76 primitives
77}