matrixr 1.1.0

Animated Matrix-style terminal screensaver
Documentation
//! Layout for the scrollable keyboard-shortcuts popup.

const HORIZONTAL_MARGIN: u16 = 2;
const HORIZONTAL_PADDING: u16 = 2;
const VERTICAL_MARGIN: u16 = 1;
const FIXED_ROWS: u16 = 4; // top padding, title, title gap, bottom padding
const TITLE: &str = "Shortcuts";

const KEY_BINDINGS: &[(&str, &str)] = &[
    ("~", "show / hide shortcuts popup"),
    ("0-9", "set speed (0: unlimited)"),
    ("d / f", "decrease / increase FPS (1-120)"),
    ("D", "toggle deep mode"),
    ("a", "toggle asynchronous updates"),
    ("b / B / n", "random / all / no bold"),
    ("c", "toggle Japanese charset (unlocked)"),
    ("m", "toggle lambda mode"),
    ("k", "toggle dynamic characters"),
    ("o", "toggle old-style scrolling"),
    ("r", "toggle rainbow mode"),
    ("x", "toggle X-window mode"),
    ("p / P", "pause / resume animation"),
    ("L", "lock / unlock application"),
    ("! @ # $", "red / green / yellow / blue"),
    ("% ^ & )", "magenta / cyan / white / black"),
    ("q / ctrl+c", "quit (when unlocked)"),
    ("↑ ↓ / PgUp PgDn", "scroll popup"),
    ("Home / End", "jump to first / last line"),
    ("Esc", "close popup"),
];

pub(crate) struct Popup {
    pub(crate) left: u16,
    pub(crate) top: u16,
    pub(crate) lines: Vec<String>,
}

pub(crate) fn popup_page_size(rows: u16) -> usize {
    usize::from(rows.saturating_sub(FIXED_ROWS + VERTICAL_MARGIN * 2).max(1))
}

pub(crate) fn popup_max_scroll(rows: u16) -> usize {
    KEY_BINDINGS.len().saturating_sub(popup_page_size(rows))
}

pub(crate) fn render_popup(columns: u16, rows: u16, requested_scroll: usize) -> Option<Popup> {
    let minimum_columns = (HORIZONTAL_MARGIN + HORIZONTAL_PADDING) * 2 + 1;
    if columns < minimum_columns || rows < FIXED_ROWS + 1 {
        return None;
    }

    let key_width = KEY_BINDINGS
        .iter()
        .map(|(keys, _)| keys.chars().count())
        .max()
        .unwrap_or(0);
    let max_content_width = usize::from(columns - minimum_columns + 1);
    let content_width = KEY_BINDINGS
        .iter()
        .map(|(_, action)| key_width + 2 + action.chars().count())
        .chain(std::iter::once(TITLE.chars().count()))
        .max()
        .unwrap_or(0)
        .min(max_content_width);
    let width = content_width + usize::from(HORIZONTAL_PADDING * 2);
    let blank = " ".repeat(width);
    let page_size = popup_page_size(rows);
    let scroll = requested_scroll.min(popup_max_scroll(rows));

    let mut lines = Vec::with_capacity(page_size.min(KEY_BINDINGS.len()) + 4);
    lines.push(blank.clone());
    lines.push(fit_line(TITLE, content_width, true));
    lines.push(blank.clone());
    lines.extend(
        KEY_BINDINGS
            .iter()
            .skip(scroll)
            .take(page_size)
            .map(|(keys, action)| {
                fit_line(
                    &format!("{keys:<key_width$}  {action}"),
                    content_width,
                    false,
                )
            }),
    );
    lines.push(blank);

    let width = u16::try_from(width).unwrap_or(columns);
    let height = u16::try_from(lines.len()).unwrap_or(rows);
    Some(Popup {
        left: columns.saturating_sub(width) / 2,
        top: rows.saturating_sub(height) / 2,
        lines,
    })
}

fn fit_line(text: &str, width: usize, centered: bool) -> String {
    let text = text.chars().take(width).collect::<String>();
    let remaining = width.saturating_sub(text.chars().count());
    let left = if centered { remaining / 2 } else { 0 };
    let padding = usize::from(HORIZONTAL_PADDING);
    format!(
        "{}{}{}",
        " ".repeat(padding + left),
        text,
        " ".repeat(padding + remaining - left),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn popup_is_centered_and_clamps_scroll() {
        let first = render_popup(56, 7, 0).unwrap();
        let last = render_popup(56, 7, usize::MAX).unwrap();
        let width = u16::try_from(first.lines[0].chars().count()).unwrap();

        assert_eq!(first.left, (56 - width) / 2);
        assert!(first.lines[3].contains(KEY_BINDINGS[0].0));
        assert!(last.lines[3].contains(KEY_BINDINGS[KEY_BINDINGS.len() - 1].0));
    }
}