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)]
15pub enum DrawCommand {
16 Behind(DrawCommandFn),
17 WithContent(DrawCommandFn),
18 Overlay(DrawCommandFn),
19}
20
21pub fn command_draw_scope(size: Size) -> DrawScopeDefault {
24 DrawScopeDefault::with_text_measurer(size, AppContextTextMeasurer::shared())
25}
26
27pub fn command_draw_scope_reusing(size: Size, storage: CommandRecording) -> DrawScopeDefault {
31 DrawScopeDefault::with_text_measurer_reusing(size, AppContextTextMeasurer::shared(), storage)
32}
33
34#[derive(Default, Clone)]
35pub struct DrawCacheBuilder {
36 behind: Vec<DrawCommandFn>,
37 with_content: Vec<DrawCommandFn>,
38 overlay: Vec<DrawCommandFn>,
39}
40
41impl DrawCacheBuilder {
42 pub fn on_draw_behind(&mut self, f: impl Fn(&mut dyn DrawScope) + 'static) {
43 self.behind
44 .push(Rc::new(move |scope: &mut DrawScopeDefault| f(scope)));
45 }
46
47 pub fn finish(self) -> Vec<DrawCommand> {
48 let mut commands = Vec::new();
49 commands.extend(self.behind.into_iter().map(DrawCommand::Behind));
50 commands.extend(self.with_content.into_iter().map(DrawCommand::WithContent));
51 commands.extend(self.overlay.into_iter().map(DrawCommand::Overlay));
52 commands
53 }
54}
55
56pub fn execute_draw_commands(commands: &[DrawCommand], size: Size) -> Vec<DrawPrimitive> {
57 let mut primitives = Vec::new();
58 for command in commands {
59 match command {
60 DrawCommand::Behind(f) | DrawCommand::WithContent(f) | DrawCommand::Overlay(f) => {
61 let mut scope = command_draw_scope(size);
62 f(&mut scope);
63 primitives.extend(scope.into_primitives());
64 }
65 }
66 }
67 primitives
68}