windows: query the system caption font

Use this for the tab bar font by default
This commit is contained in:
Wez Furlong committed 2021-12-25 09:54:31 -07:00
1 parent 714e74e7af
commit a78ff883a9
5 files changed
+174 -28

No files matched your search

+24 -4
View File
@@ -382,6 +382,7 @@ struct FontConfigInner {
no_glyphs: RefCell<HashSet<char>>,
title_font: RefCell<Option<Rc<LoadedFont>>>,
fallback_channel: RefCell<Option<Sender<FallbackResolveInfo>>>,
system_title_font: RefCell<Option<(ParsedFont, f64)>>,
}
/// Matches and loads fonts for a given input style
@@ -406,6 +407,7 @@ impl FontConfigInner {
built_in: RefCell::new(Arc::new(FontDatabase::with_built_in()?)),
no_glyphs: RefCell::new(HashSet::new()),
fallback_channel: RefCell::new(None),
system_title_font: RefCell::new(None),
})
}
@@ -504,6 +506,11 @@ impl FontConfigInner {
)
}
fn advise_title_font(&self, info: Option<(ParsedFont, f64)>) {
self.title_font.borrow_mut().take();
*self.system_title_font.borrow_mut() = info;
}
fn title_font(&self, myself: &Rc<Self>) -> anyhow::Result<Rc<LoadedFont>> {
let config = self.config.borrow();
@@ -513,11 +520,18 @@ impl FontConfigInner {
return Ok(Rc::clone(entry));
}
let (sys_font, sys_size) = Self::last_ditch_title_font();
let (sys_font, mut sys_size) = Self::last_ditch_title_font();
let mut handles = vec![];
if config.window_frame.font.is_none() {
if let Some((font, size)) = self.system_title_font.borrow().as_ref() {
handles.push(font.clone());
sys_size = *size;
}
}
let font_size = config.window_frame.font_size.unwrap_or(sys_size);
let dpi = *self.dpi.borrow() as u32;
let pixel_size = (font_size * dpi as f64 / 72.0) as u16;
let text_style = config
.window_frame
@@ -525,6 +539,9 @@ impl FontConfigInner {
.as_ref()
.unwrap_or_else(|| &sys_font);
let dpi = *self.dpi.borrow() as u32;
let pixel_size = (font_size * dpi as f64 / 72.0) as u16;
let attributes = text_style.font_with_fallback();
let preferred_attributes = attributes
.iter()
@@ -538,7 +555,6 @@ impl FontConfigInner {
.collect::<Vec<_>>();
let mut loaded = HashSet::new();
let mut handles = vec![];
for attrs in &[&preferred_attributes, &fallback_attributes] {
self.font_dirs
.borrow()
@@ -850,6 +866,10 @@ impl FontConfiguration {
self.inner.resolve_font(&self.inner, style)
}
pub fn advise_title_font(&self, info: Option<(ParsedFont, f64)>) {
self.inner.advise_title_font(info);
}
pub fn change_scaling(&self, font_scale: f64, dpi: usize) -> (f64, usize) {
self.inner.change_scaling(font_scale, dpi)
}
+55 -21
View File
@@ -7,22 +7,19 @@ use dwrote::{FontDescriptor, FontStretch, FontStyle, FontWeight};
use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::Arc;
use winapi::shared::windef::HFONT;
use winapi::shared::windef::{HDC, HFONT};
use winapi::um::dwrite::*;
use winapi::um::winbase::MulDiv;
use winapi::um::wingdi::{
CreateCompatibleDC, CreateFontIndirectW, DeleteDC, DeleteObject, GetFontData, SelectObject,
FIXED_PITCH, GDI_ERROR, LF_FACESIZE, LOGFONTW, OUT_TT_ONLY_PRECIS,
CreateCompatibleDC, CreateFontIndirectW, DeleteDC, DeleteObject, GetDeviceCaps, GetFontData,
SelectObject, FIXED_PITCH, GDI_ERROR, LF_FACESIZE, LOGFONTW, LOGPIXELSY, OUT_TT_ONLY_PRECIS,
};
/// A FontLocator implemented using the system font loading
/// functions provided by the font-loader crate.
pub struct GdiFontLocator {}
fn extract_font_data(
font: HFONT,
attr: &FontAttributes,
pixel_size: u16,
) -> anyhow::Result<ParsedFont> {
fn extract_raw_font_data(font: HFONT, name: &str) -> anyhow::Result<FontDataSource> {
unsafe {
let hdc = CreateCompatibleDC(std::ptr::null_mut());
SelectObject(hdc, font as *mut _);
@@ -61,23 +58,31 @@ fn extract_font_data(
DeleteDC(hdc);
let data = data?;
let source = FontDataSource::Memory {
Ok(FontDataSource::Memory {
data: Arc::new(data.into_boxed_slice()),
name: attr.family.clone(),
};
let mut font_info = vec![];
parse_and_collect_font_info(&source, &mut font_info, FontOrigin::Gdi)?;
let matches = ParsedFont::best_match(attr, pixel_size, font_info);
for m in matches {
return Ok(m);
}
anyhow::bail!("No font matching {:?} in {:?}", attr, source);
name: name.to_string(),
})
}
}
fn extract_font_data(
font: HFONT,
attr: &FontAttributes,
pixel_size: u16,
) -> anyhow::Result<ParsedFont> {
let source = extract_raw_font_data(font, &attr.family)?;
let mut font_info = vec![];
parse_and_collect_font_info(&source, &mut font_info, FontOrigin::Gdi)?;
let matches = ParsedFont::best_match(attr, pixel_size, font_info);
for m in matches {
return Ok(m);
}
anyhow::bail!("No font matching {:?} in {:?}", attr, source);
}
/// Convert a rust string to a windows wide string
fn wide_string(s: &str) -> Vec<u16> {
use std::os::windows::ffi::OsStrExt;
@@ -124,6 +129,35 @@ fn load_font(font_attr: &FontAttributes, pixel_size: u16) -> anyhow::Result<Pars
}
}
pub fn parse_log_font(log_font: &LOGFONTW, hdc: HDC) -> anyhow::Result<(ParsedFont, f64)> {
let name = String::from_utf16(&log_font.lfFaceName)?;
unsafe {
let font = CreateFontIndirectW(log_font);
let source = extract_raw_font_data(font, &name);
DeleteObject(font as *mut _);
let source = source?;
let point_size = MulDiv(-log_font.lfHeight, 72, GetDeviceCaps(hdc, LOGPIXELSY)) as f64;
let pixel_size = log_font.lfHeight.abs() as u16;
let mut attr = FontAttributes::new(&name);
attr.weight = config::FontWeight::from_opentype_weight(log_font.lfWeight as u16);
if log_font.lfItalic == 1 {
attr.italic = true;
}
let mut font_info = vec![];
parse_and_collect_font_info(&source, &mut font_info, FontOrigin::Gdi)?;
let matches = ParsedFont::best_match(&attr, pixel_size, font_info);
for m in matches {
return Ok((m, point_size));
}
anyhow::bail!("No font matching {:?} in {:?}", attr, source);
}
}
fn attributes_to_descriptor(font_attr: &FontAttributes) -> FontDescriptor {
FontDescriptor {
family_name: font_attr.family.to_string(),
+19 -2
View File
@@ -573,10 +573,27 @@ fn reload_background_image(
impl TermWindow {
pub async fn new_window(mux_window_id: MuxWindowId) -> anyhow::Result<()> {
let config = configuration();
let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi()) as usize;
let fontconfig = Rc::new(FontConfiguration::new(Some(config.clone()), dpi)?);
// If we need the title font, it's easier to extract that information
// from a cheeky temporary invisible window and use its metrics below.
if config.use_fancy_tab_bar {
let cheeky_window = Window::new_window(
&*WINDOW_CLASS.lock().unwrap(),
"wezterm",
100,
100,
Some(&config),
Rc::clone(&fontconfig),
move |_, _| {},
)
.await?;
fontconfig.advise_title_font(cheeky_window.get_title_font_and_point_size());
cheeky_window.close();
}
let mux = Mux::get().expect("to be main thread with mux running");
let size = match mux.get_active_tab_for_window(mux_window_id) {
Some(tab) => tab.get_size(),
+4
View File
@@ -260,4 +260,8 @@ pub trait WindowOps {
/// This may not be supported or respected by the desktop
/// environment.
fn set_resize_increments(&self, _x: u16, _y: u16) {}
fn get_title_font_and_point_size(&self) -> Option<(wezterm_font::parser::ParsedFont, f64)> {
None
}
}
+72 -1
View File
@@ -27,8 +27,13 @@ use wezterm_font::FontConfiguration;
use winapi::shared::minwindef::*;
use winapi::shared::ntdef::*;
use winapi::shared::windef::*;
use winapi::shared::winerror::S_OK;
use winapi::um::imm::*;
use winapi::um::libloaderapi::GetModuleHandleW;
use winapi::um::uxtheme::{
CloseThemeData, GetThemeFont, GetThemeSysFont, OpenThemeData, SetWindowTheme,
};
use winapi::um::wingdi::LOGFONTW;
use winapi::um::winuser::*;
use winreg::{enums::HKEY_CURRENT_USER, RegKey};
@@ -706,6 +711,73 @@ impl WindowOps for Window {
fn set_clipboard(&self, _clipboard: Clipboard, text: String) {
clipboard_win::set_clipboard_string(&text).ok();
}
fn get_title_font_and_point_size(&self) -> Option<(wezterm_font::parser::ParsedFont, f64)> {
const TMT_CAPTIONFONT: i32 = 801;
const HP_HEADERITEM: i32 = 1;
const HIS_NORMAL: i32 = 1;
unsafe fn populate_log_font(hwnd: HWND, hdc: HDC) -> Option<LOGFONTW> {
let mut log_font = LOGFONTW {
lfHeight: 0,
lfWidth: 0,
lfEscapement: 0,
lfOrientation: 0,
lfWeight: 0,
lfItalic: 0,
lfUnderline: 0,
lfStrikeOut: 0,
lfCharSet: 0,
lfOutPrecision: 0,
lfClipPrecision: 0,
lfQuality: 0,
lfPitchAndFamily: 0,
lfFaceName: [0u16; 32],
};
let theme = OpenThemeData(
hwnd,
[
'H' as u16, 'E' as u16, 'A' as u16, 'D' as u16, 'E' as u16, 'R' as u16, 0u16,
]
.as_ptr(),
);
if !theme.is_null() {
let res = GetThemeFont(
theme,
hdc,
HP_HEADERITEM,
HIS_NORMAL,
TMT_CAPTIONFONT,
&mut log_font,
);
if res == S_OK {
CloseThemeData(theme);
return Some(log_font);
}
}
let res = GetThemeSysFont(theme, TMT_CAPTIONFONT, &mut log_font);
if !theme.is_null() {
CloseThemeData(theme);
}
if res == S_OK {
Some(log_font)
} else {
None
}
}
unsafe {
let hwnd = self.0 .0;
let hdc = GetDC(hwnd);
let result = match populate_log_font(hwnd, hdc) {
Some(lf) => wezterm_font::locator::gdi::parse_log_font(&lf, hdc).ok(),
None => None,
};
ReleaseDC(hwnd, hdc);
result
}
}
}
/// Set up bidirectional pointers:
@@ -772,7 +844,6 @@ fn apply_theme(hwnd: HWND) -> Option<LRESULT> {
// Note that the MS terminal app uses the logic found here for this stuff:
// https://github.com/microsoft/terminal/blob/9b92986b49bed8cc41fde4d6ef080921c41e6d9e/src/interactivity/win32/windowtheme.cpp#L62
use winapi::um::dwmapi::DwmSetWindowAttribute;
use winapi::um::uxtheme::SetWindowTheme;
#[allow(non_snake_case)]
type WINDOWCOMPOSITIONATTRIB = u32;