Add Predrawn widget

This commit is contained in:
Joscha 2023-04-06 00:48:53 +02:00
parent ea6be7bf32
commit 88e66e17ec
2 changed files with 88 additions and 0 deletions

View file

@ -8,6 +8,7 @@ pub mod float;
pub mod join;
pub mod layer;
pub mod padding;
pub mod predrawn;
pub mod resize;
pub mod text;
@ -21,5 +22,6 @@ pub use float::*;
pub use join::*;
pub use layer::*;
pub use padding::*;
pub use predrawn::*;
pub use resize::*;
pub use text::*;

86
src/widgets/predrawn.rs Normal file
View file

@ -0,0 +1,86 @@
use std::mem;
use async_trait::async_trait;
use crate::buffer::Buffer;
use crate::{AsyncWidget, Frame, Pos, Size, Style, Styled, Widget, WidthDb};
pub struct Predrawn {
buffer: Buffer,
}
impl Predrawn {
pub fn new<E, W: Widget<E>>(inner: W, frame: &mut Frame) -> Result<Self, E> {
let mut tmp_frame = Frame::default();
tmp_frame.buffer.resize(frame.size());
mem::swap(&mut frame.widthdb, &mut tmp_frame.widthdb);
inner.draw(&mut tmp_frame)?;
mem::swap(&mut frame.widthdb, &mut tmp_frame.widthdb);
let buffer = tmp_frame.buffer;
Ok(Self { buffer })
}
pub async fn new_async<E, W: AsyncWidget<E>>(inner: W, frame: &mut Frame) -> Result<Self, E> {
let mut tmp_frame = Frame::default();
tmp_frame.buffer.resize(frame.size());
mem::swap(&mut frame.widthdb, &mut tmp_frame.widthdb);
inner.draw(&mut tmp_frame).await?;
mem::swap(&mut frame.widthdb, &mut tmp_frame.widthdb);
let buffer = tmp_frame.buffer;
Ok(Self { buffer })
}
pub fn size(&self) -> Size {
self.buffer.size()
}
fn draw_impl(&self, frame: &mut Frame) {
for (x, y, cell) in self.buffer.cells() {
let pos = Pos::new(x.into(), y.into());
let style = Style {
content_style: cell.style,
opaque: true,
};
frame.write(pos, Styled::new(&cell.content, style));
}
}
}
impl<E> Widget<E> for Predrawn {
fn size(
&self,
_widthdb: &mut WidthDb,
_max_width: Option<u16>,
_max_height: Option<u16>,
) -> Result<Size, E> {
Ok(self.buffer.size())
}
fn draw(self, frame: &mut Frame) -> Result<(), E> {
self.draw_impl(frame);
Ok(())
}
}
#[async_trait]
impl<E> AsyncWidget<E> for Predrawn {
async fn size(
&self,
_widthdb: &mut WidthDb,
_max_width: Option<u16>,
_max_height: Option<u16>,
) -> Result<Size, E> {
Ok(self.buffer.size())
}
async fn draw(self, frame: &mut Frame) -> Result<(), E> {
self.draw_impl(frame);
Ok(())
}
}