Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rust: Concrete renderers #4137

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions core/embed/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ build = "build.rs"
[features]
default = ["model_tt"]
crypto = ["zeroize"]
model_tt = ["jpeg"]
model_tr = []
model_mercury = ["jpeg", "dma2d"]
model_tt = ["jpeg", "touch"]
model_tr = ["button"]
model_mercury = ["jpeg", "dma2d", "touch", "new_rendering"]
micropython = []
protobuf = ["micropython"]
ui = []
Expand Down Expand Up @@ -93,7 +93,7 @@ debug = 2

[dependencies]
qrcodegen = { version = "1.8.0", path = "../../vendor/QR-Code-generator/rust-no-heap" }
spin = { version = "0.9.8", features = ["rwlock"], default-features = false }
spin = { version = "0.9.8", features = ["mutex", "rwlock", "spin_mutex"], default-features = false }
trezor-tjpgdec = { version = "0.1.0", path = "../../../rust/trezor-tjpgdec" }
ufmt = "0.2.0"
zeroize = { version = "1.7.0", default-features = false, optional = true }
Expand Down
1 change: 1 addition & 0 deletions core/embed/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ mod trace;
#[cfg(feature = "translations")]
mod translations;
mod trezorhal;
mod util;

// mod ui is `pub` because of the re-export pattern in individual models, which
// would trigger a brickload of "unused symbol" warnings otherwise.
Expand Down
63 changes: 52 additions & 11 deletions core/embed/rust/src/trezorhal/display.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use super::ffi;
use core::{ops::DerefMut, ptr};
use cty::c_int;
use spin::MutexGuard;

use crate::trezorhal::buffers::BufferText;
use crate::{trezorhal::buffers::BufferText, util::Lock};

pub use ffi::{DISPLAY_RESX, DISPLAY_RESY};

Expand Down Expand Up @@ -181,16 +182,56 @@ pub fn clear() {
}
}

#[cfg(feature = "xframebuffer")]
pub fn get_frame_buffer() -> (&'static mut [u8], usize) {
let fb_info = unsafe { ffi::display_get_frame_buffer() };
static X_FRAMEBUFFER_LOCK: Lock<()> = Lock::new(());

pub struct XFrameBuffer<'a> {
guard: MutexGuard<'a, ()>,
buf: &'a mut [u8],
stride: usize,
}

impl XFrameBuffer<'_> {
pub fn lock() -> Self {
let guard = X_FRAMEBUFFER_LOCK.lock();

#[cfg(not(feature = "xframebuffer"))]
{
static mut EMPTY: [u8; 0] = [];
let buf = unsafe { &mut *ptr::addr_of_mut!(EMPTY) };
return Self {
guard,
buf: &mut buf[..],
stride: 0,
};
}

#[cfg(feature = "xframebuffer")]
{
let fb_info = unsafe { ffi::display_get_frame_buffer() };

let fb = unsafe {
core::slice::from_raw_parts_mut(
fb_info.ptr as *mut u8,
DISPLAY_RESY as usize * fb_info.stride,
)
};
Self {
guard,
buf: fb,
stride: fb_info.stride,
}
}
}

let fb = unsafe {
core::slice::from_raw_parts_mut(
fb_info.ptr as *mut u8,
DISPLAY_RESY as usize * fb_info.stride,
)
};
pub unsafe fn force_unlock() {
unsafe { X_FRAMEBUFFER_LOCK.force_unlock() };
}

(fb, fb_info.stride)
pub fn buf(&mut self) -> &mut [u8] {
self.buf
}

