Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support using heh as a Ratatui widget #120

Merged
merged 7 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,45 @@ pacman -S heh
apk add heh
```

## Using as a Ratatui widget

`heh` can be used a library and embedded into other TUI applications which use [Ratatui](https://ratatui.rs) and [crossterm](https://github.com/crossterm-rs/crossterm).

Add `heh` to your dependencies in `Cargo.toml`:

```toml
[dependencies]
ratatui = "0.24"
crossterm = "0.27"
heh = "0.4"
```

Create the application:

```rust
use heh::app::Application as Heh;
use heh::decoder::Encoding;

let file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap();
let heh = Heh::new(file, Encoding::Ascii, 0).unwrap();
```

Then you can render a frame as follows:

```rust
terminal.draw(|frame| {
heh.render_frame(frame, frame.size());
});
```

To handle key events:

```rust
heh.handle_input(&crossterm::event::Event::Key(/* */)).unwrap();
```

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to add a link to binsider as an example use case of using this as a library!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

Added in 0d77149

See the [binsider](https://github.com/orhun/binsider) project for an example use case.

# Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md).
83 changes: 60 additions & 23 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@
//!
//! The application holds the main components of the other modules, like the [`ScreenHandler`],
//! [`LabelHandler`], and input handling, as well as the state data that each of them need.
//!
//! [`ScreenHandler`]: crate::screen::Handler
//! [`LabelHandler`]: crate::label::Handler

use std::{error::Error, fs::File, process};

use arboard::Clipboard;
use crossterm::event::{self, Event, KeyEventKind};
use ratatui::layout::Rect;
use ratatui::Frame;

use crate::buffer::AsyncBuffer;
use crate::decoder::Encoding;
use crate::windows::search::Search;
use crate::{
input,
label::LabelHandler,
screen::ScreenHandler,
label::Handler as LabelHandler,
screen::Handler as ScreenHandler,
windows::{
editor::Editor, jump_to_byte::JumpToByte, unsaved_changes::UnsavedChanges, KeyHandler,
Window,
Expand Down Expand Up @@ -53,9 +58,9 @@
}

/// State Information needed by the [`ScreenHandler`] and [`KeyHandler`].
pub(crate) struct AppData {
pub struct Data {
/// The file under editing.
pub(crate) file: File,
pub file: File,

/// The file content.
pub(crate) contents: AsyncBuffer,
Expand Down Expand Up @@ -103,7 +108,7 @@
pub(crate) search_offsets: Vec<usize>,
}

impl AppData {
impl Data {
/// Reindexes contents to find locations of the user's search term.
pub(crate) fn reindex_search(&mut self) {
self.search_offsets = self
Expand All @@ -117,32 +122,30 @@

/// Application provides the user interaction interface and renders the terminal screen in response
/// to user actions.
pub(crate) struct Application {
pub struct Application {
/// The application's state and data.
pub(crate) data: AppData,
pub data: Data,

/// Renders and displays objects to the terminal.
pub(crate) display: ScreenHandler,

/// The labels at the bottom of the UI that provide information
/// based on the current offset.
pub(crate) labels: LabelHandler,
pub labels: LabelHandler,

/// The window that handles keyboard input. This is usually in the form of the Hex/ASCII editor
/// or popups.
pub(crate) key_handler: Box<dyn KeyHandler>,
pub key_handler: Box<dyn KeyHandler>,
}

impl Application {
/// Creates a new application, focusing the Hex editor and starting with an offset of 0 by
/// default. This is called once at the beginning of the program.
///
/// # Errors
///
/// This errors out if the file specified is empty.
pub(crate) fn new(
file: File,
encoding: Encoding,
offset: usize,
) -> Result<Self, Box<dyn Error>> {
pub fn new(file: File, encoding: Encoding, offset: usize) -> Result<Self, Box<dyn Error>> {

Check warning on line 148 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L148

Added line #L148 was not covered by tests
let contents = AsyncBuffer::new(&file)?;
if contents.is_empty() {
eprintln!("heh does not support editing empty files");
Expand All @@ -164,7 +167,7 @@
let display = ScreenHandler::new()?;

let app = Self {
data: AppData {
data: Data {

Check warning on line 170 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L170

Added line #L170 was not covered by tests
file,
contents,
encoding,
Expand Down Expand Up @@ -193,11 +196,16 @@

/// A loop that repeatedly renders the terminal and modifies state based on input. Is stopped
/// when input handling receives CNTRLq, the command to stop.
pub(crate) fn run(&mut self) -> Result<(), Box<dyn Error>> {
///
/// # Errors
///
/// This errors when the UI fails to render.
pub fn run(&mut self) -> Result<(), Box<dyn Error>> {

Check warning on line 203 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L203

Added line #L203 was not covered by tests
ScreenHandler::setup()?;
loop {
self.render_display()?;
if !self.handle_input()? {
let event = event::read()?;
if !self.handle_input(&event)? {

Check warning on line 208 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L207-L208

Added lines #L207 - L208 were not covered by tests
break;
}
}
Expand All @@ -208,25 +216,54 @@
/// Renders the display. This is a wrapper around [`ScreenHandler`'s
/// render](ScreenHandler::render) method.
fn render_display(&mut self) -> Result<(), Box<dyn Error>> {
self.display.render(&mut self.data, &self.labels, self.key_handler.as_ref())?;
Ok(())
self.display.render(&mut self.data, &self.labels, self.key_handler.as_ref())
orhun marked this conversation as resolved.
Show resolved Hide resolved
}

Check warning on line 220 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L219-L220

Added lines #L219 - L220 were not covered by tests

/// Renders a single frame for the given area.
pub fn render_frame(&mut self, frame: &mut Frame, area: Rect) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you be willing to create an issue so that at some point I remember to create tests specifically for render_frame and handle_input? I'll have to look into it but I think I'll want more coverage on these now that they'll be library functions.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beep beep, you got it!
#124

self.data.contents.compute_new_window(self.data.offset);
// We check if we need to recompute the terminal size in the case that the saved off
// variable differs from the current frame, which can occur when a terminal is resized
// between an event handling and a rendering.
if area != self.display.terminal_size {
self.display.terminal_size = area;
self.display.comp_layouts =
ScreenHandler::calculate_dimensions(area, self.key_handler.as_ref());
// We change the start_address here to ensure that 0 is ALWAYS the first start
// address. We round to preventing constant resizing always moving to 0.
self.data.start_address = (self.data.start_address
+ (self.display.comp_layouts.bytes_per_line / 2))
/ self.display.comp_layouts.bytes_per_line
* self.display.comp_layouts.bytes_per_line;
}
ScreenHandler::render_frame(
frame,
self.display.terminal_size,
&mut self.data,
&self.labels,
self.key_handler.as_ref(),
&self.display.comp_layouts,
);

Check warning on line 246 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L223-L246

Added lines #L223 - L246 were not covered by tests
}

/// Handles all forms of user input. This calls out to code in [input], which uses
/// [Application's `key_handler` method](Application::key_handler) to determine what to do for
/// key input.
fn handle_input(&mut self) -> Result<bool, Box<dyn Error>> {
let event = event::read()?;
///
/// # Errors
///
/// This errors when handling the key event fails.
pub fn handle_input(&mut self, event: &Event) -> Result<bool, Box<dyn Error>> {

Check warning on line 256 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L256

Added line #L256 was not covered by tests
match event {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
self.labels.notification.clear();
return input::handle_key_input(self, key);
return input::handle_key_input(self, *key);

Check warning on line 261 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L261

Added line #L261 was not covered by tests
}
}
Event::Mouse(mouse) => {
self.labels.notification.clear();
input::handle_mouse_input(self, mouse);
input::handle_mouse_input(self, *mouse);

Check warning on line 266 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L266

Added line #L266 was not covered by tests
}
Event::Resize(_, _) | Event::FocusGained | Event::FocusLost | Event::Paste(_) => {}
}
Expand Down
4 changes: 3 additions & 1 deletion src/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Decoder utilities.

use std::str::from_utf8;

use crate::character::{Category, RichChar, Type, CHARACTER_FILL, CHARACTER_UNKNOWN};
Expand Down Expand Up @@ -80,7 +82,7 @@ impl<'a> Iterator for LossyUTF8Decoder<'a> {
}

#[derive(Copy, Clone, Debug)]
pub(crate) enum Encoding {
pub enum Encoding {
Ascii,
Utf8,
}
Expand Down
10 changes: 5 additions & 5 deletions src/label.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl fmt::Display for Endianness {
}

#[derive(Default)]
pub(crate) struct LabelHandler {
pub struct Handler {
signed_eight: String,
signed_sixteen: String,
signed_thirtytwo: String,
Expand All @@ -59,11 +59,11 @@ pub(crate) struct LabelHandler {
stream_length: usize,
stream_length_string: String,
pub(crate) offset: String,
pub(crate) notification: String,
pub notification: String,
pub(crate) endianness: Endianness,
}

impl Index<&str> for LabelHandler {
impl Index<&str> for Handler {
type Output = String;

fn index(&self, index: &str) -> &Self::Output {
Expand All @@ -89,7 +89,7 @@ impl Index<&str> for LabelHandler {
}
}

impl LabelHandler {
impl Handler {
pub(crate) fn new(bytes: &[u8], offset: usize) -> Self {
let mut labels = Self { ..Default::default() };
labels.update_stream_length(8);
Expand Down Expand Up @@ -243,7 +243,7 @@ mod tests {
fn test_binary_label() {
// Given a label handler with the content 'hello' and offset of 0
let content = "hello".as_bytes();
let mut label_handler = LabelHandler::new(content, 0);
let mut label_handler = Handler::new(content, 0);
// The binary label should contain the binary veresion of the first character
assert!(label_handler.binary.eq("01101000"));

Expand Down
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pub mod app;
mod buffer;
mod character;
mod chunk;
pub mod decoder;
pub mod input;
pub mod label;
pub mod screen;
pub mod windows;
15 changes: 2 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,8 @@ use std::{error::Error, fs::OpenOptions, io, process};
use clap::{Parser, ValueEnum};
use crossterm::tty::IsTty;

use app::Application;

use crate::decoder::Encoding;

mod app;
mod buffer;
mod character;
mod chunk;
mod decoder;
mod input;
mod label;
mod screen;
mod windows;
use heh::app::Application;
use heh::decoder::Encoding;

const ABOUT: &str = "
A HEx Helper to edit bytes by the nibble.
Expand Down
Loading
Loading