Skip to content

Instantly share code, notes, and snippets.

@Cypher1
Created October 27, 2022 03:16
Show Gist options
  • Save Cypher1/bf04f8f980bb8cb9c9ae10eb9c4c98ef to your computer and use it in GitHub Desktop.
Save Cypher1/bf04f8f980bb8cb9c9ae10eb9c4c98ef to your computer and use it in GitHub Desktop.
Demonstrate using CrossTerm for a TUI
[package]
name = "rusterm"
version = "0.1.0"
edition = "2021"
[dependencies]
crokey = "0.5.1"
crossbeam = "0.8.2"
crossterm = "0.25.0"
notify = "5.0.0"
termimad = "0.20.3"
tokio = "1.21.2"
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
use std::{
thread,
time::{Duration, Instant},
};
use std::io::{stdout, Write};
use crossterm::{
cursor::{MoveTo, SavePosition, RestorePosition},
terminal::{Clear, ClearType},
style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor},
// ExecutableCommand,
QueueableCommand, Result,
};
const TARGET_FPS: u64 = 2;
const MILLIS_PER_SECOND: u64 = 1000;
const TARGET_MILLIS: u64 = MILLIS_PER_SECOND/TARGET_FPS;
fn main() -> Result<()> {
let start = Instant::now();
stdout().queue(Clear(ClearType::All))?;
let mut count = 0;
loop {
let wait_time = Duration::from_millis(TARGET_MILLIS);
let frame_start = Instant::now();
count += 1;
let millis_per_frame = start.elapsed().as_millis().checked_div(count as u128).unwrap_or(0);
let fps = (MILLIS_PER_SECOND as u128).checked_div(millis_per_frame).unwrap_or(0);
let last_line = 5;
stdout()
// .queue(Clear(ClearType::All))?
.queue(SavePosition)?
.queue(MoveTo(0, last_line))?
.queue(Clear(ClearType::FromCursorUp))?
.queue(SetForegroundColor(Color::Blue))?
.queue(SetBackgroundColor(Color::Red))?
.queue(MoveTo(0, 0))?
.queue(Print("Styled text here (1).\n"))?
.queue(SetForegroundColor(Color::Red))?
.queue(SetBackgroundColor(Color::Blue))?
.queue(Print("Styled text here (2).\n"))?
.queue(SetForegroundColor(Color::White))?
.queue(SetBackgroundColor(Color::Black))?
.queue(Print("Styled text here (3).\n"))?
.queue(Print(&format!("Iterations: {}. Average FPS: {}.\n", count, fps)))?
.queue(ResetColor)?
.queue(RestorePosition)?;
stdout().flush()?;
let runtime = frame_start.elapsed();
if let Some(remaining) = wait_time.checked_sub(runtime) {
thread::sleep(remaining);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment