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 4 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
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,43 @@ 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

# Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md).
56 changes: 40 additions & 16 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

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

use crate::buffer::AsyncBuffer;
use crate::decoder::Encoding;
Expand Down Expand Up @@ -53,9 +55,9 @@
}

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

/// The file content.
pub(crate) contents: AsyncBuffer,
Expand Down Expand Up @@ -117,16 +119,16 @@

/// 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: AppData,

/// 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.
Expand All @@ -138,11 +140,7 @@
/// default. This is called once at the beginning of the program.
///
/// 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 143 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L143

Added line #L143 was not covered by tests
let contents = AsyncBuffer::new(&file)?;
if contents.is_empty() {
eprintln!("heh does not support editing empty files");
Expand Down Expand Up @@ -193,11 +191,12 @@

/// 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>> {
pub fn run(&mut self) -> Result<(), Box<dyn Error>> {

Check warning on line 194 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L194

Added line #L194 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 199 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L198-L199

Added lines #L198 - L199 were not covered by tests
break;
}
}
Expand All @@ -208,15 +207,40 @@
/// 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 211 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L210-L211

Added lines #L210 - L211 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 237 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L214-L237

Added lines #L214 - L237 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()?;
pub fn handle_input(&mut self, event: Event) -> Result<bool, Box<dyn Error>> {

Check warning on line 243 in src/app.rs

View check run for this annotation

Codecov / codecov/patch

src/app.rs#L243

Added line #L243 was not covered by tests
match event {
Event::Key(key) => {
if key.kind == KeyEventKind::Press {
Expand Down
2 changes: 1 addition & 1 deletion src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl<'a> Iterator for LossyUTF8Decoder<'a> {
}

#[derive(Copy, Clone, Debug)]
pub(crate) enum Encoding {
pub enum Encoding {
Ascii,
Utf8,
}
Expand Down
4 changes: 2 additions & 2 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 LabelHandler {
signed_eight: String,
signed_sixteen: String,
signed_thirtytwo: String,
Expand All @@ -59,7 +59,7 @@ 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,
}

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;
mod input;
mod label;
pub mod screen;
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