Support taking any Display in SetTitle (#528)

This commit is contained in:
Koxiaet 2020-12-30 17:50:44 +00:00 committed by GitHub
parent e7ea585e7c
commit 6a1114b241
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 8 deletions

View File

@ -338,16 +338,16 @@ impl Command for SetSize {
///
/// Commands must be executed/queued for execution otherwise they do nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SetTitle<'a>(pub &'a str);
pub struct SetTitle<T>(pub T);
impl<'a> Command for SetTitle<'a> {
impl<T: fmt::Display> Command for SetTitle<T> {
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
ansi::set_title_ansi_sequence(f, self.0)
ansi::set_title_ansi_sequence(f, &self.0)
}
#[cfg(windows)]
fn execute_winapi(&self, _writer: impl FnMut() -> Result<()>) -> Result<()> {
sys::set_window_title(self.0)
sys::set_window_title(&self.0)
}
}

View File

@ -30,6 +30,9 @@ pub(crate) fn set_size_csi_sequence(
write!(f, csi!("8;{};{}t"), height, width)
}
pub(crate) fn set_title_ansi_sequence(f: &mut impl fmt::Write, title: &str) -> fmt::Result {
pub(crate) fn set_title_ansi_sequence(
f: &mut impl fmt::Write,
title: impl fmt::Display,
) -> fmt::Result {
write!(f, "\x1B]0;{}\x07", title)
}

View File

@ -1,4 +1,7 @@
//! WinAPI related logic for terminal manipulation.
use std::fmt::{self, Write};
use crossterm_winapi::{Console, ConsoleMode, Coord, Handle, ScreenBuffer, Size};
use winapi::{
shared::minwindef::DWORD,
@ -190,9 +193,20 @@ pub(crate) fn set_size(width: u16, height: u16) -> Result<()> {
Ok(())
}
pub(crate) fn set_window_title(title: &str) -> Result<()> {
let mut title: Vec<_> = title.encode_utf16().collect();
title.push(0);
pub(crate) fn set_window_title(title: impl fmt::Display) -> Result<()> {
struct Utf16Encoder(Vec<u16>);
impl Write for Utf16Encoder {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend(s.encode_utf16());
Ok(())
}
}
let mut title_utf16 = Utf16Encoder(Vec::new());
write!(title_utf16, "{}", title).expect("formatting failed");
title_utf16.0.push(0);
let title = title_utf16.0;
let result = unsafe { SetConsoleTitleW(title.as_ptr()) };
if result != 0 {
Ok(())