-
Notifications
You must be signed in to change notification settings - Fork 59
Terminal colors #138
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
Open
unorsk
wants to merge
2
commits into
itsjunetime:main
Choose a base branch
from
unorsk:terminal-colors
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Terminal colors #138
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,7 +5,7 @@ use core::{ | |
| use std::{ | ||
| borrow::Cow, | ||
| ffi::OsString, | ||
| io::{BufReader, Read as _, Stdout, Write as _, stdout}, | ||
| io::{BufReader, IsTerminal as _, Read as _, Stdout, Write as _, stdout}, | ||
| mem, | ||
| path::PathBuf, | ||
| sync::{Arc, Mutex}, | ||
|
|
@@ -107,6 +107,8 @@ async fn inner_main() -> Result<(), WrappedErr> { | |
| optional -w,--white-color white: String | ||
| /// Custom black color, specified in css format (e.g "000000" or "rgb(0, 0, 0)") | ||
| optional -b,--black-color black: String | ||
| /// Use terminal foreground/background colors for the PDF | ||
| optional -t,--terminal-colors | ||
| /// Print the version and exit | ||
| optional --version | ||
| /// PDF file to read | ||
|
|
@@ -128,37 +130,49 @@ async fn inner_main() -> Result<(), WrappedErr> { | |
| .canonicalize() | ||
| .map_err(|e| WrappedErr(format!("Cannot canonicalize provided file: {e}").into()))?; | ||
|
|
||
| let black = flags | ||
| .black_color | ||
| .as_deref() | ||
| .map(|color| { | ||
| parse_color_to_i32(color).map_err(|e| { | ||
| WrappedErr( | ||
| format!( | ||
| "Couldn't parse black color {color:?}: {e} - is it formatted like a CSS color?" | ||
| if flags.terminal_colors && (flags.black_color.is_some() || flags.white_color.is_some()) { | ||
| return Err(WrappedErr( | ||
| "--terminal-colors cannot be combined with --black-color or --white-color".into() | ||
| )); | ||
| } | ||
|
|
||
| let (black, white) = if flags.terminal_colors { | ||
| query_terminal_colors() | ||
| } else { | ||
| let black = flags | ||
| .black_color | ||
| .as_deref() | ||
| .map(|color| { | ||
| parse_color_to_i32(color).map_err(|e| { | ||
| WrappedErr( | ||
| format!( | ||
| "Couldn't parse black color {color:?}: {e} - is it formatted like a CSS color?" | ||
| ) | ||
| .into() | ||
| ) | ||
| .into() | ||
| ) | ||
| }) | ||
| }) | ||
| }) | ||
| .transpose()? | ||
| .unwrap_or(MUPDF_BLACK); | ||
|
|
||
| let white = flags | ||
| .white_color | ||
| .as_deref() | ||
| .map(|color| { | ||
| parse_color_to_i32(color).map_err(|e| { | ||
| WrappedErr( | ||
| format!( | ||
| "Couldn't parse white color {color:?}: {e} - is it formatted like a CSS color?" | ||
| .transpose()? | ||
| .unwrap_or(MUPDF_BLACK); | ||
|
|
||
| let white = flags | ||
| .white_color | ||
| .as_deref() | ||
| .map(|color| { | ||
| parse_color_to_i32(color).map_err(|e| { | ||
| WrappedErr( | ||
| format!( | ||
| "Couldn't parse white color {color:?}: {e} - is it formatted like a CSS color?" | ||
| ) | ||
| .into() | ||
| ) | ||
| .into() | ||
| ) | ||
| }) | ||
| }) | ||
| }) | ||
| .transpose()? | ||
| .unwrap_or(MUPDF_WHITE); | ||
| .transpose()? | ||
| .unwrap_or(MUPDF_WHITE); | ||
|
|
||
| (black, white) | ||
| }; | ||
|
|
||
| // need to keep it around throughout the lifetime of the program, but don't rly need to use it. | ||
| // Just need to make sure it doesn't get dropped yet. | ||
|
|
@@ -546,6 +560,76 @@ fn parse_color_to_i32(cs: &str) -> Result<i32, csscolorparser::ParseColorError> | |
| Ok(i32::from_be_bytes([0, r, g, b])) | ||
| } | ||
|
|
||
| fn query_terminal_colors() -> (i32, i32) { | ||
| if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { | ||
| return (MUPDF_BLACK, MUPDF_WHITE); | ||
| } | ||
|
|
||
| let Ok(()) = enable_raw_mode() else { | ||
| return (MUPDF_BLACK, MUPDF_WHITE); | ||
| }; | ||
|
|
||
| struct RawModeGuard; | ||
| impl Drop for RawModeGuard { | ||
| fn drop(&mut self) { | ||
| let _ = disable_raw_mode(); | ||
| } | ||
| } | ||
| let _guard = RawModeGuard; | ||
|
|
||
| let stdin = std::io::stdin(); | ||
| let mut handle = stdin.lock(); | ||
|
|
||
| let fg = query_osc_color(10, &mut handle); | ||
| let bg = query_osc_color(11, &mut handle); | ||
| drop(handle); | ||
|
|
||
| (fg.unwrap_or(MUPDF_BLACK), bg.unwrap_or(MUPDF_WHITE)) | ||
| } | ||
|
|
||
| fn query_osc_color(osc: u8, handle: &mut std::io::StdinLock<'_>) -> Option<i32> { | ||
| print!("\x1b]{osc};?\x1b\\"); | ||
| std::io::stdout().flush().ok()?; | ||
|
|
||
| let mut buf = Vec::with_capacity(64); | ||
| let mut prev = None::<u8>; | ||
| let mut byte = [0u8; 1]; | ||
| loop { | ||
| handle.read_exact(&mut byte).ok()?; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Imo we should probably ready into a larger buffer instead of just reading byte-by-byte, right? Less syscalls and such. I think you can essentially just wrap |
||
| let b = byte[0]; | ||
|
|
||
| if b == 0x07 || b == 0x9c { | ||
| break; | ||
| } | ||
| if prev == Some(0x1b) && b == b'\\' { | ||
| buf.pop(); | ||
| break; | ||
| } | ||
|
|
||
| buf.push(b); | ||
| prev = Some(b); | ||
| } | ||
|
|
||
| let input = core::str::from_utf8(&buf).ok()?; | ||
| let rgb_str = input.split("rgb:").nth(1)?; | ||
|
|
||
| let mut parts = rgb_str.split('/'); | ||
| let parse = |hex: &str| -> Option<u8> { | ||
| let val = u16::from_str_radix(hex, 16).ok()?; | ||
| Some(if hex.len() <= 2 { | ||
| val as u8 | ||
| } else { | ||
| (val >> 8) as u8 | ||
| }) | ||
| }; | ||
|
|
||
| let r = parse(parts.next()?)?; | ||
| let g = parse(parts.next()?)?; | ||
| let b = parse(parts.next()?)?; | ||
|
|
||
| Some(i32::from_be_bytes([0, r, g, b])) | ||
| } | ||
|
|
||
| fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> { | ||
| // send the command code to get the terminal window size | ||
| print!("\x1b[14t"); | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reading through this function in general is making me a bit apprehensive, mainly due to reading some descriptions of the spec and seeing how many variants in the response specification there can be. If such a crate exists, I think I'd prefer for this functionality to be pulled in from a different crate that maintains more compatibility between the different standards. I worry that if we ship this as-is, we'll get bug reports from people whose terminals implement some other variant of this spec, and that'll just be really annoying to try to keep up with.
Would you be able to poke around and see if you can find a different crate that does this? If not, obviously, we can build in the functionality, it's just not ideal.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Those variants really only need to be supported by terminals when they receive a request to set the colors. When a terminal is reporting colors, it should only be responding with an rgb format (e.g. something like
rgb:1212/3434/5656). There are a few terminals that have an option to respond with two-digit rgb values (e.g.rgb:12/34/56), but I think the default should always be four-digit rgb. Personally I'd consider it a terminal bug if they respond with anything else.