use vtcode_commons::ansi_capabilities::{ColorScheme, detect_color_scheme};
use crate::theme::color_math::{contrast_ratio, relative_luminance};
use crate::theme::registry::{available_theme_suites, theme_definition, theme_suite_id};
use crate::theme::types::{DEFAULT_THEME_ID, ThemeSuite};
pub fn theme_matches_terminal_scheme(theme_id: &str) -> bool {
let scheme = detect_color_scheme();
let theme_is_light = is_light_theme(theme_id);
match scheme {
ColorScheme::Light => theme_is_light,
ColorScheme::Dark | ColorScheme::Unknown => !theme_is_light,
}
}
pub fn is_light_theme(theme_id: &str) -> bool {
theme_definition(theme_id)
.map(|theme| relative_luminance(theme.palette.background) > 0.5)
.unwrap_or(false)
}
pub fn suggest_theme_for_terminal() -> &'static str {
suggest_theme_for_scheme(!matches!(detect_color_scheme(), ColorScheme::Light))
}
fn suggest_theme_for_scheme(dark: bool) -> &'static str {
if dark { DEFAULT_THEME_ID } else { "vitesse-light" }
}
pub fn theme_for_terminal_scheme_change(current_theme_id: &str, dark: bool) -> &'static str {
if let Some(suite_id) = theme_suite_id(current_theme_id)
&& let Some(suite) = available_theme_suites().into_iter().find(|suite| suite.id == suite_id)
{
if let Some(theme_id) = suite_twin(&suite, current_theme_id, dark) {
return theme_id;
}
}
suggest_theme_for_scheme(dark)
}
fn suite_twin(suite: &ThemeSuite, current: &str, dark: bool) -> Option<&'static str> {
let qualifier = suite_qualifier(suite.id, current);
let candidates: Vec<&'static str> = suite
.theme_ids
.iter()
.copied()
.filter(|theme_id| is_light_theme(theme_id) != dark)
.collect();
if let Some(&exact) = candidates
.iter()
.find(|theme_id| suite_qualifier(suite.id, theme_id) == qualifier)
{
return Some(exact);
}
if let Some(&plain) = candidates
.iter()
.find(|theme_id| suite_qualifier(suite.id, theme_id).is_empty())
{
return Some(plain);
}
candidates
.into_iter()
.max_by(|left, right| variant_readability(left).total_cmp(&variant_readability(right)))
}
fn suite_qualifier<'a>(suite_id: &str, theme_id: &'a str) -> &'a str {
let qualifier = theme_id.strip_prefix(suite_id).unwrap_or_default().trim_start_matches('-');
if qualifier == "light" || qualifier == "dark" {
return "";
}
qualifier
.strip_prefix("light-")
.or_else(|| qualifier.strip_prefix("dark-"))
.unwrap_or(qualifier)
}
fn variant_readability(theme_id: &str) -> f32 {
theme_definition(theme_id)
.map(|theme| contrast_ratio(theme.palette.foreground, theme.palette.background))
.unwrap_or(0.0)
}