use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::clock::font::{self, Bitmap};
use crate::common::TerminalEffect;
use crate::render::braille::{BrailleGrid, DOTS_Y};
use chrono::{DateTime, Local, Timelike};
use crossterm::style::{Attribute, Color};
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const GAP: usize = 1;
const RULE_GAP_ROWS: usize = 1;
const RULE_ROWS: usize = 1;
const RULE_DOTS: usize = 2;
type Source = fn() -> SystemTime;
fn system_clock() -> SystemTime {
SystemTime::now()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ClockOptions {
pub show_seconds: bool,
pub color: Color,
pub accent: Color,
}
impl Default for ClockOptions {
fn default() -> Self {
Self {
show_seconds: true,
color: Color::White,
accent: Color::Cyan,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClockTime {
pub hour: u32,
pub minute: u32,
pub second: u32,
pub fraction: f64,
}
fn read_time(now: SystemTime) -> ClockTime {
let since_epoch = now.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
let stamp = DateTime::from_timestamp(
since_epoch.as_secs() as i64,
since_epoch.subsec_nanos(),
)
.unwrap_or_default()
.with_timezone(&Local);
ClockTime {
hour: stamp.hour(),
minute: stamp.minute(),
second: stamp.second(),
fraction: stamp.nanosecond() as f64 / 1_000_000_000.0,
}
}
fn time_text(reading: &ClockTime, show_seconds: bool) -> String {
if show_seconds {
format!(
"{:02}:{:02}:{:02}",
reading.hour, reading.minute, reading.second
)
} else {
format!("{:02}:{:02}", reading.hour, reading.minute)
}
}
fn rule_fraction(reading: &ClockTime, show_seconds: bool) -> f64 {
if show_seconds {
reading.fraction
} else {
(reading.minute as f64 + reading.fraction) / 60.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layout {
glyphs: Vec<(usize, Bitmap)>,
cells_wide: usize,
}
impl Layout {
pub fn new(text: &str) -> Self {
let glyphs: Vec<(usize, Bitmap)> = text
.chars()
.filter_map(|c| {
font::bitmap(c)
.map(|bitmap| (bitmap.width / font::CELL_DOTS, bitmap))
})
.collect();
let ink: usize = glyphs.iter().map(|(cells, _)| cells).sum();
let cells_wide = ink + GAP * glyphs.len().saturating_sub(1);
Self { glyphs, cells_wide }
}
pub fn cells_wide(&self) -> usize {
self.cells_wide
}
}
pub fn digit_rows(scale: usize) -> usize {
(font::GLYPH_H * font::CELL_DOTS * scale).div_ceil(DOTS_Y)
}
pub fn total_rows(scale: usize) -> usize {
digit_rows(scale) + RULE_GAP_ROWS + RULE_ROWS
}
const SCALE_STEP: usize = 2;
const MIN_ALIGNED_SCALE: usize = 2;
pub fn scale_for(cells_wide: usize, size: (u16, u16)) -> usize {
let (width, height) = (size.0 as usize, size.1 as usize);
let mut best = 1;
let mut scale = MIN_ALIGNED_SCALE;
while cells_wide * scale <= width && total_rows(scale) <= height {
best = scale;
scale += SCALE_STEP;
}
best
}
pub struct Clock {
screen_size: (u16, u16),
options: ClockOptions,
canvas: Canvas,
digits: BrailleGrid,
accent: BrailleGrid,
laid_out_text: String,
laid_out_scale: usize,
now: Source,
}
impl TerminalEffect for Clock {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.draw()
}
fn update(&mut self) {}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width.max(1), height.max(1));
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.reset();
}
fn reset(&mut self) {
self.canvas.clear();
}
}
impl Clock {
pub fn new(options: ClockOptions, screen_size: (u16, u16)) -> Self {
Self::with_clock(options, screen_size, system_clock)
}
pub fn with_clock(
options: ClockOptions,
screen_size: (u16, u16),
now: Source,
) -> Self {
let screen_size = (screen_size.0.max(1), screen_size.1.max(1));
Self {
screen_size,
options,
canvas: Canvas::new(screen_size.0, screen_size.1),
digits: BrailleGrid::new(1, 1),
accent: BrailleGrid::new(1, 1),
laid_out_text: String::new(),
laid_out_scale: 0,
now,
}
}
fn draw(&mut self) -> Vec<(usize, usize, Cell)> {
let reading = read_time((self.now)());
let text = time_text(&reading, self.options.show_seconds);
let layout = Layout::new(&text);
let scale = scale_for(layout.cells_wide(), self.screen_size);
let cells = (layout.cells_wide() * scale, total_rows(scale));
self.digits.resize(cells.0, cells.1);
self.accent.resize(cells.0, cells.1);
if text != self.laid_out_text || scale != self.laid_out_scale {
self.digits.clear();
paint_digits(&mut self.digits, &layout, scale);
self.laid_out_text.clone_from(&text);
self.laid_out_scale = scale;
}
self.accent.clear();
let fraction = rule_fraction(&reading, self.options.show_seconds);
paint_rule(&mut self.accent, &layout, scale, fraction);
self.canvas.clear();
let at = self.origin(layout.cells_wide(), scale);
stamp(&self.digits, &mut self.canvas, at, self.options.color);
stamp(&self.accent, &mut self.canvas, at, self.options.accent);
self.canvas.commit()
}
fn origin(&self, cells_wide: usize, scale: usize) -> (usize, usize) {
let width = cells_wide * scale;
let height = total_rows(scale);
(
(self.screen_size.0 as usize).saturating_sub(width) / 2,
(self.screen_size.1 as usize).saturating_sub(height) / 2,
)
}
pub fn digits_grid(&self) -> &BrailleGrid {
&self.digits
}
pub fn accent_grid(&self) -> &BrailleGrid {
&self.accent
}
pub fn scale(&self) -> usize {
self.laid_out_scale
}
}
fn paint_digits(grid: &mut BrailleGrid, layout: &Layout, scale: usize) {
let mut cell_x = 0;
for (source_wide, bitmap) in &layout.glyphs {
for dot_y in 0..bitmap.height {
for dot_x in 0..bitmap.width {
if !bitmap.get(dot_x, dot_y) {
continue;
}
let left = (cell_x * font::CELL_DOTS + dot_x) * scale;
let top = dot_y * scale;
for sy in 0..scale {
for sx in 0..scale {
grid.raise_dot(left + sx, top + sy);
}
}
}
}
cell_x += source_wide + GAP;
}
}
fn paint_rule(
grid: &mut BrailleGrid,
layout: &Layout,
scale: usize,
fraction: f64,
) {
let width_dots = layout.cells_wide() * font::CELL_DOTS * scale;
let baseline = digit_rows(scale) * DOTS_Y + RULE_GAP_ROWS * DOTS_Y;
let hairline = baseline + RULE_DOTS - 1;
for dot_x in 0..width_dots {
grid.raise_dot(dot_x, hairline);
}
let filled = (width_dots as f64 * fraction.clamp(0.0, 1.0)).round() as usize;
for dot_x in 0..filled.min(width_dots) {
for dy in 0..RULE_DOTS {
grid.raise_dot(dot_x, baseline + dy);
}
}
}
fn stamp(
grid: &BrailleGrid,
canvas: &mut Canvas,
at: (usize, usize),
color: Color,
) {
for cell_y in 0..grid.height() {
let y = at.1 + cell_y;
if y >= canvas.height() {
break;
}
for cell_x in 0..grid.width() {
let symbol = grid.cell_char(cell_x, cell_y);
if symbol == ' ' {
continue;
}
let x = at.0 + cell_x;
if x >= canvas.width() {
break;
}
canvas.set(x, y, Cell::new(symbol, color, Attribute::Reset));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
thread_local! {
static FAKE_TIME: std::cell::Cell<Option<Duration>> =
const { std::cell::Cell::new(None) };
}
fn fake_clock() -> SystemTime {
FAKE_TIME.with(|cell| match cell.get() {
Some(offset) => UNIX_EPOCH + offset,
None => UNIX_EPOCH,
})
}
fn set_fake_time(seconds: u64) {
FAKE_TIME.with(|cell| cell.set(Some(Duration::from_secs(seconds))));
}
fn set_fake_time_ms(seconds: u64, millis: u64) {
FAKE_TIME.with(|cell| {
cell.set(Some(
Duration::from_secs(seconds) + Duration::from_millis(millis),
))
});
}
fn clock_at(size: (u16, u16)) -> Clock {
Clock::with_clock(ClockOptions::default(), size, fake_clock)
}
#[test]
fn a_reading_is_inside_every_field_s_range() {
for _ in 0..64 {
let reading = read_time(system_clock());
assert!(reading.hour < 24, "hour {} is not 0..24", reading.hour);
assert!(
reading.minute < 60,
"minute {} is not 0..60",
reading.minute
);
assert!(
reading.second < 60,
"second {} is not 0..60",
reading.second
);
assert!(
(0.0..1.0).contains(&reading.fraction),
"fraction {} is not 0..1",
reading.fraction
);
}
}
#[test]
fn the_text_is_zero_padded_and_follows_the_seconds_option() {
let reading = ClockTime {
hour: 7,
minute: 4,
second: 9,
fraction: 0.0,
};
assert_eq!(time_text(&reading, true), "07:04:09");
assert_eq!(time_text(&reading, false), "07:04");
let midnight = ClockTime {
hour: 0,
minute: 0,
second: 0,
fraction: 0.0,
};
assert_eq!(time_text(&midnight, true), "00:00:00");
}
#[test]
fn hours_run_to_twenty_three_and_not_to_twelve() {
let mut reading = ClockTime {
hour: 23,
minute: 59,
second: 59,
fraction: 0.0,
};
assert_eq!(time_text(&reading, false), "23:59");
reading.hour = 13;
assert_eq!(time_text(&reading, false), "13:59");
reading.hour = 12;
assert_eq!(time_text(&reading, false), "12:59");
}
#[test]
fn the_rule_tracks_the_period_the_digits_show() {
let quarter = ClockTime {
hour: 0,
minute: 10,
second: 15,
fraction: 0.5,
};
assert!((rule_fraction(&quarter, true) - 0.5).abs() < 1e-9);
assert!((rule_fraction(&quarter, false) - 10.5 / 60.0).abs() < 1e-9);
let start = ClockTime {
hour: 0,
minute: 0,
second: 0,
fraction: 0.0,
};
assert_eq!(rule_fraction(&start, true), 0.0);
assert_eq!(rule_fraction(&start, false), 0.0);
}
#[test]
fn a_layout_is_wider_than_its_character_count() {
let with_seconds = Layout::new("12:34:56");
let without = Layout::new("12:34");
let separator_cells =
font::cell_width(font::SEPARATOR).expect("in the font");
assert_eq!(
with_seconds.cells_wide(),
6 * font::GLYPH_W + 2 * separator_cells + 7 * GAP
);
assert_eq!(
without.cells_wide(),
4 * font::GLYPH_W + separator_cells + 4 * GAP
);
assert!(
with_seconds.cells_wide() > "12:34:56".len(),
"the layout ignored the separator's width"
);
}
#[test]
fn every_time_of_day_is_the_same_width() {
let mut widths = std::collections::HashSet::new();
for hour in 0..24 {
for minute in 0..60 {
let text = format!("{hour:02}:{minute:02}:00");
widths.insert(Layout::new(&text).cells_wide());
}
}
assert_eq!(
widths.len(),
1,
"the clock's width changes with its digits: {widths:?}. A `1` that is \
narrower than a `0` would make the clock twitch sideways every hour."
);
}
#[test]
fn the_scale_is_the_largest_even_one_that_fits() {
let wide = Layout::new("12:34:56").cells_wide();
for &(width, height) in
&[(80, 24), (120, 40), (200, 50), (400, 200), (1000, 300)]
{
let scale = scale_for(wide, (width, height));
assert_eq!(
scale % 2,
0,
"at {width}x{height} the scale is {scale}, which is odd, so every \
digit's horizontal edges fall between two dot rows of a cell"
);
let next = scale + SCALE_STEP;
assert!(
wide * next > width as usize || total_rows(next) > height as usize,
"at {width}x{height} the scale is {scale} but {next} also fits"
);
}
assert_eq!(scale_for(wide, (80, 24)), 2);
assert_eq!(scale_for(wide, (200, 50)), 4);
for &(width, height) in &[(6, 6), (1, 1), (40, 10), (60, 12)] {
assert_eq!(
scale_for(wide, (width, height)),
1,
"at {width}x{height} the scale should be the floor of 1"
);
}
let narrow = Layout::new("12:34").cells_wide();
for &(width, height) in &[(120, 40), (200, 50), (400, 200)] {
assert!(
scale_for(narrow, (width, height))
> scale_for(wide, (width, height)),
"at {width}x{height} turning seconds off did not make the clock \
bigger: {} against {}",
scale_for(narrow, (width, height)),
scale_for(wide, (width, height))
);
}
assert_eq!(scale_for(wide, (80, 24)), scale_for(narrow, (80, 24)));
assert_eq!(scale_for(wide, (6, 6)), 1);
assert_eq!(scale_for(wide, (1, 1)), 1);
}
fn bottom_is_a_digit_row(bottom: usize, digit_dot_rows: usize) -> bool {
bottom < digit_dot_rows
}
#[test]
fn a_changing_clock_leaves_nothing_of_the_old_time_on_screen() {
const START: u64 = 10 * 3600 + 9 * 60 + 55;
for &(width, height) in &[(200, 50), (80, 24), (120, 40)] {
let mut clock = clock_at((width, height));
let mut screen =
vec![vec![Cell::default(); width as usize]; height as usize];
for step in 0..10u64 {
set_fake_time(START + step);
for (x, y, cell) in clock.get_diff() {
if x < width as usize && y < height as usize {
screen[y][x] = cell;
}
}
let reading =
read_time(UNIX_EPOCH + Duration::from_secs(START + step));
let expected = time_text(&reading, clock.options.show_seconds);
let mut fresh = clock_at((width, height));
let mut reference =
vec![vec![Cell::default(); width as usize]; height as usize];
for (x, y, cell) in fresh.get_diff() {
if x < width as usize && y < height as usize {
reference[y][x] = cell;
}
}
let stale: Vec<String> = (0..height as usize)
.flat_map(|y| (0..width as usize).map(move |x| (x, y)))
.filter(|&(x, y)| screen[y][x].symbol != reference[y][x].symbol)
.map(|(x, y)| {
format!(
"({x},{y}) {:?} should be {:?}",
screen[y][x].symbol, reference[y][x].symbol
)
})
.collect();
assert!(
stale.is_empty(),
"at {width}x{height}, showing {expected} (step {step}), the \
screen still holds {} cell(s) from the previous time. First \
few: {}",
stale.len(),
stale.iter().take(8).cloned().collect::<Vec<_>>().join("; ")
);
}
}
}
#[test]
fn no_two_glyphs_touch() {
for &(width, height) in &[(200, 50), (400, 200), (80, 24), (120, 40)] {
set_fake_time(20 * 3600 + 34 * 60 + 56);
let mut clock = clock_at((width, height));
clock.draw();
let scale = clock.laid_out_scale;
let grid = clock.digits_grid();
let digit_rows_dots = digit_rows(scale) * DOTS_Y;
let inked: Vec<bool> = (0..grid.dot_width())
.map(|x| (0..digit_rows_dots).any(|y| grid.dot(x, y)))
.collect();
let runs = ink_runs(&inked);
let glyphs = time_text(
&ClockTime {
hour: 20,
minute: 34,
second: 56,
fraction: 0.0,
},
clock.options.show_seconds,
)
.chars()
.count();
assert_eq!(
runs.len(),
glyphs,
"at {width}x{height} (scale {scale}) the clock draws {} ink runs for \
{glyphs} glyphs, so glyphs are merging into their neighbours. \
Runs: {runs:?}",
runs.len()
);
}
}
fn ink_runs(flags: &[bool]) -> Vec<(usize, usize)> {
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut start: Option<usize> = None;
for (i, f) in flags.iter().enumerate() {
match (*f, start) {
(true, None) => start = Some(i),
(false, Some(s)) => {
runs.push((s, i - 1));
start = None;
}
_ => {}
}
}
if let Some(s) = start {
runs.push((s, flags.len() - 1));
}
runs
}
#[test]
fn the_gap_between_glyphs_is_the_width_it_should_be() {
set_fake_time(20 * 3600 + 34 * 60 + 56);
for &(width, height) in &[(200, 50), (80, 24), (400, 200)] {
let mut clock = clock_at((width, height));
clock.draw();
let scale = clock.laid_out_scale;
let grid = clock.digits_grid();
let digit_rows_dots = digit_rows(scale) * DOTS_Y;
let inked: Vec<bool> = (0..grid.dot_width())
.map(|x| (0..digit_rows_dots).any(|y| grid.dot(x, y)))
.collect();
let runs = ink_runs(&inked);
let glyphs = 8;
assert!(
runs.len() > 1,
"at {width}x{height} there is {runs:?} -- one ink run, so there are \
no gaps to check and this test would pass on any drawing"
);
assert_eq!(
runs.len(),
glyphs,
"at {width}x{height} (scale {scale}) the clock draws {} ink runs \
for {glyphs} glyphs. Runs: {runs:?}",
runs.len()
);
let expected = GAP * font::CELL_DOTS * scale;
for pair in runs.windows(2) {
let gap = pair[1].0 - pair[0].1 - 1;
assert!(
gap >= expected,
"at {width}x{height} (scale {scale}) two glyphs are {gap} dots \
apart, and the layout asks for {expected}"
);
}
}
}
#[test]
fn a_digits_horizontal_edges_land_on_cell_boundaries() {
set_fake_time(23 * 3600 + 45 * 60 + 30);
let mut clock = clock_at((200, 50));
clock.draw();
let scale = clock.laid_out_scale;
assert!(
scale >= 2,
"the clock is at scale {scale}, too small to check"
);
let grid = clock.digits_grid();
let rows = grid.dot_height();
let digit_dot_rows = digit_rows(scale) * DOTS_Y;
let mut ragged: Vec<String> = Vec::new();
for dot_x in 0..grid.dot_width() {
let column: Vec<usize> =
(0..rows).filter(|y| grid.dot(dot_x, *y)).collect();
for window in column.windows(2) {
let (above, below) = (window[0], window[1]);
if below - above > 1 && below / DOTS_Y == above / DOTS_Y {
ragged.push(format!(
"column {dot_x}: ink at dot row {above} and again at {below}, \
both inside cell row {}",
above / DOTS_Y
));
}
}
let extremes = match (column.first(), column.last()) {
(Some(&top), Some(&bottom))
if bottom_is_a_digit_row(bottom, digit_dot_rows) =>
{
Some((top, bottom))
}
_ => None,
};
if let Some((top, bottom)) = extremes {
if top > 0 && top / DOTS_Y == (top - 1) / DOTS_Y {
ragged.push(format!(
"column {dot_x}: ink starts at dot row {top}, inside cell \
row {}, so the glyph's top edge is drawn across a cell",
top / DOTS_Y
));
}
if bottom + 1 < rows && bottom / DOTS_Y == (bottom + 1) / DOTS_Y {
ragged.push(format!(
"column {dot_x}: ink ends at dot row {bottom}, inside cell \
row {}, so the glyph's bottom edge is drawn across a cell",
bottom / DOTS_Y
));
}
}
}
assert!(
ragged.is_empty(),
"the digits' horizontal edges do not land on cell boundaries, so the \
glyphs render with ragged top and bottom rows. {} column(s) affected, \
first few: {}",
ragged.len(),
ragged
.iter()
.take(5)
.cloned()
.collect::<Vec<_>>()
.join("; ")
);
}
#[test]
fn a_short_terminal_bounds_the_scale_by_height() {
let wide = Layout::new("12:34:56").cells_wide();
let scale = scale_for(wide, (200, 8));
assert!(
total_rows(scale) <= 8,
"at 200x8 the clock wants {scale} rows of an 8-row terminal"
);
assert!(total_rows(scale + SCALE_STEP) > 8);
}
#[test]
fn nothing_is_drawn_outside_the_terminal() {
set_fake_time(12 * 3600 + 34 * 60 + 56);
for (width, height) in
[(6, 6), (1, 1), (8, 200), (200, 8), (80, 24), (200, 50)]
{
let mut clock = clock_at((width, height));
for frame in 0..3 {
let diff = clock.draw();
for (x, y, _) in diff {
assert!(
x < width as usize && y < height as usize,
"at {width}x{height} frame {frame} wrote ({x}, {y})"
);
}
}
clock.update_size(height, width);
for (x, y, _) in clock.draw() {
assert!(
x < height as usize && y < width as usize,
"at {width}x{height}, resized to {height}x{width}, wrote \
({x}, {y}) outside the new size"
);
}
}
}
#[test]
fn crossing_a_second_redraws_only_the_digit_that_changed() {
set_fake_time(12 * 3600 + 34 * 60 + 56);
let mut clock = clock_at((80, 24));
clock.draw();
assert!(
clock.draw().is_empty(),
"a frame at an unchanged instant rewrote cells"
);
set_fake_time(12 * 3600 + 34 * 60 + 57);
let tick = clock.draw();
assert!(!tick.is_empty(), "a new second changed nothing");
let cells = (80 * 24) as usize;
assert!(
tick.len() < cells / 4,
"a one-digit tick rewrote {} of {cells} cells, so the clock is \
repainting its whole face every second",
tick.len()
);
}
#[test]
fn the_rule_grows_monotonically_within_a_second() {
set_fake_time(0);
let mut clock = clock_at((200, 50));
clock.draw();
assert_eq!(
bar_width(&clock),
0,
"the rule is already {} dots along at the top of a second",
bar_width(&clock)
);
assert_eq!(
track_width(&clock),
clock.accent_grid().dot_width(),
"the rule has no track to grow along"
);
let mut previous = 0;
for step in 1..40 {
set_fake_time_ms(0, step * 25);
clock.draw();
let width = bar_width(&clock);
assert!(
width >= previous,
"the rule shrank at {}ms: {width} against {previous}",
step * 25
);
previous = width;
}
let full = clock.accent_grid().dot_width();
assert!(
previous * 16 >= full * 14,
"at 975ms the bar is {previous} of {full} dots"
);
}
fn bar_width(clock: &Clock) -> usize {
let grid = clock.accent_grid();
let scale = clock.laid_out_scale;
let baseline = digit_rows(scale) * DOTS_Y + RULE_GAP_ROWS * DOTS_Y;
(0..grid.dot_width())
.filter(|x| (0..RULE_DOTS).all(|dy| grid.dot(*x, baseline + dy)))
.count()
}
fn track_width(clock: &Clock) -> usize {
let grid = clock.accent_grid();
let scale = clock.laid_out_scale;
let hairline =
digit_rows(scale) * DOTS_Y + RULE_GAP_ROWS * DOTS_Y + RULE_DOTS - 1;
(0..grid.dot_width())
.filter(|x| grid.dot(*x, hairline))
.count()
}
#[test]
fn the_rule_starts_over_at_the_top_of_each_period() {
set_fake_time_ms(60, 800);
let mut clock = clock_at((200, 50));
clock.draw();
let late = bar_width(&clock);
assert!(
late * 5 >= clock.accent_grid().dot_width() * 4,
"at 800ms the rule is only {late} of {} dots",
clock.accent_grid().dot_width()
);
set_fake_time(61);
clock.draw();
assert_eq!(
bar_width(&clock),
0,
"the rule did not reset at the top of the second"
);
}
#[test]
fn seconds_off_is_a_bigger_clock_and_a_minute_long_rule() {
set_fake_time(0);
let mut with = clock_at((120, 40));
with.draw();
let wide_rows = with.digits_grid().height();
let mut without = Clock::with_clock(
ClockOptions {
show_seconds: false,
..ClockOptions::default()
},
(120, 40),
fake_clock,
);
without.draw();
assert_eq!(
(with.laid_out_scale, without.laid_out_scale),
(2, 4),
"at 120x40 the seconds clock is at scale {} and the seconds-off one at \
{}. The scale is what 'bigger' means here, so if this changed then the \
comment above is stale.",
with.laid_out_scale,
without.laid_out_scale
);
assert!(
without.digits_grid().height() > wide_rows,
"without seconds the clock is {} rows against {wide_rows}, so the \
larger scale bought no height",
without.digits_grid().height()
);
let mut chosen = None;
for second in 0..3600u64 {
let reading = read_time(UNIX_EPOCH + Duration::from_secs(second));
if rule_fraction(&reading, false) * 4.0 <= rule_fraction(&reading, true)
{
chosen = Some((second, reading));
break;
}
}
let (instant, reading) = chosen.expect(
"no instant in the first hour has the minute rule at a quarter of the \
seconds rule, which cannot happen -- `rule_fraction` is not being read",
);
set_fake_time(instant);
with.draw();
without.draw();
let expected_seconds = (with.accent_grid().dot_width() as f64
* rule_fraction(&reading, true))
as usize;
let expected_minutes = (without.accent_grid().dot_width() as f64
* rule_fraction(&reading, false))
as usize;
assert_eq!(
bar_width(&with),
expected_seconds,
"the seconds rule is {} dots where {expected_seconds} of {} is \
{reading:?}",
bar_width(&with),
with.accent_grid().dot_width()
);
assert_eq!(
bar_width(&without),
expected_minutes,
"the minute rule is {} dots where {expected_minutes} of {} is \
{reading:?}",
bar_width(&without),
without.accent_grid().dot_width()
);
assert!(
expected_minutes * 4 <= expected_seconds,
"at {reading:?} the two bars are {expected_minutes} and \
{expected_seconds} dots, which are too close to tell the periods \
apart -- the search should have found a better instant"
);
}
#[test]
fn the_frame_carries_the_configured_colours_and_is_centred() {
let options = ClockOptions {
show_seconds: true,
color: Color::Red,
accent: Color::Blue,
};
set_fake_time(9 * 3600 + 8 * 60 + 7);
let mut clock = Clock::with_clock(options, (80, 24), fake_clock);
let frame = clock.draw();
assert!(!frame.is_empty(), "the first frame drew nothing");
assert!(
frame.iter().any(|(_, _, cell)| cell.color == Color::Red),
"no digit was drawn in the configured colour"
);
assert!(
frame.iter().any(|(_, _, cell)| cell.color == Color::Blue),
"the separator and rule were not drawn in the accent colour"
);
assert!(
frame.iter().all(|(_, _, cell)| cell.symbol != ' '),
"a blank cell was reported, which would erase the background"
);
let layout = Layout::new("09:08:07");
let clock_w =
layout.cells_wide() * scale_for(layout.cells_wide(), (80, 24));
let left = frame.iter().map(|(x, _, _)| *x).min().expect("some cells");
let slack = (80 - clock_w) / 2;
assert!(
left.abs_diff(slack) <= 1,
"the clock starts at column {left}, and centring puts it at {slack}"
);
}
#[test]
fn a_resize_repaints_the_whole_terminal() {
set_fake_time(3 * 3600 + 2 * 60 + 1);
let mut clock = clock_at((80, 24));
clock.draw();
clock.update_size(60, 20);
let frame = clock.draw();
let columns: std::collections::BTreeSet<usize> =
frame.iter().map(|(x, _, _)| *x).collect();
let layout = Layout::new("03:02:01");
let scale = scale_for(layout.cells_wide(), (60, 20));
let expected = layout.cells_wide() * scale;
let left = (60 - expected) / 2;
assert!(
columns.contains(&left) && columns.contains(&(left + expected - 1)),
"after a resize the clock spans {columns:?}, which does not reach both \
edges of its own {expected} cell box at column {left}"
);
assert!(
columns.iter().all(|x| *x < 60),
"a resized clock wrote outside 60 columns: {columns:?}"
);
}
#[test]
fn the_grids_are_the_size_of_the_clock() {
set_fake_time(23 * 3600 + 59 * 60 + 58);
let mut clock = clock_at((400, 200));
clock.draw();
let layout = Layout::new("23:59:59");
let scale = scale_for(layout.cells_wide(), (400, 200));
assert_eq!(clock.digits_grid().width(), layout.cells_wide() * scale);
assert_eq!(clock.digits_grid().height(), total_rows(scale));
assert!(
clock.digits_grid().width() < 400,
"the digit grid is {} cells wide on a 400 column terminal",
clock.digits_grid().width()
);
}
#[test]
fn the_separator_and_the_rule_do_not_share_a_cell_with_a_digit() {
set_fake_time_ms(12 * 3600 + 30 * 60 + 30, 500);
let mut clock = clock_at((200, 50));
clock.draw();
let digits = clock.digits_grid();
let accent = clock.accent_grid();
assert_eq!(digits.width(), accent.width());
assert_eq!(digits.height(), accent.height());
for cell_y in 0..digits.height() {
for cell_x in 0..digits.width() {
assert!(
!(digits.dot(cell_x, cell_y) && accent.dot(cell_x, cell_y)),
"cell ({cell_x}, {cell_y}) has ink in both grids, so one stamp \
would erase the other"
);
}
}
}
}