//! Layout and painting for the original pointer tooltips. use crate::{game_font::BitmapFont, ui_sprite::source_over, RgbaImage}; use std::time::{Duration, Instant}; #[derive(Default)] pub struct TooltipHover { anchor: Option<([i32; 2], Instant)>, } impl TooltipHover { /// iron3d+0x9bbc0 only samples pointer position on frames that publish a hint. pub fn visible(&mut self, pointer: [i32; 2], now: Instant) -> bool { if let Some((anchor, since)) = self.anchor { if anchor[0].abs_diff(pointer[0]) < 3 && anchor[1].abs_diff(pointer[1]) < 3 { return now.duration_since(since) > Duration::from_millis(250); } } self.anchor = Some((pointer, now)); false } } /// iron3d+0x9b910 flips the box to the left or above if it would cross an edge. pub fn origin( [x, y]: [i32; 2], [width, height]: [i32; 2], [right, bottom]: [i32; 2], cursor_offset: i32, ) -> [i32; 2] { [ if x + width < right { x } else { x - width - 1 }, if y + cursor_offset + height < bottom { y + cursor_offset } else { y - height - 1 }, ] } /// Paints the frame and text at the font's original pixel size. pub fn paint(font: &BitmapFont, text: &str) -> Result { let [width, height] = font.line_metrics(text)?; let glyphs = font.centered_line(text, width, height)?; let [width, height] = [usize::from(width) + 8, usize::from(height) + 8]; let mut pixels = vec![0; width * height * 4]; for (y, row) in pixels.chunks_exact_mut(width * 4).enumerate() { for (x, pixel) in row.chunks_exact_mut(4).enumerate() { let border = x == 0 || y == 0 || x == width - 1 || y == height - 1; pixel.copy_from_slice(if border { &[0, 0, 0, 255] } else { &[245, 245, 150, 255] }); } } let text_stride = glyphs.width as usize * 4; for (y, row) in glyphs.rgba8.chunks_exact(text_stride).enumerate() { let start = ((y + 4) * width + 5) * 4; for (dest, glyph) in pixels[start..start + text_stride] .chunks_exact_mut(4) .zip(row.chunks_exact(4)) { source_over(dest, &[0, 0, 0, glyph[3]]); } } Ok(RgbaImage { width: width as u32, height: height as u32, rgba8: pixels, }) } #[cfg(test)] mod tests { use super::*; #[test] fn waits_for_strictly_more_than_250_ms_within_two_pixels_of_the_anchor() { let start = Instant::now(); let at = |ms| start + Duration::from_millis(ms); let mut hover = TooltipHover::default(); assert!(!hover.visible([90, 123], at(0))); assert!(!hover.visible([92, 121], at(250))); assert!(hover.visible([92, 121], at(251))); assert!(!hover.visible([90, 126], at(252))); assert!(hover.visible([90, 126], at(503))); } #[test] fn flips_at_the_viewport_edges() { assert_eq!(origin([425, 122], [78, 17], [800, 600], 20), [425, 142]); assert_eq!(origin([722, 563], [78, 17], [800, 600], 20), [643, 545]); } }