From 6a1114b2419e75bc32eb2accac346f536d46ad76 Mon Sep 17 00:00:00 2001 From: Koxiaet Date: Wed, 30 Dec 2020 17:50:44 +0000 Subject: [PATCH] Support taking any Display in SetTitle (#528) --- src/terminal.rs | 8 ++++---- src/terminal/ansi.rs | 5 ++++- src/terminal/sys/windows.rs | 20 +++++++++++++++++--- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/terminal.rs b/src/terminal.rs index 4d52112..43a6c41 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -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(pub T); -impl<'a> Command for SetTitle<'a> { +impl Command for SetTitle { 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) } } diff --git a/src/terminal/ansi.rs b/src/terminal/ansi.rs index 427509a..7e091aa 100644 --- a/src/terminal/ansi.rs +++ b/src/terminal/ansi.rs @@ -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) } diff --git a/src/terminal/sys/windows.rs b/src/terminal/sys/windows.rs index a5b04a6..483ea3f 100644 --- a/src/terminal/sys/windows.rs +++ b/src/terminal/sys/windows.rs @@ -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); + 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(())