use std::collections::BTreeMap;
use crate::paint::PaintOp;
use super::caps::BackendCapabilities;
use super::traits::{PageSize, RenderBackend, RenderBackendError};
use super::util::{paint_op_kind, PageState};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DrawStats {
pub pages: usize,
pub ops: usize,
pub per_kind: BTreeMap<&'static str, usize>,
}
impl DrawStats {
pub fn count_of(&self, kind: &str) -> usize {
self.per_kind.get(kind).copied().unwrap_or(0)
}
}
#[derive(Debug, Clone, Default)]
pub struct NullBackend {
state: PageState,
stats: DrawStats,
}
impl NullBackend {
pub fn new() -> Self {
Self::default()
}
pub fn stats(&self) -> &DrawStats {
&self.stats
}
}
impl RenderBackend for NullBackend {
type Output = DrawStats;
type Error = RenderBackendError;
fn capabilities(&self) -> BackendCapabilities {
BackendCapabilities {
multi_page: true,
deterministic: true,
..BackendCapabilities::none("null")
}
}
fn begin_page(&mut self, size: PageSize) -> Result<(), Self::Error> {
self.state.begin(size)
}
fn draw(&mut self, op: &PaintOp) -> Result<(), Self::Error> {
self.state.record_draw()?;
self.stats.ops += 1;
*self.stats.per_kind.entry(paint_op_kind(op)).or_insert(0) += 1;
Ok(())
}
fn end_page(&mut self) -> Result<(), Self::Error> {
self.state.end()?;
self.stats.pages += 1;
Ok(())
}
fn finish(self) -> Result<Self::Output, Self::Error> {
self.state.assert_finished()?;
Ok(self.stats)
}
fn finish_boxed(self: Box<Self>) -> Result<Self::Output, Self::Error> {
(*self).finish()
}
}
#[derive(Debug, Clone, Default)]
pub struct TraceBackend {
state: PageState,
lines: Vec<String>,
}
impl TraceBackend {
pub fn new() -> Self {
Self::default()
}
pub fn lines(&self) -> &[String] {
&self.lines
}
pub fn trace(&self) -> String {
self.lines.join("\n")
}
}
impl RenderBackend for TraceBackend {
type Output = String;
type Error = RenderBackendError;
fn capabilities(&self) -> BackendCapabilities {
BackendCapabilities {
multi_page: true,
deterministic: true,
..BackendCapabilities::none("trace")
}
}
fn begin_page(&mut self, size: PageSize) -> Result<(), Self::Error> {
self.state.begin(size)?;
self.lines
.push(format!("begin_page {:.2}x{:.2}", size.width, size.height));
Ok(())
}
fn draw(&mut self, op: &PaintOp) -> Result<(), Self::Error> {
self.state.record_draw()?;
let b = op.bounds();
self.lines.push(format!(
" {} bbox={:.2},{:.2},{:.2},{:.2}",
paint_op_kind(op),
b.x,
b.y,
b.width,
b.height
));
Ok(())
}
fn end_page(&mut self) -> Result<(), Self::Error> {
let (_, ops) = self.state.end()?;
self.lines.push(format!("end_page ops={ops}"));
Ok(())
}
fn finish(self) -> Result<Self::Output, Self::Error> {
self.state.assert_finished()?;
Ok(self.lines.join("\n"))
}
fn finish_boxed(self: Box<Self>) -> Result<Self::Output, Self::Error> {
(*self).finish()
}
}