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

Query window pixel size #166

Merged
merged 2 commits into from
Oct 16, 2020
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,16 @@ To publish a new release run `scripts/release` from the project directory.
Kitty supports hyperlinks since [version 0.19][kitty-0.19], see [Kitty GH-68].
Note that `mdcat` *unconditionally* prints hyperlinks if it detects a kitty terminal.
It makes no attempt to detect whether the Kitty version is compatible or the [`allow_hyperlinks`] setting is enabled.

### Changed
- `mdcat` now asks the controlling terminal for the terminal size and thus correctly detects the terminal size even if standard input, standard output and standard error are all redirected (see [GH-166]).
- `mdcat` no longer requires `kitty icat` to detect the size of kitty windows (see [GH-166]).
Consequently mdcat can now show images on Kitty terminals even over SSH.

[kitty-0.19]: https://sw.kovidgoyal.net/kitty/changelog.html#id2
[kitty GH-68]: https://github.com/kovidgoyal/kitty/issues/68
[`allow_hyperlinks`]: https://sw.kovidgoyal.net/kitty/conf.html?highlight=hyperlinks#opt-kitty.allow_hyperlinks
[GH-166]: https://github.com/lunaryorn/mdcat/pull/166

## [0.21.1] – 2020-09-01

Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ base64 = "^0.12"
gethostname = "^0.2"
image = "^0.23"
mime = "^0.3"
term_size = "^0.3"
url = "^2.1"
fehler = "^1"
anyhow = "^1"
Expand Down Expand Up @@ -50,6 +49,12 @@ version = "^4.4"
default-features = false
features = ["parsing", "assets", "dump-load", "regex-fancy"]

[target.'cfg(unix)'.dependencies]
libc = "^0.2"

[target.'cfg(windows)'.dependencies]
term_size = "^0.3"

