feat(core/caesar): implement new menu navigation
What changed, and why it matters
This commit refactors the on-screen menu and button navigation for the Trezor hardware wallet's 'Caesar' layout. It introduces a new 'Shift' gesture (hold left button, then press right) and moves address details into a context menu. There is no direct evidence in the commit of a security vulnerability; it appears to be a user-interface redesign with corresponding test updates. However, any change to button-handling state machines on a security device warrants careful review because mistakes could, in theory, allow unintended confirmations or menu bypasses.
Treat as a normal UI refactor commit. Conduct a focused security review of the new ButtonController Shift state transitions and the confirm/cancel paths in the BTC GetAddress flow to ensure no unintended confirmation, cancellation, or information-hiding behavior is introduced. No immediate incident response is indicated by the diff itself.
Security signals we found
New button state machine handling simultaneous/hold interactions (Shift mode)
Changes to address confirmation and details UI flow
Changes to debug-link button event injection used in tests
No explicit security fix or vulnerability disclosure in commit message
Evidence from the diff
The patch implements a new menu-navigation system in the Caesar UI: a context menu opened by the left button, a ‘Shift’ mode where holding the left button turns the right button into a scroll-up action, and a numeric page counter. It updates ButtonController state machine with Shifted, ShiftStarted, ShiftedTriggered, and ShiftEnded states; adds menu_shift_icon, close_shift_icon, and related button details; and rewrites AddressDetails to show only a QR code while account/path/xpub data move to a menu-driven info page. The BTC GetAddress flow and debug-link test helpers are updated accordingly. No security bug is visible in the diff, but the new state machine is security-critical and should be formally reviewed for race conditions or incorrect transitions.
Changed components
core/embed/rust/src/ui/layout_caesar/component/button_controller.rscore/embed/rust/src/ui/layout_caesar/component/button.rscore/embed/rust/src/ui/layout_caesar/component/page.rscore/embed/rust/src/ui/layout_caesar/component/address_details.rscore/embed/rust/src/ui/layout_caesar/ui_firmware.rscore/src/trezor/ui/layouts/caesar/__init__.pypython/src/trezorlib/debuglink.pytests/input_flows.pyInspect captured patch +708 / −430
### core/embed/rust/src/ui/layout_caesar/component/address_details.rs
@@ -1,171 +1,34 @@
-use heapless::Vec;
-
-use super::{
- theme, ButtonController, ButtonControllerMsg, ButtonDetails, ButtonLayout, ButtonPos, Frame,
-};
-use crate::micropython::buffer::StrBuffer;
+use super::{theme, ButtonController, ButtonControllerMsg, ButtonDetails, ButtonLayout, ButtonPos};
use crate::micropython::Error;
use crate::strutil::TString;
-use crate::translations::TR;
-use crate::ui::component::text::paragraphs::{
- Paragraph, ParagraphSource, ParagraphVecShort, Paragraphs, VecExt,
-};
-use crate::ui::component::{Child, Component, Event, EventCtx, Pad, Paginate, Qr};
+use crate::ui::component::{Child, Component, Event, EventCtx, Pad, Qr};
use crate::ui::geometry::Rect;
-use crate::ui::layout::util::MAX_XPUBS;
use crate::ui::shape::Renderer;
const QR_BORDER: i16 = 3;
+/// QR code of an address, opened from the context menu. The account
+/// information is shown in its own menu item.
pub struct AddressDetails {
qr_code: Qr,
- details_view: Paragraphs<ParagraphVecShort<'static>>,
- xpub_view: Frame<Paragraphs<Paragraph<'static>>>,
- xpubs: Vec<(StrBuffer, StrBuffer), MAX_XPUBS>,
- current_page: usize,
- current_subpage: usize,
- area: Rect,
pad: Pad,
buttons: Child<ButtonController>,
}
impl AddressDetails {
- pub fn new(
- qr_address: TString<'static>,
- case_sensitive: bool,
- account: Option<(TString<'static>, TString<'static>)>,
- path: Option<(TString<'static>, TString<'static>)>,
- ) -> Result<Self, Error> {
+ pub fn new(qr_address: TString<'static>, case_sensitive: bool) -> Result<Self, Error> {
let qr_code = qr_address
.map(|s| Qr::new(s, case_sensitive))?
.with_border(QR_BORDER);
- let details_view = {
- let mut para = ParagraphVecShort::new();
- if let Some((label, account)) = account {
- para.add(Paragraph::new(&theme::TEXT_BOLD, label));
- para.add(Paragraph::new(&theme::TEXT_MONO, account));
- }
- if let Some((label, path)) = path {
- para.add(Paragraph::new(&theme::TEXT_BOLD, label));
- para.add(Paragraph::new(&theme::TEXT_MONO, path));
- }
- Paragraphs::new(para)
- };
- let xpub_view = Frame::new(
- "".into(),
- Paragraph::new(&theme::TEXT_MONO_DATA, "").into_paragraphs(),
- );
-
- let result = Self {
+ Ok(Self {
qr_code,
- details_view,
- xpub_view,
- xpubs: Vec::new(),
- area: Rect::zero(),
- current_page: 0,
- current_subpage: 0,
pad: Pad::with_background(theme::BG).with_clear(),
- buttons: Child::new(ButtonController::new(ButtonLayout::arrow_none_arrow())),
- };
- Ok(result)
- }
-
- pub fn add_xpub(&mut self, title: StrBuffer, xpub: StrBuffer) -> Result<(), Error> {
- self.xpubs
- .push((title, xpub))
- .map_err(|_| Error::OutOfRange)
- }
-
- fn is_in_subpage(&self) -> bool {
- self.current_subpage > 0
- }
-
- fn is_xpub_page(&self) -> bool {
- self.current_page > 1
- }
-
- fn is_last_page(&self) -> bool {
- self.current_page == self.page_count() - 1
- }
-
- fn is_last_subpage(&mut self) -> bool {
- self.current_subpage == self.subpages_in_current_page() - 1
- }
-
- fn subpages_in_current_page(&mut self) -> usize {
- if self.is_xpub_page() {
- self.xpub_view.pager().total() as usize
- } else {
- 1
- }
- }
-
- /// Button layout for the current page.
- /// Normally there are arrows everywhere, apart from the right side of the
- /// last page. On xpub pages there is SHOW ALL middle button when it
- /// cannot fit one page. On xpub subpages there are wide arrows to
- /// scroll.
- fn get_button_layout(&mut self) -> ButtonLayout {
- let (left, middle, right) = if self.is_in_subpage() {
- let left = Some(ButtonDetails::up_arrow_icon_wide());
- let right = if self.is_last_subpage() {
- None
- } else {
- Some(ButtonDetails::down_arrow_icon_wide())
- };
- (left, None, right)
- } else {
- let left = Some(ButtonDetails::left_arrow_icon());
- let middle = if self.is_xpub_page() && self.subpages_in_current_page() > 1 {
- Some(ButtonDetails::armed_text(TR::buttons__show_all.into()))
- } else {
- None
- };
- let right = if self.is_last_page() {
- None
- } else {
- Some(ButtonDetails::right_arrow_icon())
- };
- (left, middle, right)
- };
- ButtonLayout::new(left, middle, right)
- }
-
- /// Reflecting the current page in the buttons.
- fn update_buttons(&mut self, ctx: &mut EventCtx) {
- let btn_layout = self.get_button_layout();
- self.buttons.mutate(ctx, |_ctx, buttons| {
- buttons.set(btn_layout);
- });
- }
-
- fn page_count(&self) -> usize {
- 2 + self.xpubs.len()
- }
-
- fn fill_xpub_page(&mut self, ctx: &mut EventCtx) {
- let i = self.current_page - 2;
- self.xpub_view.update_title(ctx, self.xpubs[i].0.into());
- self.xpub_view.update_content(ctx, |p| {
- p.update(self.xpubs[i].1);
- p.change_page(0)
- });
- }
-
- fn change_page(&mut self, ctx: &mut EventCtx) {
- if self.is_xpub_page() {
- self.fill_xpub_page(ctx);
- }
- self.pad.clear();
- self.current_subpage = 0;
- }
-
- fn change_subpage(&mut self, ctx: &mut EventCtx) {
- if self.is_xpub_page() {
- self.xpub_view
- .update_content(ctx, |p| p.change_page(self.current_subpage as u16));
- self.pad.clear();
- }
+ buttons: Child::new(ButtonController::new(ButtonLayout::new(
+ Some(ButtonDetails::close_icon()),
+ None,
+ None,
+ ))),
+ })
}
}
@@ -178,86 +41,31 @@ impl Component for AddressDetails {
// Therefore, also placing pad on the whole bounds.
self.qr_code.place(bounds);
self.pad.place(bounds);
- let (content_area, button_area) = bounds.split_bottom(theme::BUTTON_HEIGHT);
- self.details_view.place(content_area);
- self.xpub_view.place(content_area);
+ let (_, button_area) = bounds.split_bottom(theme::BUTTON_HEIGHT);
self.buttons.place(button_area);
- self.area = content_area;
bounds
}
fn event(&mut self, ctx: &mut EventCtx, event: Event) -> Option<Self::Msg> {
- // Possibly update the components that have e.g. marquee
- match self.current_page {
- 0 => self.qr_code.event(ctx, event),
- 1 => self.details_view.event(ctx, event),
- _ => self.xpub_view.event(ctx, event),
- };
-
- let button_event = self.buttons.event(ctx, event);
- if let Some(ButtonControllerMsg::Triggered(button, _)) = button_event {
- if self.is_in_subpage() {
- match button {
- ButtonPos::Left => {
- // Going back
- self.current_subpage -= 1;
- }
- ButtonPos::Right => {
- // Going next
- self.current_subpage += 1;
- }
- _ => unreachable!(),
- }
- self.change_subpage(ctx);
- self.update_buttons(ctx);
- return None;
- } else {
- match button {
- ButtonPos::Left => {
- // Cancelling or going back
- if self.current_page == 0 {
- return Some(());
- }
- self.current_page -= 1;
- self.change_page(ctx);
- }
- ButtonPos::Right => {
- // Going to the next page
- self.current_page += 1;
- self.change_page(ctx);
- }
- ButtonPos::Middle => {
- // Going into subpage
- self.current_subpage = 1;
- self.change_subpage(ctx);
- }
- }
- self.update_buttons(ctx);
- return None;
- }
+ if let Some(ButtonControllerMsg::Triggered(ButtonPos::Left, _)) =
+ self.buttons.event(ctx, event)
+ {
+ return Some(());
}
None
}
fn render<'s>(&'s self, target: &mut impl Renderer<'s>) {
self.pad.render(target);
self.buttons.render(target);
- match self.current_page {
- 0 => self.qr_code.render(target),
- 1 => self.details_view.render(target),
- _ => self.xpub_view.render(target),
- }
+ self.qr_code.render(target);
}
}
#[cfg(feature = "ui_debug")]
impl crate::trace::Trace for AddressDetails {
fn trace(&self, t: &mut dyn crate::trace::Tracer) {
t.component("AddressDetails");
- match self.current_page {
- 0 => t.child("qr_code", &self.qr_code),
- 1 => t.child("details_view", &self.details_view),
- _ => t.child("xpub_view", &self.xpub_view),
- }
+ t.child("qr_code", &self.qr_code);
}
}
### core/embed/rust/src/ui/layout_caesar/component/button.rs
@@ -13,6 +13,9 @@ use crate::ui::{constant, shape};
const HALF_SCREEN_BUTTON_WIDTH: i16 = constant::WIDTH / 2 - 1;
+/// How long the left button has to be held to engage "Shift".
+pub const SHIFT_HOLD_MS: u32 = 200;
+
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum ButtonPos {
Left,
@@ -276,6 +279,12 @@ pub struct ButtonDetails {
fixed_width: Option<i16>,
offset: Offset,
pub send_long_press: bool,
+ /// How long the button has to be held to send
+ /// `ButtonControllerMsg::LongPressed`. `None` means the default.
+ pub long_press_ms: Option<u32>,
+ /// Holding this (left) button acts as "Shift", turning the right button
+ /// into its secondary function.
+ pub shift: bool,
}
impl ButtonDetails {
@@ -289,6 +298,8 @@ impl ButtonDetails {
fixed_width: None,
offset: Offset::zero(),
send_long_press: false,
+ long_press_ms: None,
+ shift: false,
}
}
@@ -302,6 +313,8 @@ impl ButtonDetails {
fixed_width: None,
offset: Offset::zero(),
send_long_press: false,
+ long_press_ms: None,
+ shift: false,
}
}
@@ -327,6 +340,41 @@ impl ButtonDetails {
Self::icon(theme::ICON_CANCEL).with_offset(Offset::new(3, -3))
}
+ /// Hamburger icon opening the context menu. No outline.
+ pub fn menu_icon() -> Self {
+ Self::icon(theme::ICON_MENU).with_offset(Offset::new(3, -3))
+ }
+
+ /// Hamburger icon in brackets. Opens the context menu when pressed
+ /// briefly, engages "Shift" when held.
+ pub fn menu_shift_icon() -> Self {
+ Self::icon(theme::ICON_MENU_SHIFT)
+ .with_fixed_width(theme::ICON_MENU_SHIFT.toif.width())
+ .with_offset(Offset::new(0, -3))
+ .with_shift()
+ }
+
+ /// Cross closing the current screen. No outline.
+ pub fn close_icon() -> Self {
+ Self::icon(theme::ICON_CLOSE).with_offset(Offset::new(3, -3))
+ }
+
+ /// Cross in brackets. Closes the current screen when pressed briefly,
+ /// engages "Shift" when held.
+ pub fn close_shift_icon() -> Self {
+ Self::icon(theme::ICON_CLOSE_SHIFT)
+ .with_fixed_width(theme::ICON_CLOSE_SHIFT.toif.width())
+ .with_offset(Offset::new(0, -3))
+ .with_shift()
+ }
+
+ /// Arrow glyph between arms, entering the selected menu item.
+ pub fn menu_select_icon() -> Self {
+ Self::icon(theme::ICON_MID_BUTTON_ARROW_DOWN)
+ .with_arms()
+ .with_fixed_width(theme::ARMED_ICON_WIDTH)
+ }
+
/// Info icon with an outline.
pub fn info_icon() -> Self {
Self::text("i".into())
@@ -370,6 +418,21 @@ impl ButtonDetails {
.with_fixed_width(HALF_SCREEN_BUTTON_WIDTH)
}
+ /// Scrolling down to the next page. Takes half the screen's width.
+ pub fn scroll_down_wide() -> Self {
+ Self::icon(theme::ICON_RIGHT_BUTTON_ARROW_DOWN)
+ .with_outline()
+ .with_fixed_width(HALF_SCREEN_BUTTON_WIDTH)
+ }
+
+ /// Scrolling up to the previous page - the secondary function of the
+ /// right button while "Shift" is held. Takes half the screen's width.
+ pub fn scroll_up_wide() -> Self {
+ Self::icon(theme::ICON_RIGHT_BUTTON_ARROW_UP)
+ .with_outline()
+ .with_fixed_width(HALF_SCREEN_BUTTON_WIDTH)
+ }
+
/// Outline around the button.
pub fn with_outline(mut self) -> Self {
self.decoration = Some(Decoration::Outline);
@@ -413,6 +476,14 @@ impl ButtonDetails {
self.font = font;
self
}
+
+ /// Holding the (left) button engages "Shift" after `SHIFT_HOLD_MS`.
+ pub fn with_shift(mut self) -> Self {
+ self.shift = true;
+ self.send_long_press = true;
+ self.long_press_ms = Some(SHIFT_HOLD_MS);
+ self
+ }
}
/// Holding the button details for all three possible buttons.
### core/embed/rust/src/ui/layout_caesar/component/button_controller.rs
@@ -18,7 +18,7 @@ enum ButtonState {
Nothing,
/// One Button is down when previously nothing was.
/// _ _ ... ↓ _ | _ ↓
- /// NEXT: Nothing, BothDown, HTCNeedsRelease
+ /// NEXT: Nothing, BothDown, HTCNeedsRelease, Shifted
OneDown(PhysicalButton),
/// Both buttons are down ("middle-click").
/// ↓ _ | _ ↓ ... ↓ ↓
@@ -34,6 +34,12 @@ enum ButtonState {
/// ↓ _ | _ ↓ ... ↓ _ | _ ↓
/// NEXT: Nothing
HTCNeedsRelease(PhysicalButton),
+ /// Left button is held as "Shift" (only when it is a shift button, see
+ /// `ButtonDetails::with_shift`). Right button may be down or not; its
+ /// secondary function is triggered when it is released.
+ /// ↓ _ | ↓ ↓
+ /// NEXT: Nothing, HTCNeedsRelease
+ Shifted { right_down: bool },
}
pub enum ButtonControllerMsg {
@@ -47,6 +53,15 @@ pub enum ButtonControllerMsg {
/// Hold-to-confirm button was released prematurely - without triggering
/// LongPressed.
ReleasedWithoutLongPress(ButtonPos),
+ /// Left button was held long enough to engage "Shift".
+ ShiftStarted,
+ /// Right button was pressed and released while "Shift" was held - its
+ /// secondary function should be performed. Repeatable while "Shift" is
+ /// held.
+ ShiftedTriggered,
+ /// Left button was released, ending "Shift". Its primary function is not
+ /// triggered.
+ ShiftEnded,
}
/// Defines what kind of button should be currently used.
@@ -105,30 +120,44 @@ pub struct ButtonContainer {
/// Whether it should even send `ButtonControllerMsg::LongPressed` events
/// (optional)
send_long_press: bool,
+ /// Whether holding the button engages "Shift"
+ shift: bool,
}
impl ButtonContainer {
/// Supplying `None` as `btn_details` marks the button inactive
/// (it can be later activated in `set()`).
+ const DEFAULT_LONG_PRESS_MS: u32 = 1000;
+
pub fn new(pos: ButtonPos, btn_details: Option<ButtonDetails>) -> Self {
- const DEFAULT_LONG_PRESS_MS: u32 = 1000;
- let send_long_press = btn_details.as_ref().is_some_and(|btn| btn.send_long_press);
- Self {
+ let mut container = Self {
pos,
- button_type: btn_details.map(|d| ButtonType::from_button_details(pos, d)),
+ button_type: None,
pressed_since: None,
- long_press_ms: DEFAULT_LONG_PRESS_MS,
+ long_press_ms: Self::DEFAULT_LONG_PRESS_MS,
long_pressed_timer: Timer::new(),
- send_long_press,
- }
+ send_long_press: false,
+ shift: false,
+ };
+ container.set_details(btn_details);
+ container
+ }
+
+ fn set_details(&mut self, btn_details: Option<ButtonDetails>) {
+ self.send_long_press = btn_details.as_ref().is_some_and(|btn| btn.send_long_press);
+ self.long_press_ms = btn_details
+ .as_ref()
+ .and_then(|btn| btn.long_press_ms)
+ .unwrap_or(Self::DEFAULT_LONG_PRESS_MS);
+ self.shift = btn_details.as_ref().is_some_and(|btn| btn.shift);
+ self.button_type = btn_details.map(|d| ButtonType::from_button_details(self.pos, d));
}
/// Changing the state of the button.
///
/// Passing `None` as `btn_details` will mark the button as inactive.
pub fn set(&mut self, btn_details: Option<ButtonDetails>, button_area: Rect) {
- self.send_long_press = btn_details.as_ref().is_some_and(|btn| btn.send_long_press);
- self.button_type = btn_details.map(|d| ButtonType::from_button_details(self.pos, d));
+ self.set_details(btn_details);
if let Some(button_type) = &mut self.button_type {
button_type.place(button_area);
}
@@ -195,6 +224,11 @@ impl ButtonContainer {
}
}
+ /// Whether holding the button engages "Shift".
+ pub fn is_shift(&self) -> bool {
+ self.button_type.is_some() && self.shift
+ }
+
/// Reset the pressed information.
pub fn reset(&mut self) {
self.pressed_since = None;
@@ -284,6 +318,33 @@ impl ButtonController {
self.right_btn.set_pressed(ctx, right);
}
+ /// Showing the buttons pressed or released according to the current
+ /// state. Also useful after the buttons were replaced by `set()` while
+ /// being held.
+ pub fn refresh_pressed(&mut self, ctx: &mut EventCtx) {
+ match self.state {
+ // Not showing anything also when we wait for a release
+ ButtonState::Nothing | ButtonState::HTCNeedsRelease(_) => {
+ self.set_pressed(ctx, false, false, false);
+ }
+ ButtonState::OneDown(down_button) => match down_button {
+ PhysicalButton::Left => {
+ self.set_pressed(ctx, true, false, false);
+ }
+ PhysicalButton::Right => {
+ self.set_pressed(ctx, false, false, true);
+ }
+ _ => {}
+ },
+ ButtonState::BothDown | ButtonState::OneReleased(_) => {
+ self.set_pressed(ctx, false, true, false);
+ }
+ ButtonState::Shifted { right_down } => {
+ self.set_pressed(ctx, true, false, right_down);
+ }
+ }
+ }
+
pub fn highlight_button(&mut self, ctx: &mut EventCtx, pos: ButtonPos) {
match pos {
ButtonPos::Left => self.left_btn.set_pressed(ctx, true),
@@ -445,6 +506,18 @@ impl Component for ButtonController {
return None;
}
}
+ // ↓ ▼ - right pressed before "Shift" engaged by the hold timer
+ // (both pressed almost together): engage it now, so that the
+ // right release performs the secondary function.
+ if which_down == PhysicalButton::Left
+ && b == PhysicalButton::Right
+ && self.left_btn.is_shift()
+ {
+ self.left_btn.reset();
+ self.state = ButtonState::Shifted { right_down: true };
+ self.refresh_pressed(ctx);
+ return Some(ButtonControllerMsg::ShiftStarted);
+ }
// ↓ ↓
if self.handle_middle_button {
self.got_pressed(ctx, ButtonPos::Middle);
@@ -529,29 +602,33 @@ impl Component for ButtonController {
}
_ => (self.state, None),
},
- };
-
- // Updating the visual feedback for the buttons
- match new_state {
- // Not showing anything also when we wait for a release
- ButtonState::Nothing | ButtonState::HTCNeedsRelease(_) => {
- self.set_pressed(ctx, false, false, false);
- }
- ButtonState::OneDown(down_button) => match down_button {
- PhysicalButton::Left => {
- self.set_pressed(ctx, true, false, false);
- }
- PhysicalButton::Right => {
- self.set_pressed(ctx, false, false, true);
+ // ↓ _ | ↓ ↓
+ ButtonState::Shifted { right_down } => match button_event {
+ // ↓ ▼
+ ButtonEvent::ButtonPressed(PhysicalButton::Right) if !right_down => {
+ (ButtonState::Shifted { right_down: true }, None)
}
- _ => {}
+ // ↓ ▲
+ ButtonEvent::ButtonReleased(PhysicalButton::Right) if right_down => (
+ ButtonState::Shifted { right_down: false },
+ Some(ButtonControllerMsg::ShiftedTriggered),
+ ),
+ // ▲ * - leaving "Shift" without triggering anything
+ ButtonEvent::ButtonReleased(PhysicalButton::Left) => (
+ if right_down {
+ ButtonState::HTCNeedsRelease(PhysicalButton::Right)
+ } else {
+ ButtonState::Nothing
+ },
+ Some(ButtonControllerMsg::ShiftEnded),
+ ),
+ _ => (self.state, None),
},
- ButtonState::BothDown | ButtonState::OneReleased(_) => {
- self.set_pressed(ctx, false, true, false);
- }
};
self.state = new_state;
+ // Updating the visual feedback for the buttons
+ self.refresh_pressed(ctx);
event
}
// Timer - handle clickable properties and HoldToConfirm expiration
@@ -560,6 +637,15 @@ impl Component for ButtonController {
ignore_btn_delay.handle_timers(event);
}
if let Some(pos) = self.handle_long_press_timers(event) {
+ if pos == ButtonPos::Left
+ && self.left_btn.is_shift()
+ && self.state == ButtonState::OneDown(PhysicalButton::Left)
+ {
+ // Left button stays highlighted, it is still being held.
+ self.left_btn.reset();
+ self.state = ButtonState::Shifted { right_down: false };
+ return Some(ButtonControllerMsg::ShiftStarted);
+ }
return Some(ButtonControllerMsg::LongPressed(pos));
}
self.handle_htc_expiration(ctx, event)
### core/embed/rust/src/ui/layout_caesar/component/frame.rs
@@ -126,6 +126,12 @@ where
self.title = Some(Child::new(Title::new(title)));
self
}
+
+ /// Showing a numeric "current/total" page counter instead of the dots.
+ pub fn with_numeric_page_counter(mut self) -> Self {
+ self.scrollbar = self.scrollbar.with_numeric();
+ self
+ }
}
impl<T> Component for ScrollableFrame<T>
@@ -145,7 +151,7 @@ where
(bounds, Rect::zero(), Rect::zero())
} else {
let (scrollbar_area, content_area) =
- bounds.split_top(ScrollBar::MAX_DOT_SIZE + constant::LINE_SPACE);
+ bounds.split_top(self.scrollbar.overall_height() + constant::LINE_SPACE);
(content_area, scrollbar_area, Rect::zero())
}
} else {
### core/embed/rust/src/ui/layout_caesar/component/input_methods/choice.rs
@@ -136,12 +136,24 @@ where
/// Need to update the initial button layout.
pub fn with_initial_page_counter(mut self, page_counter: usize) -> Self {
self.page_counter = page_counter;
+ self.reset_initial_buttons();
+ self
+ }
+
+ /// Adjust the choice factory at the very beginning.
+ /// Need to update the initial button layout.
+ pub fn with_choice_factory(mut self, adjust: impl FnOnce(&mut F)) -> Self {
+ adjust(&mut self.choices);
+ self.reset_initial_buttons();
+ self
+ }
+
+ fn reset_initial_buttons(&mut self) {
let initial_btn_layout = self.get_current_item().btn_layout();
self.buttons = Child::new(
ButtonController::new(initial_btn_layout)
.with_ignore_btn_delay(constant::IGNORE_OTHER_BTN_MS),
);
- self
}
pub fn with_controls(mut self, controls: ChoiceControls) -> Self {
### core/embed/rust/src/ui/layout_caesar/component/input_methods/simple_choice.rs
@@ -23,6 +23,9 @@ struct ChoiceFactorySimple {
choices: Vec<TString<'static>, MAX_LENGTH>,
controls: ChoiceControls,
select_text: TString<'static>,
+ /// Using the context menu buttons - arrow glyph to enter an item, cross to
+ /// close the menu.
+ menu_buttons: bool,
}
impl ChoiceFactorySimple {
@@ -35,6 +38,7 @@ impl ChoiceFactorySimple {
choices,
controls,
select_text,
+ menu_buttons: false,
}
}
@@ -53,15 +57,27 @@ impl ChoiceFactory for ChoiceFactorySimple {
fn get(&self, choice_index: usize) -> (Self::Item, Self::Action) {
let text = &self.choices[choice_index];
- let mut choice_item =
- text.map(|t| ChoiceItem::new(t, ButtonLayout::arrow_armed_arrow(self.select_text)));
+ let btn_layout = if self.menu_buttons {
+ ButtonLayout::new(
+ Some(ButtonDetails::left_arrow_icon()),
+ Some(ButtonDetails::menu_select_icon()),
+ Some(ButtonDetails::right_arrow_icon()),
+ )
+ } else {
+ ButtonLayout::arrow_armed_arrow(self.select_text)
+ };
+ let mut choice_item = text.map(|t| ChoiceItem::new(t, btn_layout));
// Disabling prev/next buttons for the first/last choice when not in carousel.
// (could be done to the same item if there is only one)
if self.controls != ChoiceControls::Carousel {
if choice_index == 0 {
if self.controls == ChoiceControls::Cancellable {
- choice_item.set_left_btn(Some(ButtonDetails::cancel_icon()));
+ choice_item.set_left_btn(Some(if self.menu_buttons {
+ ButtonDetails::close_icon()
+ } else {
+ ButtonDetails::cancel_icon()
+ }));
} else {
choice_item.set_left_btn(None);
}
@@ -82,6 +98,8 @@ pub struct SimpleChoice {
page_count: u16,
return_index: bool,
ignore_cancelled: bool,
+ /// Which items are dangerous (e.g. cancelling the whole flow).
+ danger_items: Vec<bool, MAX_LENGTH>,
}
impl SimpleChoice {
@@ -98,6 +116,7 @@ impl SimpleChoice {
page_count,
return_index: false,
ignore_cancelled: false,
+ danger_items: Vec::new(),
}
}
@@ -131,6 +150,16 @@ impl SimpleChoice {
self
}
+ /// Using the context menu buttons - arrow glyph to enter an item, cross to
+ /// close the menu. `danger_items` marks the items that are dangerous.
+ pub fn with_menu_buttons(mut self, danger_items: Vec<bool, MAX_LENGTH>) -> Self {
+ self.choice_page = self.choice_page.with_choice_factory(|choices| {
+ choices.menu_buttons = true;
+ });
+ self.danger_items = danger_items;
+ self
+ }
+
/// Translating the resulting index into actual string choice.
pub fn result_by_index(&self, index: usize) -> TString<'static> {
self.choice_page.choice_factory().get_string(index)
@@ -190,5 +219,10 @@ impl crate::trace::Trace for SimpleChoice {
fn trace(&self, t: &mut dyn crate::trace::Tracer) {
t.component("SimpleChoice");
t.child("choice_page", &self.choice_page);
+ t.in_list("danger_items", &|l| {
+ for danger in self.danger_items.iter() {
+ l.bool(*danger);
+ }
+ });
}
}
### core/embed/rust/src/ui/layout_caesar/component/mod.rs
@@ -61,7 +61,7 @@ pub use input_methods::{
wordlist::{WordlistEntry, WordlistType},
};
#[cfg(feature = "translations")]
-pub use page::ButtonPage;
+pub use page::{ButtonPage, MenuNav};
pub use progress::Progress;
pub use scrollbar::ScrollBar;
#[cfg(feature = "translations")]
### core/embed/rust/src/ui/layout_caesar/component/page.rs
@@ -10,6 +10,17 @@ use crate::ui::geometry::{Insets, Rect};
use crate::ui::shape::Renderer;
use crate::ui::util::Pager;
+/// What the left button does in the menu navigation (see
+/// `ButtonPage::with_menu_nav`).
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum MenuNav {
+ /// Opens the context menu - the screen returns `PageMsg::Info`.
+ Menu,
+ /// Closes the screen, e.g. the one opened from a context menu - the screen
+ /// returns `PageMsg::Cancelled`.
+ Close,
+}
+
pub struct ButtonPage<T>
where
T: Component + Paginate,
@@ -21,6 +32,10 @@ where
back_btn_details: Option<ButtonDetails>,
next_btn_details: Option<ButtonDetails>,
has_menu: bool,
+ /// Menu navigation, replacing the cancel/back/next buttons.
+ menu_nav: Option<MenuNav>,
+ /// Whether the left button is being held as "Shift" (menu navigation only).
+ shift_active: bool,
buttons: Child<ButtonController>,
}
@@ -37,6 +52,8 @@ where
back_btn_details: Some(ButtonDetails::up_arrow_icon()),
next_btn_details: Some(ButtonDetails::down_arrow_icon_wide()),
has_menu: false,
+ menu_nav: None,
+ shift_active: false,
// Setting empty layout for now, we do not yet know the page count.
// Initial button layout will be set in `place()` after we can call
// `content.page_count()`.
@@ -59,6 +76,17 @@ where
self
}
+ /// Navigation with the left button opening a context menu (or closing the
+ /// screen), and the right button scrolling down and finally confirming
+ /// (when there is a confirm button).
+ ///
+ /// Holding the left button on any but the first page engages "Shift", and
+ /// the right button then scrolls up.
+ pub fn with_menu_nav(mut self, menu_nav: MenuNav) -> Self {
+ self.menu_nav = Some(menu_nav);
+ self
+ }
+
pub fn with_back_btn(mut self, btn_details: Option<ButtonDetails>) -> Self {
self.back_btn_details = btn_details;
self
@@ -94,12 +122,20 @@ where
fn update_buttons(&mut self, ctx: &mut EventCtx) {
let pager = self.pager();
let btn_layout = self.get_button_layout(pager.has_prev(), pager.has_next());
- self.buttons.mutate(ctx, |_ctx, buttons| {
+ let shift_active = self.shift_active;
+ self.buttons.mutate(ctx, |ctx, buttons| {
buttons.set(btn_layout);
+ if shift_active {
+ // The new left button is still being held.
+ buttons.refresh_pressed(ctx);
+ }
});
}
fn get_button_layout(&self, has_prev: bool, has_next: bool) -> ButtonLayout {
+ if let Some(menu_nav) = self.menu_nav {
+ return self.get_menu_nav_button_layout(menu_nav, has_prev, has_next);
+ }
let btn_left = if !has_prev {
self.cancel_btn_details.clone()
} else {
@@ -115,6 +151,69 @@ where
};
ButtonLayout::new(btn_left, btn_middle, btn_right)
}
+
+ fn get_menu_nav_button_layout(
+ &self,
+ menu_nav: MenuNav,
+ has_prev: bool,
+ has_next: bool,
+ ) -> ButtonLayout {
+ // The bracketed left icon advertises "Shift", which is offered only when
+ // there is somewhere to scroll up to. It stays while "Shift" is held.
+ let shift = has_prev || self.shift_active;
+ let btn_left = match (menu_nav, shift) {
+ (MenuNav::Menu, false) => ButtonDetails::menu_icon(),
+ (MenuNav::Menu, true) => ButtonDetails::menu_shift_icon(),
+ (MenuNav::Close, false) => ButtonDetails::close_icon(),
+ (MenuNav::Close, true) => ButtonDetails::close_shift_icon(),
+ };
+ let btn_right = if self.shift_active {
+ has_prev.then(ButtonDetails::scroll_up_wide)
+ } else if has_next {
+ Some(ButtonDetails::scroll_down_wide())
+ } else {
+ self.confirm_btn_details.clone()
+ };
+ ButtonLayout::new(Some(btn_left), None, btn_right)
+ }
+
+ fn event_menu_nav(
+ &mut self,
+ ctx: &mut EventCtx,
+ event: Event,
+ menu_nav: MenuNav,
+ ) -> Option<PageMsg<T::Msg>> {
+ match self.buttons.event(ctx, event) {
+ Some(ButtonControllerMsg::Triggered(ButtonPos::Left, _)) => {
+ return Some(match menu_nav {
+ MenuNav::Menu => PageMsg::Info,
+ MenuNav::Close => PageMsg::Cancelled,
+ });
+ }
+ Some(ButtonControllerMsg::Triggered(ButtonPos::Right, _)) => {
+ if self.pager().has_next() {
+ self.next_page();
+ self.change_page(ctx);
+ } else {
+ return Some(PageMsg::Confirmed);
+ }
+ }
+ Some(ButtonControllerMsg::ShiftStarted) => {
+ self.shift_active = true;
+ self.update_buttons(ctx);
+ }
+ Some(ButtonControllerMsg::ShiftedTriggered) if self.pager().has_prev() => {
+ self.prev_page();
+ self.change_page(ctx);
+ }
+ Some(ButtonControllerMsg::ShiftEnded) => {
+ self.shift_active = false;
+ self.update_buttons(ctx);
+ }
+ _ => {}
+ }
+ None
+ }
}
impl<T> Paginate for ButtonPage<T>
@@ -153,7 +252,12 @@ where
fn event(&mut self, ctx: &mut EventCtx, event: Event) -> Option<Self::Msg> {
ctx.set_page_count(self.pager().total());
- if let Some(ButtonControllerMsg::Triggered(pos, _)) = self.buttons.event(ctx, event) {
+ if let Some(menu_nav) = self.menu_nav {
+ if let Some(msg) = self.event_menu_nav(ctx, event, menu_nav) {
+ return Some(msg);
+ }
+ } else if let Some(ButtonControllerMsg::Triggered(pos, _)) = self.buttons.event(ctx, event)
+ {
match pos {
ButtonPos::Left => {
if self.pager().has_prev() {
@@ -210,6 +314,9 @@ where
t.int("page_count", i64::from(self.pager().total()));
t.child("buttons", &self.buttons);
t.child("content", &self.content);
- t.bool("has_menu", self.has_menu && self.pager().is_last());
+ let has_menu = self.has_menu || self.menu_nav == Some(MenuNav::Menu);
+ t.bool("has_menu", has_menu && self.pager().is_last());
+ // The context menu is opened by the left button.
+ t.bool("left_menu", self.menu_nav == Some(MenuNav::Menu));
}
}
### core/embed/rust/src/ui/layout_caesar/component/scrollbar.rs
@@ -1,15 +1,18 @@
use heapless::Vec;
use super::super::theme;
+use crate::strutil::ShortString;
use crate::ui::component::{Component, Event, EventCtx, Never, Pad, Paginate};
-use crate::ui::geometry::{Offset, Point, Rect};
+use crate::ui::geometry::{Alignment, Alignment2D, Offset, Point, Rect};
use crate::ui::shape::{self, Renderer};
use crate::ui::util::Pager;
/// Scrollbar to be painted horizontally at the top right of the screen.
pub struct ScrollBar {
pad: Pad,
pager: Pager,
+ /// Showing a numeric "current/total" counter instead of the dots.
+ numeric: bool,
}
/// Carrying the appearance of the scrollbar dot.
@@ -38,9 +41,16 @@ impl ScrollBar {
Self {
pad: Pad::with_background(theme::BG),
pager: Pager::new(page_count),
+ numeric: false,
}
}
+ /// Showing a numeric "current/total" counter instead of the dots.
+ pub fn with_numeric(mut self) -> Self {
+ self.numeric = true;
+ self
+ }
+
/// Page count will be given later as it is not available yet.
pub fn to_be_filled_later() -> Self {
Self::new(1)
@@ -52,10 +62,25 @@ impl ScrollBar {
/// The width the scrollbar will really occupy.
pub fn overall_width(&self) -> i16 {
+ if self.numeric {
+ // Reserving the same width for the current page as for the total,
+ // so that the counter fits on every page.
+ let (_, total) = self.numeric_parts();
+ return 2 * theme::FONT_HEADER.text_width(&total) + Self::NUMERIC_SEPARATOR_WIDTH;
+ }
let dots_shown = self.pager.total().min(MAX_DOTS);
Self::dots_width(dots_shown)
}
+ /// The height the scrollbar will really occupy.
+ pub fn overall_height(&self) -> i16 {
+ if self.numeric {
+ theme::FONT_HEADER.text_height()
+ } else {
+ Self::MAX_DOT_SIZE
+ }
+ }
+
pub fn set_pager(&mut self, pager: Pager) {
self.pager = pager;
}
@@ -180,6 +205,41 @@ impl ScrollBar {
dots
}
+ /// Space the separator icon takes in the numeric counter (with a 1px gap
+ /// on both sides).
+ const NUMERIC_SEPARATOR_WIDTH: i16 = theme::ICON_PAGE_SEPARATOR.toif.width() + 2;
+
+ fn numeric_parts(&self) -> (ShortString, ShortString) {
+ (
+ uformat!("{}", self.pager.current() + 1),
+ uformat!("{}", self.pager.total()),
+ )
+ }
+
+ /// "current/total" counter, right-aligned.
+ fn render_numeric<'s>(&'s self, target: &mut impl Renderer<'s>) {
+ let (current, total) = self.numeric_parts();
+ let font = theme::FONT_HEADER;
+ let baseline = self.pad.area.top_right() + Offset::y(font.text_height() - 1);
+ let total_left = baseline.x - font.text_width(&total);
+ let current_right = total_left - Self::NUMERIC_SEPARATOR_WIDTH;
+ shape::Text::new(baseline, &total, font)
+ .with_align(Alignment::End)
+ .with_fg(theme::FG)
+ .render(target);
+ shape::ToifImage::new(
+ Point::new(current_right + 1, baseline.y),
+ theme::ICON_PAGE_SEPARATOR.toif,
+ )
+ .with_align(Alignment2D::BOTTOM_LEFT)
+ .with_fg(theme::FG)
+ .render(target);
+ shape::Text::new(Point::new(current_right, baseline.y), ¤t, font)
+ .with_align(Alignment::End)
+ .with_fg(theme::FG)
+ .render(target);
+ }
+
fn render_horizontal<'s>(&'s self, target: &mut impl Renderer<'s>) {
let mut top_right = self.pad.area.top_right();
for dot in self.get_drawable_dots().iter().rev() {
@@ -195,9 +255,14 @@ impl Component for ScrollBar {
fn place(&mut self, bounds: Rect) -> Rect {
// Occupying as little space as possible (according to the number of pages),
// aligning to the right.
+ let offset = if self.numeric {
+ Offset::zero()
+ } else {
+ Offset::y(1) // offset for centering vertically
+ };
let scrollbar_area = Rect::from_top_right_and_size(
- bounds.top_right() + Offset::y(1), // offset for centering vertically
- Offset::new(self.overall_width(), Self::MAX_DOT_SIZE),
+ bounds.top_right() + offset,
+ Offset::new(self.overall_width(), self.overall_height()),
);
self.pad.place(scrollbar_area);
scrollbar_area
@@ -215,7 +280,11 @@ impl Component for ScrollBar {
}
self.pad.render(target);
- self.render_horizontal(target);
+ if self.numeric {
+ self.render_numeric(target);
+ } else {
+ self.render_horizontal(target);
+ }
}
}
### core/embed/rust/src/ui/layout_caesar/theme/mod.rs
@@ -153,6 +153,8 @@ pub const BUTTON_HEIGHT: i16 = BUTTON_CONTENT_HEIGHT + 2 * BUTTON_OUTLINE;
pub const BUTTON_ICON_WIDTH: i16 = BUTTON_HEIGHT;
pub const TITLE_AREA_HEIGHT: i16 = 12;
pub const ARMS_MARGIN: i16 = 2;
+/// Width of an icon between the arms of a middle button.
+pub const ARMED_ICON_WIDTH: i16 = 24;
// How many pixels should be between text and icons.
pub const ELLIPSIS_ICON_MARGIN: i16 = 4;
### core/embed/rust/src/ui/layout_caesar/ui_firmware.rs
@@ -4,7 +4,7 @@ use heapless::Vec;
use super::component::{
AddressDetails, ButtonActions, ButtonDetails, ButtonLayout, ButtonPage, ChoiceControls,
- CoinJoinProgress, ConfirmHomescreen, Flow, FlowPages, Frame, Homescreen, Lockscreen,
+ CoinJoinProgress, ConfirmHomescreen, Flow, FlowPages, Frame, Homescreen, Lockscreen, MenuNav,
NumberInput, Page, PassphraseEntry, PinEntry, Progress, ScrollableFrame, ShareWords, ShowMore,
SimpleChoice, WordlistEntry, WordlistType, SIMPLE_CHOICE_MAX_LENGTH,
};
@@ -27,6 +27,7 @@ use crate::ui::component::{
Component, ComponentExt, Empty, FlowMsg, FormattedText, Label, LineBreaking, Never, PageMsg,
Paginate, Timeout,
};
+use crate::ui::layout::menu_item_intent::MenuItemIntent;
use crate::ui::layout::obj::{LayoutMaybeTrace, LayoutObj, RootComponent};
use crate::ui::layout::util::{ConfirmValueParams, PropsList, RecoveryType};
use crate::ui::notification::Notification;
@@ -89,19 +90,7 @@ impl FirmwareUI for UICaesar {
let verb = verb.unwrap_or(TR::buttons__confirm.into());
let address: TString = address.try_into()?;
- let get_page = move |page_index| {
- assert!(page_index == 0);
- let (btn_layout, btn_actions) = if info_button {
- (
- ButtonLayout::cancel_armed_info(verb),
- ButtonActions::cancel_confirm_info(),
- )
- } else {
- (
- ButtonLayout::cancel_none_text(verb),
- ButtonActions::cancel_none_confirm(),
- )
- };
+ let address_ops = move || {
let mut ops = OpTextLayout::new(theme::TEXT_MONO_DATA);
if let Some(label) = address_label {
// NOTE: need to explicitly turn off the chunkification before rendering the
@@ -118,8 +107,28 @@ impl FirmwareUI for UICaesar {
ops.add_chunkify_text(Some((theme::MONO_CHUNKS, 2)));
}
ops.add_text_with_font(address, fonts::FONT_MONO);
- let formatted = FormattedText::new(ops).vertically_centered();
- Page::new(btn_layout, btn_actions, formatted).with_title(title)
+ FormattedText::new(ops).vertically_centered()
+ };
+
+ if info_button {
+ // The info is in the context menu, opened by the left button.
+ let content = ButtonPage::new(address_ops(), theme::BG)
+ .with_menu_nav(MenuNav::Menu)
+ .with_confirm_btn(Some(ButtonDetails::text(verb)));
+ let frame = ScrollableFrame::new(content)
+ .with_title(title)
+ .with_numeric_page_counter();
+ return LayoutObj::new(frame);
+ }
+
+ let get_page = move |page_index| {
+ assert!(page_index == 0);
+ Page::new(
+ ButtonLayout::cancel_none_text(verb),
+ ButtonActions::cancel_none_confirm(),
+ address_ops(),
+ )
+ .with_title(title)
};
let pages = FlowPages::new(get_page, 1);
@@ -915,20 +924,22 @@ impl FirmwareUI for UICaesar {
items: heapless::Vec<SelectMenuItem, MAX_MENU_ITEMS>,
current: usize,
) -> Result<impl LayoutMaybeTrace, Error> {
- // the entry's intent is not rendered on this model
- let labels: heapless::Vec<TString<'static>, MAX_MENU_ITEMS> =
- items.into_iter().map(|item| item.text).collect();
- // Returning the index of the selected menu item
+ let labels: heapless::Vec<TString<'static>, SIMPLE_CHOICE_MAX_LENGTH> =
+ items.iter().map(|item| item.text).collect();
+ // the entry's intent is not rendered, it is only traced for the tests
+ let danger_items = items
+ .iter()
+ .map(|item| item.intent == MenuItemIntent::Danger)
+ .collect();
+ // Returning the index of the selected menu item. The select text is not
+ // used, the menu buttons show an arrow glyph instead.
let layout = RootComponent::new(
- SimpleChoice::new(
- labels,
- ChoiceControls::Cancellable,
- TR::buttons__view.into(),
- )
- .with_initial_page_counter(current)
- .with_show_incomplete()
- .with_return_index()
- .with_ignore_cancelled(),
+ SimpleChoice::new(labels, ChoiceControls::Cancellable, TString::empty())
+ .with_menu_buttons(danger_items)
+ .with_initial_page_counter(current)
+ .with_show_incomplete()
+ .with_return_index()
+ .with_ignore_cancelled(),
);
Ok(layout)
}
@@ -985,18 +996,12 @@ impl FirmwareUI for UICaesar {
address: TString<'static>,
case_sensitive: bool,
_details_title: TString<'static>,
- account: Option<(TString<'static>, TString<'static>)>,
- path: Option<(TString<'static>, TString<'static>)>,
- xpubs: Obj,
+ _account: Option<(TString<'static>, TString<'static>)>,
+ _path: Option<(TString<'static>, TString<'static>)>,
+ _xpubs: Obj,
) -> Result<impl LayoutMaybeTrace, Error> {
- let mut ad = AddressDetails::new(address, case_sensitive, account, path)?;
-
- for i in IterBuf::new().try_iterate(xpubs)? {
- let [xtitle, text]: [StrBuffer; 2] = util::iter_into_array(i)?;
- ad.add_xpub(xtitle, text)?;
- }
-
- let layout = RootComponent::new(ad);
+ // Only the QR code, the account information has its own menu item.
+ let layout = RootComponent::new(AddressDetails::new(address, case_sensitive)?);
Ok(layout)
}
@@ -1284,23 +1289,24 @@ impl FirmwareUI for UICaesar {
add_paragraphs(&mut paragraphs, None, Some(value.try_into()?), true);
} else {
for para in IterBuf::new().try_iterate(value)? {
- let [key, value, _is_data]: [Obj; 3] = util::iter_into_array(para)?;
+ let [key, value, is_data]: [Obj; 3] = util::iter_into_array(para)?;
+ // Data (e.g. xpubs) is never hyphenated
+ let is_data = is_data.try_into_option::<bool>()?.unwrap_or(false);
add_paragraphs(
&mut paragraphs,
key.try_into_option()?,
value.try_into_option()?,
- false,
+ is_data,
);
}
}
+ // Opened from the context menu, closed by the left button.
let page = ButtonPage::new(paragraphs.into_paragraphs(), theme::BG)
- .with_back_btn(Some(ButtonDetails::left_arrow_icon()))
- .with_next_btn(Some(ButtonDetails::right_arrow_icon()))
- .with_cancel_btn(Some(ButtonDetails::cancel_icon()))
+ .with_menu_nav(MenuNav::Close)
.with_confirm_btn(None);
- let mut frame = ScrollableFrame::new(page);
+ let mut frame = ScrollableFrame::new(page).with_numeric_page_counter();
if !title.is_empty() {
frame = frame.with_title(title);
}
### core/src/apps/debug/__init__.py
@@ -130,9 +130,7 @@ async def _layout_click(x: int, y: int, hold_ms: int = 0) -> None:
ui.CURRENT_LAYOUT.layout.touch_event, io.TOUCH_END, x, y
)
- async def _layout_press_button(
- debug_btn: DebugPhysicalButton, hold_ms: int = 0
- ) -> None:
+ def _physical_buttons(debug_btn: DebugPhysicalButton) -> list[int]:
from trezor.enums import DebugPhysicalButton
buttons = []
@@ -144,6 +142,17 @@ async def _layout_press_button(
elif debug_btn == DebugPhysicalButton.MIDDLE_BTN:
buttons.append(io.BUTTON_LEFT)
buttons.append(io.BUTTON_RIGHT)
+ return buttons
+
+ def _layout_button_event(debug_btn: DebugPhysicalButton, event: int) -> None:
+ assert isinstance(ui.CURRENT_LAYOUT, ui.Layout)
+ for btn in _physical_buttons(debug_btn):
+ ui.CURRENT_LAYOUT._event(ui.CURRENT_LAYOUT.layout.button_event, event, btn)
+
+ async def _layout_press_button(
+ debug_btn: DebugPhysicalButton, hold_ms: int = 0
+ ) -> None:
+ buttons = _physical_buttons(debug_btn)
assert isinstance(ui.CURRENT_LAYOUT, ui.Layout)
for btn in buttons:
@@ -245,7 +254,13 @@ async def dispatch_DebugLinkDecision(
await _layout_click(x, y, msg.hold_ms or 0)
# press specific button
elif msg.physical_button is not None:
- await _layout_press_button(msg.physical_button, msg.hold_ms or 0)
+ # `touch_event_type` allows holding a button while pressing another
+ if msg.touch_event_type == DebugTouchEventType.TOUCH_START:
+ _layout_button_event(msg.physical_button, io.BUTTON_PRESSED)
+ elif msg.touch_event_type == DebugTouchEventType.TOUCH_END:
+ _layout_button_event(msg.physical_button, io.BUTTON_RELEASED)
+ else:
+ await _layout_press_button(msg.physical_button, msg.hold_ms or 0)
elif msg.swipe is not None:
await _layout_swipe(msg.swipe)
elif msg.button is not None:
### core/src/trezor/ui/layouts/caesar/__init__.py
@@ -330,76 +330,66 @@ async def show_address(
br_code: ButtonRequestType = ButtonRequestType.Address,
chunkify: bool = False,
) -> None:
+ from trezor.ui.layouts.menu import Menu, MenuLeaf, cancel_leaf, confirm_with_menu
+
mismatch_title = mismatch_title or TR.addr_mismatch__mismatch # def_arg
- send_button_request = True
if title is None:
# Will be a marquee in case of multisig
title = TR.address__title_receive_address
if multisig_index is not None:
title = f"{title} (MULTISIG)" # TODO translation?
- while True:
- with trezorui_api.confirm_address(
- title=title,
- address=address,
- address_label=None,
- info_button=True,
- chunkify=chunkify,
+ def xpub_title(i: int) -> str:
+ # Will be marquee (cannot fit one line)
+ result = TR.address__title_multisig_xpub_template.format(i + 1)
+ result += (
+ TR.address__title_yours
+ if i == multisig_index
+ else TR.address__title_cosigner
+ )
+ return result
+
+ account_info: list[StrPropertyType] = []
+ if account:
+ account_info.append((with_colon(TR.words__account), account, False))
+ if path:
+ account_info.append(
+ (with_colon(TR.address_details__derivation_path), path, False)
+ )
+ account_info.extend((xpub_title(i), xpub, True) for i, xpub in enumerate(xpubs))
+
+ async def show_qr_code() -> None:
+ with trezorui_api.show_address_details(
+ qr_title="", # unused on this model
+ address=address if address_qr is None else address_qr,
+ case_sensitive=case_sensitive,
+ details_title="", # unused on this model
+ account=None, # shown in the account info
+ path=None, # shown in the account info
+ xpubs=(), # shown in the account info
) as layout:
- result = await interact(
- layout,
- br_name if send_button_request else None,
- br_code,
- raise_on_cancel=None,
- )
- send_button_request = False
-
- # User confirmed with middle button.
- if result is CONFIRMED:
- break
-
- # User pressed right button, go to address details.
- elif result is INFO:
-
- def xpub_title(i: int) -> str:
- # Will be marquee (cannot fit one line)
- result = TR.address__title_multisig_xpub_template.format(i + 1)
- result += (
- TR.address__title_yours
- if i == multisig_index
- else TR.address__title_cosigner
- )
- return result
-
- with trezorui_api.show_address_details(
- qr_title="", # unused on this model
- address=address if address_qr is None else address_qr,
- case_sensitive=case_sensitive,
- details_title="", # unused on this model
- account=(with_colon(TR.words__account), account) if account else None,
- path=(
- (with_colon(TR.address_details__derivation_path), path)
- if path
- else None
- ),
- xpubs=[(xpub_title(i), xpub) for i, xpub in enumerate(xpubs)],
- ) as layout:
- result = await interact(layout, None, raise_on_cancel=None)
- # Can only go back from the address details.
- assert result is CANCELLED
+ await interact(layout, None, raise_on_cancel=None)
- # User pressed left cancel button, show mismatch dialogue.
- else:
- with trezorui_api.show_mismatch(title=mismatch_title) as layout:
- result = await interact(
- layout,
- None,
- raise_on_cancel=None,
- )
- assert result in (CONFIRMED, CANCELLED)
- # Right button aborts action, left goes back to showing address.
- if result is CONFIRMED:
- raise ActionCancelled
+ menu_items: list[MenuLeaf[None]] = [MenuLeaf(TR.address__qr_code, show_qr_code)]
+ if account_info:
+ menu_items.append(
+ create_info_menu_leaf(TR.address_details__account_info, account_info)
+ )
+ menu_items.append(
+ cancel_leaf(
+ TR.buttons__cancel,
+ confirm=lambda: trezorui_api.show_mismatch(title=mismatch_title),
+ )
+ )
+
+ with trezorui_api.confirm_address(
+ title=title,
+ address=address,
+ address_label=None,
+ info_button=True,
+ chunkify=chunkify,
+ ) as layout:
+ await confirm_with_menu(layout, Menu(menu_items), br_name, br_code)
async def show_pubkey(
### python/src/trezorlib/debuglink.py
@@ -488,6 +488,14 @@ def action_bar(self) -> str:
def has_menu(self) -> bool:
return bool(self.find_unique_value_by_key("has_menu", False, bool))
+ def has_left_menu(self) -> bool:
+ """Whether the menu is opened by the left button (Caesar)."""
+ return bool(self.find_unique_value_by_key("left_menu", False, bool))
+
+ def danger_menu_items(self) -> list[bool]:
+ """Which menu items are dangerous, e.g. cancelling the flow (Caesar)."""
+ return self.find_unique_value_by_key("danger_items", [], list)
+
def has_flow_menu(self) -> bool:
return bool(self.find_unique_value_by_key("has_flow_menu", False, bool))
@@ -726,6 +734,36 @@ def hold_touch(self, pos: tuple[int, int]) -> t.Iterator[None]:
wait=False,
)
+ @contextmanager
+ def hold_button(self, button: messages.DebugPhysicalButton) -> t.Iterator[None]:
+ """Hold a physical button while the block is executed."""
+ self._decision(
+ messages.DebugLinkDecision(
+ physical_button=button,
+ touch_event_type=DebugTouchEventType.TOUCH_START,
+ ),
+ wait=False,
+ )
+ try:
+ yield
+ finally:
+ self._decision(
+ messages.DebugLinkDecision(
+ physical_button=button,
+ touch_event_type=DebugTouchEventType.TOUCH_END,
+ ),
+ wait=False,
+ )
+
+ def press_right_with_shift(self, count: int = 1) -> None:
+ """Press the right button `count` times while holding the left button as
+ "Shift" (Caesar), which triggers its secondary function, e.g. scrolling up."""
+ with self.hold_button(messages.DebugPhysicalButton.LEFT_BTN):
+ # wait for "Shift" to engage (200 ms in the firmware)
+ time.sleep(0.3)
+ for _ in range(count):
+ self.press_right()
+
def synchronize_at(
self, layout_text: str | list[str], timeout: float = 5
) -> LayoutContent:
@@ -1130,7 +1168,10 @@ def visit_menu_items(
if layout.has_menu():
is_menu = True
if self.debuglink.layout_type is LayoutType.Caesar:
- self.debuglink.press_right()
+ if layout.has_left_menu():
+ self.debuglink.press_left()
+ else:
+ self.debuglink.press_right()
else:
self.debuglink.click(self.debuglink.screen_buttons.menu())
@@ -1154,11 +1195,13 @@ def visit_menu_items(
raise UnexpectedMenuError(menu_layout.json_str)
elif self.debuglink.layout_type is LayoutType.Caesar:
assert gen is None, "Menu visiting callback not yet supported on Caesar"
- menu_items_count = self.debuglink.read_layout().page_count()
- for _ in range(menu_items_count):
- self.debuglink.press_middle()
- # paginate through all properties and confirm
- self._paginate_and_confirm(None)
+ menu_layout = self.debuglink.read_layout()
+ danger_items = menu_layout.danger_menu_items()
+ for i in range(menu_layout.page_count()):
+ if i >= len(danger_items) or not danger_items[i]:
+ self.debuglink.press_middle()
+ # paginate through all properties and confirm
+ self._paginate_and_confirm(None)
# paginate to next menu item
self.debuglink.press_right()
### tests/input_flows.py
@@ -541,25 +541,29 @@ def input_flow_bolt(self) -> BRGeneratorType:
self.debug.press_yes()
def input_flow_caesar(self) -> BRGeneratorType:
- # Find out the page-length of the address
- br = yield
- if br.pages is not None:
- address_swipes = br.pages - 1
- else:
- address_swipes = 0
- for _ in range(address_swipes):
- self.debug.press_right()
-
- # Go into details
- self.debug.press_right()
- # Go through details and back
+ yield
+ # menu
+ self.debug.press_left()
+ layout = self.debug.synchronize_at("SimpleChoice")
+ assert layout.page_count() == 3
+ # qr code
+ self.debug.press_middle()
+ self.debug.synchronize_at("Qr")
+ self.debug.press_left()
+ # account info
+ self.debug.synchronize_at("SimpleChoice")
self.debug.press_right()
+ self.debug.press_middle()
+ self.debug.synchronize_at("Paragraphs")
self.debug.press_left()
+ # close the menu
+ self.debug.synchronize_at("SimpleChoice")
self.debug.press_left()
- # Confirm
- for _ in range(address_swipes):
+ self.debug.press_left()
+ # scroll through the address and confirm
+ layout = self.debug.synchronize_at("ButtonPage")
+ for _ in range(layout.page_count()):
self.debug.press_right()
- self.debug.press_middle()
def input_flow_delizia(self) -> BRGeneratorType:
yield
@@ -630,15 +634,24 @@ def input_flow_bolt(self) -> BRGeneratorType:
def input_flow_caesar(self) -> BRGeneratorType:
yield
- # Go into details
- self.debug.press_right()
- # Go through details and back
- self.debug.press_right()
+ # menu
self.debug.press_left()
+ self.debug.synchronize_at("SimpleChoice")
+ # qr code
+ self.debug.press_middle()
+ self.debug.synchronize_at("Qr")
self.debug.press_left()
- # Cancel
+ # account info
+ self.debug.synchronize_at("SimpleChoice")
+ self.debug.press_right()
+ self.debug.press_middle()
+ self.debug.synchronize_at("Paragraphs")
self.debug.press_left()
- # Confirm address mismatch
+ # cancel
+ self.debug.synchronize_at("SimpleChoice")
+ self.debug.press_right()
+ self.debug.press_middle()
+ # address mismatch - quit
# Clicking right twice, as some languages can have two pages
self.debug.press_right()
self.debug.press_right()
@@ -720,27 +733,25 @@ def input_flow_caesar(self) -> BRGeneratorType:
yield # path warning
self.debug.press_yes()
- br = yield # show address
- # Find out the page-length of the address
- if br.pages is not None:
- address_swipes = br.pages - 1
- else:
- address_swipes = 0
- for _ in range(address_swipes):
- self.debug.press_right()
-
- # qr code
- self.debug.press_right()
- # address details
+ yield # show address
+ # menu
+ self.debug.press_left()
+ self.debug.synchronize_at("SimpleChoice")
+ # account info
self.debug.press_right()
+ self.debug.press_middle()
+ self.debug.synchronize_at("Paragraphs")
self._assert_account()
+ self.debug.press_left()
- # Go back and confirm
+ # close the menu
+ self.debug.synchronize_at("SimpleChoice")
self.debug.press_left()
self.debug.press_left()
- for _ in range(address_swipes):
+ # scroll through the address and confirm
+ layout = self.debug.synchronize_at("ButtonPage")
+ for _ in range(layout.page_count()):
self.debug.press_right()
- self.debug.press_middle()
def input_flow_delizia(self) -> BRGeneratorType:
yield # path warning
@@ -852,37 +863,55 @@ def input_flow_caesar(self) -> BRGeneratorType:
assert "(MULTISIG)" in layout.title()
assert layout.text_content().replace(" ", "") == self.address
- self.debug.press_right()
- assert "Qr" in self.all_components()
+ # menu
+ self.debug.press_left()
+ self.debug.synchronize_at("SimpleChoice")
+ # qr code
+ self.debug.press_middle()
+ self.debug.synchronize_at("Qr")
+ self.debug.press_left()
+ # account info
+ self.debug.synchronize_at("SimpleChoice")
self.debug.press_right()
- layout = self.debug.read_layout()
- # address details
- # TODO: locate it more precisely
- assert "Multisig 2 of 3" in layout.json_str
-
- # Three xpub pages with the same testing logic
+ self.debug.press_middle()
+ layout = self.debug.synchronize_at("Paragraphs")
+ assert "Multisig 2 of 3" in layout.text_content()
+ content = ""
+ for page in range(layout.page_count()):
+ if page > 0:
+ self.debug.press_right()
+ content += self.debug.read_layout().text_content()
+ content = "".join(content.split())
for xpub_num in range(3):
- self.debug.press_right()
- layout = self.debug.read_layout()
- self._assert_xpub_title(layout.title(), xpub_num)
- xpub_part_1 = layout.text_content().replace(" ", "")
- # Press "SHOW MORE"
- self.debug.press_middle()
- layout = self.debug.read_layout()
- xpub_part_2 = layout.text_content().replace(" ", "")
- # Go back
- self.debug.press_left()
- assert self.xpubs[xpub_num] == xpub_part_1 + xpub_part_2
-
- for _ in range(5):
- self.debug.press_left()
- # show address
+ xpub_title = TR.format(
+ "address__title_multisig_xpub_template", xpub_num + 1
+ ) + (
+ TR.address__title_yours
+ if self.index == xpub_num
+ else TR.address__title_cosigner
+ )
+ assert "".join(xpub_title.split()) in content
+ # Xpubs are split into lines and pages
+ assert self.xpubs[xpub_num][:20] in content
+ # hold left as "Shift" to scroll back up to the first page
+ self.debug.press_right_with_shift(layout.page_count() - 1)
+ assert self.debug.read_layout().active_page() == 0
self.debug.press_left()
- # address mismatch
+
+ # cancel
+ self.debug.synchronize_at("SimpleChoice")
+ self.debug.press_right()
+ self.debug.press_middle()
+ # address mismatch - go back to the menu
self.debug.press_left()
+ # close the menu
+ self.debug.synchronize_at("SimpleChoice")
+ for _ in range(3):
+ self.debug.press_left()
# show address
- self.debug.press_middle()
+ self.debug.synchronize_at("ButtonPage")
+ self.debug.press_right()
def input_flow_delizia(self) -> BRGeneratorType:
yield # multisig address warningWhy this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.