format apps/repl

This commit is contained in:
bunnie 2024-01-14 18:56:07 +08:00
parent fb463786fe
commit d3eb53ba89
3 changed files with 143 additions and 123 deletions

View file

@ -1,15 +1,23 @@
use xous::{MessageEnvelope};
use xous_ipc::String;
use core::fmt::Write; use core::fmt::Write;
use std::collections::HashMap; use std::collections::HashMap;
use xous::MessageEnvelope;
use xous_ipc::String;
/////////////////////////// Common items to all commands /////////////////////////// Common items to all commands
pub trait ShellCmdApi<'a> { pub trait ShellCmdApi<'a> {
// user implemented: // user implemented:
// called to process the command with the remainder of the string attached // called to process the command with the remainder of the string attached
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error>; fn process(
&mut self,
args: String<1024>,
env: &mut CommonEnv,
) -> Result<Option<String<1024>>, xous::Error>;
// called to process incoming messages that may have been origniated by the most recently issued command // called to process incoming messages that may have been origniated by the most recently issued command
fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> { fn callback(
&mut self,
msg: &MessageEnvelope,
_env: &mut CommonEnv,
) -> Result<Option<String<1024>>, xous::Error> {
log::info!("received unhandled message {:?}", msg); log::info!("received unhandled message {:?}", msg);
Ok(None) Ok(None)
} }
@ -23,16 +31,8 @@ pub trait ShellCmdApi<'a> {
// the argument to this macro is the command verb // the argument to this macro is the command verb
macro_rules! cmd_api { macro_rules! cmd_api {
($verb:expr) => { ($verb:expr) => {
fn verb(&self) -> &'static str { fn verb(&self) -> &'static str { stringify!($verb) }
stringify!($verb) fn matches(&self, verb: &str) -> bool { if verb == stringify!($verb) { true } else { false } }
}
fn matches(&self, verb: &str) -> bool {
if verb == stringify!($verb) {
true
} else {
false
}
}
}; };
} }
@ -46,12 +46,12 @@ pub struct CommonEnv {
codec: codec::Codec, codec: codec::Codec,
ticktimer: ticktimer_server::Ticktimer, ticktimer: ticktimer_server::Ticktimer,
gam: gam::Gam, gam: gam::Gam,
cb_registrations: HashMap::<u32, String::<256>>, cb_registrations: HashMap<u32, String<256>>,
trng: Trng, trng: Trng,
xns: xous_names::XousNames, xns: xous_names::XousNames,
} }
impl CommonEnv { impl CommonEnv {
pub fn register_handler(&mut self, verb: String::<256>) -> u32 { pub fn register_handler(&mut self, verb: String<256>) -> u32 {
let mut key: u32; let mut key: u32;
loop { loop {
key = self.trng.get_u32().unwrap(); key = self.trng.get_u32().unwrap();
@ -78,11 +78,12 @@ impl CommonEnv {
*/ */
///// 1. add your module here, and pull its namespace into the local crate ///// 1. add your module here, and pull its namespace into the local crate
mod audio; use audio::*; mod audio;
use audio::*;
pub struct CmdEnv { pub struct CmdEnv {
common_env: CommonEnv, common_env: CommonEnv,
lastverb: String::<256>, lastverb: String<256>,
///// 2. declare storage for your command here. ///// 2. declare storage for your command here.
audio_cmd: Audio, audio_cmd: Audio,
} }
@ -109,10 +110,14 @@ impl CmdEnv {
} }
} }
pub fn dispatch(&mut self, maybe_cmdline: Option<&mut String::<1024>>, maybe_callback: Option<&MessageEnvelope>) -> Result<Option<String::<1024>>, xous::Error> { pub fn dispatch(
&mut self,
maybe_cmdline: Option<&mut String<1024>>,
maybe_callback: Option<&MessageEnvelope>,
) -> Result<Option<String<1024>>, xous::Error> {
let mut ret = String::<1024>::new(); let mut ret = String::<1024>::new();
let commands: &mut [& mut dyn ShellCmdApi] = &mut [ let commands: &mut [&mut dyn ShellCmdApi] = &mut [
///// 4. add your command to this array, so that it can be looked up and dispatched ///// 4. add your command to this array, so that it can be looked up and dispatched
&mut self.audio_cmd, &mut self.audio_cmd,
]; ];
@ -120,7 +125,7 @@ impl CmdEnv {
if let Some(cmdline) = maybe_cmdline { if let Some(cmdline) = maybe_cmdline {
let maybe_verb = tokenize(cmdline); let maybe_verb = tokenize(cmdline);
let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None); let mut cmd_ret: Result<Option<String<1024>>, xous::Error> = Ok(None);
if let Some(verb_string) = maybe_verb { if let Some(verb_string) = maybe_verb {
let verb = verb_string.to_str(); let verb = verb_string.to_str();
@ -155,15 +160,11 @@ impl CmdEnv {
Ok(None) Ok(None)
} }
} else if let Some(callback) = maybe_callback { } else if let Some(callback) = maybe_callback {
let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None); let mut cmd_ret: Result<Option<String<1024>>, xous::Error> = Ok(None);
// first check and see if we have a callback registration; if not, just map to the last verb // first check and see if we have a callback registration; if not, just map to the last verb
let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) { let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) {
Some(verb) => { Some(verb) => verb.to_str(),
verb.to_str() None => self.lastverb.to_str(),
},
None => {
self.lastverb.to_str()
}
}; };
// now dispatch // now dispatch
let mut verbfound = false; let mut verbfound = false;
@ -174,11 +175,7 @@ impl CmdEnv {
break; break;
}; };
} }
if verbfound { if verbfound { cmd_ret } else { Ok(None) }
cmd_ret
} else {
Ok(None)
}
} else { } else {
Ok(None) Ok(None)
} }
@ -188,7 +185,7 @@ impl CmdEnv {
/// extract the first token, as delimited by spaces /// extract the first token, as delimited by spaces
/// modifies the incoming line by removing the token and returning the remainder /// modifies the incoming line by removing the token and returning the remainder
/// returns the found token /// returns the found token
pub fn tokenize(line: &mut String::<1024>) -> Option<String::<1024>> { pub fn tokenize(line: &mut String<1024>) -> Option<String<1024>> {
let mut token = String::<1024>::new(); let mut token = String::<1024>::new();
let mut retline = String::<1024>::new(); let mut retline = String::<1024>::new();
@ -211,9 +208,5 @@ pub fn tokenize(line: &mut String::<1024>) -> Option<String::<1024>> {
} }
line.clear(); line.clear();
write!(line, "{}", retline.as_str().unwrap()).unwrap(); write!(line, "{}", retline.as_str().unwrap()).unwrap();
if token.len() > 0 { if token.len() > 0 { Some(token) } else { None }
Some(token)
} else {
None
}
} }

View file

@ -1,9 +1,11 @@
use crate::{ShellCmdApi,CommonEnv};
use xous_ipc::String;
use xous::{MessageEnvelope, Message};
use codec::*;
use core::fmt::Write; use core::fmt::Write;
use codec::*;
use locales::t; use locales::t;
use xous::{Message, MessageEnvelope};
use xous_ipc::String;
use crate::{CommonEnv, ShellCmdApi};
#[derive(Debug)] #[derive(Debug)]
pub struct Audio { pub struct Audio {
@ -16,13 +18,7 @@ pub struct Audio {
impl Audio { impl Audio {
pub fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_REPL).unwrap(); let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_REPL).unwrap();
Audio { Audio { callback_id: None, callback_conn, framecount: 0, play_sample: 0.0, freq: 440.0 }
callback_id: None,
callback_conn,
framecount: 0,
play_sample: 0.0,
freq: 440.0,
}
} }
} }
@ -51,7 +47,7 @@ fn simple_kilofloat_parse(input: &str) -> core::result::Result<i32, ParseIntErro
} }
significance /= 10; significance /= 10;
} else { } else {
return "z".parse::<i32>() // you can't create a ParseIntError any other way return "z".parse::<i32>(); // you can't create a ParseIntError any other way
} }
} }
Ok(result) Ok(result)
@ -64,7 +60,11 @@ fn simple_kilofloat_parse(input: &str) -> core::result::Result<i32, ParseIntErro
impl<'a> ShellCmdApi<'a> for Audio { impl<'a> ShellCmdApi<'a> for Audio {
cmd_api!(audio); cmd_api!(audio);
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> { fn process(
&mut self,
args: String<1024>,
env: &mut CommonEnv,
) -> Result<Option<String<1024>>, xous::Error> {
let mut ret = String::<1024>::new(); let mut ret = String::<1024>::new();
let helpstring = t!("replapp.audio.help", locales::LANG); let helpstring = t!("replapp.audio.help", locales::LANG);
let mut tokens = args.as_str().unwrap().split(' '); let mut tokens = args.as_str().unwrap().split(' ');
@ -114,7 +114,8 @@ impl<'a> ShellCmdApi<'a> for Audio {
move || { move || {
let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
ticktimer.sleep_ms((duration * 1000.0) as usize).unwrap(); ticktimer.sleep_ms((duration * 1000.0) as usize).unwrap();
xous::send_message(conn, Message::new_scalar(cb_id as usize, 0, 0, 0, STOP_ID)).unwrap(); xous::send_message(conn, Message::new_scalar(cb_id as usize, 0, 0, 0, STOP_ID))
.unwrap();
} }
}); });
write!(ret, "{}", t!("replapp.audio.start", locales::LANG)).unwrap(); write!(ret, "{}", t!("replapp.audio.start", locales::LANG)).unwrap();
@ -123,16 +124,25 @@ impl<'a> ShellCmdApi<'a> for Audio {
write!(ret, "{}", helpstring).unwrap(); write!(ret, "{}", helpstring).unwrap();
} }
} }
} }
Ok(Some(ret)) Ok(Some(ret))
} }
fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> { fn callback(
&mut self,
msg: &MessageEnvelope,
env: &mut CommonEnv,
) -> Result<Option<String<1024>>, xous::Error> {
const AMPLITUDE: f32 = 0.8; const AMPLITUDE: f32 = 0.8;
match &msg.body { match &msg.body {
Message::Scalar(xous::ScalarMessage{id: _, arg1: free_play, arg2: _avail_rec, arg3: _, arg4: routing_id}) => { Message::Scalar(xous::ScalarMessage {
id: _,
arg1: free_play,
arg2: _avail_rec,
arg3: _,
arg4: routing_id,
}) => {
if *routing_id == codec::AUDIO_CB_ROUTING_ID { if *routing_id == codec::AUDIO_CB_ROUTING_ID {
let mut frames: FrameRing = FrameRing::new(); let mut frames: FrameRing = FrameRing::new();
let frames_to_push = if frames.writeable_count() < *free_play { let frames_to_push = if frames.writeable_count() < *free_play {
@ -144,11 +154,14 @@ impl<'a> ShellCmdApi<'a> for Audio {
log::debug!("f{} p{}", self.framecount, frames_to_push); log::debug!("f{} p{}", self.framecount, frames_to_push);
for _ in 0..frames_to_push { for _ in 0..frames_to_push {
let mut frame: [u32; codec::FIFO_DEPTH] = [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; codec::FIFO_DEPTH]; let mut frame: [u32; codec::FIFO_DEPTH] =
[ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; codec::FIFO_DEPTH];
// put the "expensive" f32 comparison outside the cosine wave table computation loop // put the "expensive" f32 comparison outside the cosine wave table computation loop
let omega = self.freq * 2.0 * std::f32::consts::PI / SAMPLE_RATE_HZ; let omega = self.freq * 2.0 * std::f32::consts::PI / SAMPLE_RATE_HZ;
for sample in frame.iter_mut() { for sample in frame.iter_mut() {
let raw_sine: i16 = (AMPLITUDE * cos_table::cos( self.play_sample * omega ) * i16::MAX as f32) as i16; let raw_sine: i16 = (AMPLITUDE
* cos_table::cos(self.play_sample * omega)
* i16::MAX as f32) as i16;
let left = raw_sine as u16; let left = raw_sine as u16;
let right = raw_sine as u16; let right = raw_sine as u16;
*sample = right as u32 | (left as u32) << 16; *sample = right as u32 | (left as u32) << 16;
@ -156,26 +169,28 @@ impl<'a> ShellCmdApi<'a> for Audio {
} }
frames.nq_frame(frame).unwrap(); frames.nq_frame(frame).unwrap();
} }
env.codec.swap_frames(&mut frames).unwrap(); env.codec.swap_frames(&mut frames).unwrap();
} else if *routing_id == STOP_ID { } else if *routing_id == STOP_ID {
let mut ret = String::<1024>::new(); let mut ret = String::<1024>::new();
env.codec.abort().unwrap(); // this should stop callbacks from occurring too. env.codec.abort().unwrap(); // this should stop callbacks from occurring too.
write!(ret, "{} {} {}.", write!(
ret,
"{} {} {}.",
t!("replapp.audio.completion_a", locales::LANG), t!("replapp.audio.completion_a", locales::LANG),
self.framecount, self.framecount,
t!("replapp.audio.completion_b", locales::LANG), t!("replapp.audio.completion_b", locales::LANG),
).unwrap(); )
.unwrap();
self.framecount = 0; self.framecount = 0;
self.play_sample = 0.0; self.play_sample = 0.0;
env.codec.power_off().unwrap(); env.codec.power_off().unwrap();
return Ok(Some(ret)); return Ok(Some(ret));
} }
}, }
Message::Move(_mm) => { Message::Move(_mm) => {
log::error!("received memory message when not expected") log::error!("received memory message when not expected")
}, }
_ => { _ => {
log::error!("received unknown callback type") log::error!("received unknown callback type")
} }

View file

@ -1,10 +1,12 @@
use super::*;
use gam::UxRegistration;
use graphics_server::{Gid, Point, Rectangle, TextBounds, TextView, DrawStyle, PixelColor};
use graphics_server::api::GlyphStyle;
use xous::MessageEnvelope;
use core::fmt::Write; use core::fmt::Write;
use gam::UxRegistration;
use graphics_server::api::GlyphStyle;
use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView};
use locales::t; use locales::t;
use xous::MessageEnvelope;
use super::*;
#[derive(Debug)] #[derive(Debug)]
struct History { struct History {
@ -23,7 +25,7 @@ pub(crate) struct Repl {
msg: Option<MessageEnvelope>, msg: Option<MessageEnvelope>,
// record our input history // record our input history
history: Vec::<History>, history: Vec<History>,
history_len: usize, history_len: usize,
content: Gid, content: Gid,
gam: gam::Gam, gam: gam::Gam,
@ -31,7 +33,7 @@ pub(crate) struct Repl {
// variables that define our graphical attributes // variables that define our graphical attributes
screensize: Point, screensize: Point,
bubble_width: u16, bubble_width: u16,
margin: Point, // margin to edge of canvas margin: Point, // margin to edge of canvas
bubble_margin: Point, // margin of text in bubbles bubble_margin: Point, // margin of text in bubbles
bubble_radius: u16, bubble_radius: u16,
bubble_space: i16, // spacing between text bubbles bubble_space: i16, // spacing between text bubbles
@ -42,28 +44,36 @@ pub(crate) struct Repl {
// our security token for making changes to our record on the GAM // our security token for making changes to our record on the GAM
token: [u32; 4], token: [u32; 4],
} }
impl Repl{ impl Repl {
pub(crate) fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self { pub(crate) fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self {
let gam = gam::Gam::new(xns).expect("can't connect to GAM"); let gam = gam::Gam::new(xns).expect("can't connect to GAM");
let token = gam.register_ux(UxRegistration { let token = gam
app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_REPL), .register_ux(UxRegistration {
ux_type: gam::UxType::Chat, app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_REPL),
predictor: Some(xous_ipc::String::<64>::from_str(ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL)), ux_type: gam::UxType::Chat,
listener: sid.to_array(), // note disclosure of our SID to the GAM -- the secret is now shared with the GAM! predictor: Some(xous_ipc::String::<64>::from_str(
redraw_id: ReplOp::Redraw.to_u32().unwrap(), ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL,
gotinput_id: Some(ReplOp::Line.to_u32().unwrap()), )),
audioframe_id: None, listener: sid.to_array(), /* note disclosure of our SID to the GAM -- the secret is now
rawkeys_id: None, * shared with the GAM! */
focuschange_id: Some(ReplOp::ChangeFocus.to_u32().unwrap()), redraw_id: ReplOp::Redraw.to_u32().unwrap(),
}).expect("couldn't register Ux context for repl"); gotinput_id: Some(ReplOp::Line.to_u32().unwrap()),
audioframe_id: None,
rawkeys_id: None,
focuschange_id: Some(ReplOp::ChangeFocus.to_u32().unwrap()),
})
.expect("couldn't register Ux context for repl");
let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas"); let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas");
let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas"); let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas");
Repl { Repl {
input: None, input: None,
msg: None, msg: None,
history: vec![History{text: String::from(t!("replapp.greeting", locales::LANG)), is_input: false}], history: vec![History {
text: String::from(t!("replapp.greeting", locales::LANG)),
is_input: false,
}],
history_len: 10, history_len: 10,
content, content,
gam, gam,
@ -85,9 +95,7 @@ impl Repl{
Ok(()) Ok(())
} }
pub(crate) fn msg(&mut self, message: MessageEnvelope) { pub(crate) fn msg(&mut self, message: MessageEnvelope) { self.msg = Some(message); }
self.msg = Some(message);
}
fn circular_push(&mut self, item: History) { fn circular_push(&mut self, item: History) {
if self.history.len() >= self.history_len { if self.history.len() >= self.history_len {
@ -100,10 +108,7 @@ impl Repl{
pub(crate) fn update(&mut self, was_callback: bool) -> Result<(), xous::Error> { pub(crate) fn update(&mut self, was_callback: bool) -> Result<(), xous::Error> {
// if we had an input string, do something // if we had an input string, do something
if let Some(local) = &self.input { if let Some(local) = &self.input {
let input_history = History { let input_history = History { text: local.to_string(), is_input: true };
text: local.to_string(),
is_input: true,
};
self.circular_push(input_history); self.circular_push(input_history);
} }
@ -112,28 +117,29 @@ impl Repl{
// side effect our commands // side effect our commands
// redraw UI once upon accepting all input // redraw UI once upon accepting all input
if !was_callback { // don't need to redraw on a callback, save some cycles if !was_callback {
// don't need to redraw on a callback, save some cycles
self.redraw().expect("can't redraw"); self.redraw().expect("can't redraw");
} }
let mut dirty = true; let mut dirty = true;
// take the input and pass it on to the various command parsers, and attach result // take the input and pass it on to the various command parsers, and attach result
if let Some(local) = &self.input { if let Some(local) = &self.input {
if let Some(res) = self.env.dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None).expect("command dispatch failed") { if let Some(res) = self
let output_history = History { .env
text: String::from(res.as_str().unwrap_or("UTF-8 Error")), .dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None)
is_input: false .expect("command dispatch failed")
}; {
let output_history =
History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false };
self.circular_push(output_history); self.circular_push(output_history);
} else { } else {
dirty = false; dirty = false;
} }
} else if let Some(msg) = &self.msg { } else if let Some(msg) = &self.msg {
if let Some(res) = self.env.dispatch(None, Some(msg)).expect("callback failed") { if let Some(res) = self.env.dispatch(None, Some(msg)).expect("callback failed") {
let output_history = History { let output_history =
text: String::from(res.as_str().unwrap_or("UTF-8 Error")), History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false };
is_input: false
};
self.circular_push(output_history); self.circular_push(output_history);
} else { } else {
dirty = false; dirty = false;
@ -152,15 +158,18 @@ impl Repl{
} }
fn clear_area(&self) { fn clear_area(&self) {
self.gam.draw_rectangle(self.content, self.gam
Rectangle::new_with_style(Point::new(0, 0), self.screensize, .draw_rectangle(
DrawStyle { self.content,
fill_color: Some(PixelColor::Light), Rectangle::new_with_style(
stroke_color: None, Point::new(0, 0),
stroke_width: 0 self.screensize,
} DrawStyle { fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0 },
)).expect("can't clear content area"); ),
)
.expect("can't clear content area");
} }
pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> { pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> {
self.clear_area(); self.clear_area();
@ -170,18 +179,20 @@ impl Repl{
// iterator returns from oldest to newest // iterator returns from oldest to newest
// .rev() iterator is from newest to oldest // .rev() iterator is from newest to oldest
for h in self.history.iter().rev() { for h in self.history.iter().rev() {
let mut bubble_tv = let mut bubble_tv = if h.is_input {
if h.is_input { TextView::new(
TextView::new(self.content, self.content,
TextBounds::GrowableFromBr( TextBounds::GrowableFromBr(
Point::new(self.screensize.x - self.margin.x, bubble_baseline), Point::new(self.screensize.x - self.margin.x, bubble_baseline),
self.bubble_width)) self.bubble_width,
} else { ),
TextView::new(self.content, )
TextBounds::GrowableFromBl( } else {
Point::new(self.margin.x, bubble_baseline), TextView::new(
self.bubble_width)) self.content,
}; TextBounds::GrowableFromBl(Point::new(self.margin.x, bubble_baseline), self.bubble_width),
)
};
if h.is_input { if h.is_input {
bubble_tv.border_width = 1; bubble_tv.border_width = 1;
} else { } else {
@ -192,13 +203,14 @@ impl Repl{
bubble_tv.rounded_border = Some(self.bubble_radius); bubble_tv.rounded_border = Some(self.bubble_radius);
bubble_tv.style = GlyphStyle::Regular; bubble_tv.style = GlyphStyle::Regular;
bubble_tv.margin = self.bubble_margin; bubble_tv.margin = self.bubble_margin;
bubble_tv.ellipsis = false; bubble_tv.insertion = None; bubble_tv.ellipsis = false;
bubble_tv.insertion = None;
write!(bubble_tv.text, "{}", h.text.as_str()).expect("couldn't write history text to TextView"); write!(bubble_tv.text, "{}", h.text.as_str()).expect("couldn't write history text to TextView");
self.gam.post_textview(&mut bubble_tv).expect("couldn't render bubble textview"); self.gam.post_textview(&mut bubble_tv).expect("couldn't render bubble textview");
if let Some(bounds) = bubble_tv.bounds_computed { if let Some(bounds) = bubble_tv.bounds_computed {
// we only subtract 1x of the margin because the bounds were computed from a "bottom right" that already counted // we only subtract 1x of the margin because the bounds were computed from a "bottom right"
// the margin once. // that already counted the margin once.
bubble_baseline -= (bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y; bubble_baseline -= (bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y;
if bubble_baseline <= 0 { if bubble_baseline <= 0 {
// don't draw history that overflows the top of the screen // don't draw history that overflows the top of the screen