pub fn stride(&self) -> usize {
self.stride
}
}
1 change: 1 addition & 0 deletions core/embed/rust/src/trezorhal/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod bip39;
#[macro_use]
#[allow(unused_macros)]
#[cfg(feature = "ui")]
pub mod fatal_error;
#[cfg(feature = "ui")]
pub mod bitblt;
Expand Down
2 changes: 1 addition & 1 deletion core/embed/rust/src/ui/component/cached_jpeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl CachedJpeg {

let mut buf = unwrap!(ImageBuffer::new(size), "no image buf");

render_on_canvas(buf.canvas(), None, |target| {
render_on_canvas!(buf.canvas(), None, |target| {
shape::JpegImage::new_image(Point::zero(), image)
.with_scale(scale)
.render(target);
Expand Down
5 changes: 4 additions & 1 deletion core/embed/rust/src/ui/flow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ pub mod base;
pub mod page;
mod swipe;

use super::{model_mercury::ModelMercuryFeatures, UIFeaturesCommon};

pub use base::{FlowMsg, FlowState, Swipable};
pub use page::SwipePage;
pub use swipe::SwipeFlow;

pub type SwipeFlow = swipe::SwipeFlow<<ModelMercuryFeatures as UIFeaturesCommon>::Display>;
55 changes: 18 additions & 37 deletions core/embed/rust/src/ui/flow/swipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
},
ui::{
component::{
base::{AttachType, AttachType::Swipe},
base::AttachType::{self, Swipe},
swipe_detect::SwipeSettings,
Component, Event, EventCtx, SwipeDetect, SwipeDetectMsg, SwipeDirection,
},
Expand All @@ -16,7 +16,7 @@ use crate::{
flow::{base::Decision, FlowMsg, FlowState},
geometry::Rect,
layout::obj::ObjComponent,
shape::{render_on_display, ConcreteRenderer, Renderer, ScopedRenderer},
shape::{render_on_display, Display},
util::animation_disabled,
},
};
Expand All @@ -29,10 +29,10 @@ use heapless::Vec;
///
/// This copies the Component interface, but it is parametrized by a concrete
/// Renderer type, making it object-safe.
pub trait FlowComponentTrait<'s, R: Renderer<'s>>: Swipable {
pub trait FlowComponentTrait<D: Display>: Swipable {
fn place(&mut self, bounds: Rect) -> Rect;
fn event(&mut self, ctx: &mut EventCtx, event: Event) -> Option<FlowMsg>;
fn render(&'s self, target: &mut R);
fn render<'s>(&'s self, target: &mut D::Renderer<'_, '_, 's>);

#[cfg(feature = "ui_debug")]
fn trace(&self, t: &mut dyn crate::trace::Tracer);
Expand All @@ -44,10 +44,10 @@ pub trait FlowComponentTrait<'s, R: Renderer<'s>>: Swipable {
/// * also implement Swipable, required by FlowComponentTrait,
/// * use FlowMsg as their Msg type,
/// * implement MaybeTrace to be able to conform to ObjComponent.
impl<'s, R, C> FlowComponentTrait<'s, R> for C
impl<C, D> FlowComponentTrait<D> for C
where
C: Component<Msg = FlowMsg> + MaybeTrace + Swipable,
R: Renderer<'s>,
D: Display,
{
fn place(&mut self, bounds: Rect) -> Rect {
<Self as Component>::place(self, bounds)
Expand All @@ -57,7 +57,7 @@ where
<Self as Component>::event(self, ctx, event)
}

fn render(&'s self, target: &mut R) {
fn render<'bumps>(&'bumps self, target: &mut D::Renderer<'_, '_, 'bumps>) {
<Self as Component>::render(self, target)
}

Expand All @@ -67,25 +67,6 @@ where
}
}

/// Shortcut type for the concrete renderer passed into `render()` method.
type RendererImpl<'a, 'alloc, 'env> = ScopedRenderer<'alloc, 'env, ConcreteRenderer<'a, 'alloc>>;

/// Fully object-safe component-like trait for flow components.
///
/// This trait has no generic parameters:
/// * it is instantiated with a concrete Renderer type, and
/// * it requires the `FlowComponentTrait` trait to be implemented for _any_
/// lifetimes.
pub trait FlowComponentDynTrait:
for<'a, 'alloc, 'env> FlowComponentTrait<'alloc, RendererImpl<'a, 'alloc, 'env>>
{
}

impl<T> FlowComponentDynTrait for T where
T: for<'a, 'alloc, 'env> FlowComponentTrait<'alloc, RendererImpl<'a, 'alloc, 'env>>
{
}

/// Swipe flow consisting of multiple screens.
///
/// Implements swipe navigation between the states with animated transitions,
Expand All @@ -94,11 +75,11 @@ impl<T> FlowComponentDynTrait for T where
/// If a swipe is detected:
/// - currently active component is asked to handle the event,
/// - if it can't then FlowState::handle_swipe is consulted.
pub struct SwipeFlow {
pub struct SwipeFlow<D: Display> {
/// Current state of the flow.
state: &'static dyn FlowState,
/// Store of all screens which are part of the flow.
store: Vec<GcBox<dyn FlowComponentDynTrait>, 12>,
store: Vec<GcBox<dyn FlowComponentTrait<D>>, 12>,
/// Swipe detector.
swipe: SwipeDetect,
/// Swipe allowed
Expand All @@ -112,7 +93,7 @@ pub struct SwipeFlow {
decision_override: Option<StateChange>,
}

impl SwipeFlow {
impl<D: Display> SwipeFlow<D> {
pub fn new(initial_state: &'static dyn FlowState) -> Result<Self, error::Error> {
Ok(Self {
state: initial_state,
Expand All @@ -131,20 +112,20 @@ impl SwipeFlow {
pub fn with_page(
mut self,
state: &'static dyn FlowState,
page: impl FlowComponentDynTrait + 'static,
page: impl FlowComponentTrait<D> + 'static,
) -> Result<Self, error::Error> {
debug_assert!(self.store.len() == state.index());
let alloc = GcBox::new(page)?;
let page = gc::coerce!(FlowComponentDynTrait, alloc);
let page = gc::coerce!(FlowComponentTrait<D>, alloc);
unwrap!(self.store.push(page));
Ok(self)
}

fn current_page(&self) -> &GcBox<dyn FlowComponentDynTrait> {
fn current_page(&self) -> &GcBox<dyn FlowComponentTrait<D>> {
&self.store[self.state.index()]
}

fn current_page_mut(&mut self) -> &mut GcBox<dyn FlowComponentDynTrait> {
fn current_page_mut(&mut self) -> &mut GcBox<dyn FlowComponentTrait<D>> {
&mut self.store[self.state.index()]
}

Expand All @@ -170,7 +151,7 @@ impl SwipeFlow {
ctx.request_paint();
}

fn render_state<'s>(&'s self, state: usize, target: &mut RendererImpl<'_, 's, '_>) {
fn render_state<'s>(&'s self, state: usize, target: &mut D::Renderer<'_, '_, 's>) {
self.store[state].render(target);
}

Expand Down Expand Up @@ -346,7 +327,7 @@ impl SwipeFlow {
/// `FlowMsg` as their `Component::Msg` (provided by `impl FlowComponentTrait`
/// earlier in this file).
#[cfg(feature = "micropython")]
impl ObjComponent for SwipeFlow {
impl<D: Display> ObjComponent for SwipeFlow<D> {
fn obj_place(&mut self, bounds: Rect) -> Rect {
for elem in self.store.iter_mut() {
elem.place(bounds);
Expand All @@ -371,14 +352,14 @@ impl ObjComponent for SwipeFlow {
}
}
fn obj_paint(&mut self) {
render_on_display(None, Some(Color::black()), |target| {
render_on_display!(D, Color::black(), |target| {
self.render_state(self.state.index(), target);
});
}
}

#[cfg(feature = "ui_debug")]
impl crate::trace::Trace for SwipeFlow {
impl<D: Display> crate::trace::Trace for SwipeFlow<D> {
fn trace(&self, t: &mut dyn crate::trace::Tracer) {
self.current_page().trace(t)
}
Expand Down
12 changes: 9 additions & 3 deletions core/embed/rust/src/ui/layout/obj.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ use crate::{
constant, display,
event::USBEvent,
geometry::Rect,
ui_features::ModelUI,
UIFeaturesCommon,
},
};

Expand Down Expand Up @@ -120,9 +122,13 @@ where

#[cfg(feature = "new_rendering")]
{
render_on_display(None, Some(Color::black()), |target| {
self.render(target);
});
render_on_display!(
<ModelUI as UIFeaturesCommon>::Display,
Color::black(),
|target| {
self.render(target);
}
);
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions core/embed/rust/src/ui/layout/simplified.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ fn touch_eval() -> Option<TouchEvent> {
TouchEvent::new(event_type, ex as _, ey as _).ok()
}

fn render(frame: &mut impl Component) {
fn render<U: UIFeaturesCommon>(frame: &mut impl Component) {
#[cfg(not(feature = "new_rendering"))]
{
display::sync();
Expand All @@ -78,7 +78,7 @@ fn render(frame: &mut impl Component) {
#[cfg(feature = "new_rendering")]
{
display::sync();
render_on_display(None, Some(Color::black()), |target| {
render_on_display!(U::Display, Color::black(), |target| {
frame.render(target);
});
display::refresh();
Expand All @@ -88,7 +88,7 @@ fn render(frame: &mut impl Component) {
pub fn run(frame: &mut impl Component<Msg = impl ReturnToC>) -> u32 {
frame.place(ModelUI::SCREEN);
ModelUI::fadeout();
render(frame);
render::<ModelUI>(frame);
ModelUI::fadein();

#[cfg(feature = "button")]
Expand All @@ -109,7 +109,7 @@ pub fn run(frame: &mut impl Component<Msg = impl ReturnToC>) -> u32 {
if let Some(message) = msg {
return message.return_to_c();
}
render(frame);
render::<ModelUI>(frame);
}
}
}
Expand All @@ -121,7 +121,7 @@ pub fn show(frame: &mut impl Component, fading: bool) {
ModelUI::fadeout()
};

render(frame);
render::<ModelUI>(frame);

if fading {
ModelUI::fadein()
Expand Down
Loading
Loading