[dev-dependencies]
pretty_assertions = "^0.6"
goldenfile = "^1.1"
Expand Down
7 changes: 2 additions & 5 deletions src/bin/mdcat/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl Arguments {

fn main() {
let size = TerminalSize::detect().unwrap_or_default();
let columns = size.width.to_string();
let columns = size.columns.to_string();

let matches = args::app(&columns).get_matches();
let arguments = Arguments::from_matches(&matches).unwrap_or_else(|e| e.exit());
Expand All @@ -166,10 +166,7 @@ fn main() {
Ok(mut output) => {
let settings = Settings {
terminal_capabilities,
terminal_size: TerminalSize {
width: columns,
..size
},
terminal_size: TerminalSize { columns, ..size },
resource_access,
syntax_set: SyntaxSet::load_defaults_newlines(),
};
Expand Down
18 changes: 11 additions & 7 deletions src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use std::io::prelude::*;

use ansi_term::{Colour, Style};
use anyhow::anyhow;
use fehler::throws;
use pulldown_cmark::Event::*;
use pulldown_cmark::Tag::*;
Expand Down Expand Up @@ -97,7 +98,7 @@ pub fn write_event<'a, W: Write>(
write_rule(
writer,
&settings.terminal_capabilities,
settings.terminal_size.width,
settings.terminal_size.columns,
)?;
writeln!(writer)?;
TopLevel(TopLevelAttrs::margin_before()).and_data(data)
Expand Down Expand Up @@ -172,7 +173,7 @@ pub fn write_event<'a, W: Write>(
write_rule(
writer,
&settings.terminal_capabilities,
settings.terminal_size.width - (attrs.indent as usize),
settings.terminal_size.columns - (attrs.indent as usize),
)?;
writeln!(writer)?;
stack
Expand Down Expand Up @@ -291,7 +292,7 @@ pub fn write_event<'a, W: Write>(
write_rule(
writer,
&settings.terminal_capabilities,
settings.terminal_size.width - (attrs.indent as usize),
settings.terminal_size.columns - (attrs.indent as usize),
)?;
writeln!(writer)?;
stack
Expand Down Expand Up @@ -588,10 +589,13 @@ pub fn write_event<'a, W: Write>(
})
.map(|_| RenderedImage)
.ok(),
(Some(Kitty(kitty)), Some(ref url)) => kitty
.read_and_render(url, settings.resource_access)
.and_then(|contents| {
kitty.write_inline_image(writer, contents)?;
(Some(Kitty(kitty)), Some(ref url)) => settings
.terminal_size
.pixels
.ok_or_else(|| anyhow!("Terminal pixel size not available"))
.and_then(|size| {
let image = kitty.read_and_render(url, settings.resource_access, size)?;
kitty.write_inline_image(writer, image)?;
Ok(RenderedImage)
})
.ok(),
Expand Down
2 changes: 1 addition & 1 deletion src/render/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub fn write_border<W: Write>(
capabilities: &TerminalCapabilities,
terminal_size: &TerminalSize,
) -> std::io::Result<()> {
let separator = "\u{2500}".repeat(terminal_size.width.min(20));
let separator = "\u{2500}".repeat(terminal_size.columns.min(20));
let style = Style::new().fg(Colour::Green);
write_styled(writer, capabilities, &style, separator)?;
writeln!(writer)
Expand Down
121 changes: 26 additions & 95 deletions src/terminal/kitty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@

use crate::resources::read_url;
use crate::svg::render_svg;
use crate::terminal::size::PixelSize;
use crate::{magic, ResourceAccess};
use anyhow::{anyhow, Context, Error, Result};
use anyhow::{Context, Error};
use fehler::throws;
use image::imageops::FilterType;
use image::ColorType;
use image::{DynamicImage, GenericImageView};
use std::io::Write;
use std::process::{Command, Stdio};
use std::str;
use url::Url;

Expand All @@ -39,56 +39,6 @@ pub fn is_kitty() -> bool {
.unwrap_or(false)
}

/// Retrieve the terminal size in pixels by calling the command-line tool `kitty`.
///
/// ```console
/// $ kitty +kitten icat --print-window-size
/// ```
///
/// We cannot use the terminal size information from Context.output.size, because
/// the size information are in columns / rows instead of pixel.
fn get_terminal_size() -> Result<KittyDimension> {
let process = Command::new("kitty")
.arg("+kitten")
.arg("icat")
.arg("--print-window-size")
.stdout(Stdio::piped())
.spawn()
.with_context(|| "Failed to spawn kitty +kitten icat --print-window-size")?;

let output = process.wait_with_output()?;

if output.status.success() {
let terminal_size_str = std::str::from_utf8(&output.stdout).with_context(|| {
format!(
"kitty +kitten icat --print-window-size returned non-utf8: {:?}",
output.stdout
)
})?;
let terminal_size = terminal_size_str.split('x').collect::<Vec<&str>>();

terminal_size[0]
.parse::<u32>()
.and_then(|width| {
terminal_size[1]
.parse::<u32>()
.map(|height| KittyDimension { width, height })
})
.with_context(|| {
format!(
"Failed to parse kitty width and height from output: {}",
terminal_size_str
)
})
} else {
Err(anyhow!(
"kitty +kitten icat --print-window-size failed with status {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
))
}
}

/// Provides access to printing images for kitty.
#[derive(Debug, Copy, Clone)]
pub struct KittyImages;
Expand Down Expand Up @@ -134,9 +84,9 @@ impl KittyImages {
format!("f={}", image.format.control_data_value()),
];

if let Some(dimension) = image.dimension {
cmd_header.push(format!("s={}", dimension.width));
cmd_header.push(format!("v={}", dimension.height));
if let Some(size) = image.size {
cmd_header.push(format!("s={}", size.x));
cmd_header.push(format!("v={}", size.y));
}

let image_data = base64::encode(&image.contents);
Expand All @@ -163,9 +113,16 @@ impl KittyImages {
}

/// Read the image bytes from the given URL and wrap them in a `KittyImage`.
/// It scales the image down, if the image size exceeds the terminal window size.
///
/// If the image size exceeds `terminal_size` in either dimension scale the
/// image down to `terminal_size` (preserving aspect ratio).
#[throws]
pub fn read_and_render(self, url: &Url, access: ResourceAccess) -> KittyImage {
pub fn read_and_render(
self,
url: &Url,
access: ResourceAccess,
terminal_size: PixelSize,
) -> KittyImage {
let contents = read_url(url, access)?;
let mime = magic::detect_mime_type(&contents)
.with_context(|| format!("Failed to detect mime type for URL {}", url))?;
Expand All @@ -179,9 +136,8 @@ impl KittyImages {
image::load_from_memory(&contents)
.with_context(|| format!("Failed to load image from URL {}", url))?
};
let terminal_size = get_terminal_size()?;

if magic::is_png(&mime) && terminal_size.contains(&image.dimensions().into()) {
if magic::is_png(&mime) && PixelSize::from_xy(image.dimensions()) <= terminal_size {
self.render_as_png(contents)
} else {
self.render_as_rgb_or_rgba(image, terminal_size)
Expand All @@ -193,17 +149,15 @@ impl KittyImages {
KittyImage {
contents,
format: KittyFormat::PNG,
dimension: None,
size: None,
}
}

/// Render the image as RGB/RGBA format and wrap the image bytes in `KittyImage`.
/// It scales the image down if its size exceeds the terminal size.
fn render_as_rgb_or_rgba(
self,
image: DynamicImage,
terminal_size: KittyDimension,
) -> KittyImage {
///
/// If the image size exceeds `terminal_size` in either dimension scale the
/// image down to `terminal_size` (preserving aspect ratio).
fn render_as_rgb_or_rgba(self, image: DynamicImage, terminal_size: PixelSize) -> KittyImage {
let format = match image.color() {
ColorType::L8
| ColorType::Rgb8
Expand All @@ -217,25 +171,25 @@ impl KittyImages {
_ => KittyFormat::RGBA,
};

let image = if terminal_size.contains(&KittyDimension::from(image.dimensions())) {
let image = if PixelSize::from_xy(image.dimensions()) <= terminal_size {
image
} else {
image.resize(
terminal_size.width,
terminal_size.height,
terminal_size.x as u32,
terminal_size.y as u32,
FilterType::Nearest,
)
};

let image_dimension = image.dimensions().into();
let size = PixelSize::from_xy(image.dimensions());

KittyImage {
contents: match format {
KittyFormat::RGB => image.into_rgb().into_raw(),
_ => image.into_rgba().into_raw(),
},
format,
dimension: Some(image_dimension),
size: Some(size),
}
}
}
Expand All @@ -244,7 +198,7 @@ impl KittyImages {
pub struct KittyImage {
contents: Vec<u8>,
format: KittyFormat,
dimension: Option<KittyDimension>,
size: Option<PixelSize>,
}

/// The image format (PNG, RGB or RGBA) of the image bytes.
Expand All @@ -267,26 +221,3 @@ impl KittyFormat {
}
}
}

/// The dimension encapsulate the width and height in the pixel unit.
struct KittyDimension {
width: u32,
height: u32,
}

impl KittyDimension {
/// Check whether this dimension entirely contains the specified dimension.
fn contains(&self, other: &KittyDimension) -> bool {
self.width >= other.width && self.height >= other.height
}
}

impl From<(u32, u32)> for KittyDimension {
/// Convert a tuple struct (`u32`, `u32`) ordered by width and height
/// into a `KittyDimension`.
fn from(dimension: (u32, u32)) -> KittyDimension {
let (width, height) = dimension;

KittyDimension { width, height }
}
}
2 changes: 1 addition & 1 deletion src/terminal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ mod osc;
mod terminology;

pub use self::ansi::AnsiStyle;
pub use self::size::Size as TerminalSize;
pub use self::size::TerminalSize;

/// The capability of basic styling.
#[derive(Debug, Copy, Clone)]
Expand Down
Loading