use crate::{
AppExt as _, Appearance, paint,
theme::{Theme, layout},
};
use gpui::{App, Global};
use std::{cell::Cell, rc::Rc};
impl Theme {
pub fn install(appearance: Appearance, cx: &mut App) {
let theme = Self::from_palette(appearance, cx);
let brand = cx.brand();
layout::set_base_radius(brand.radius);
Self::install_custom(theme, cx);
}
pub fn install_custom(theme: Theme, cx: &mut App) {
paint::set_current_appearance(theme.appearance);
paint::bump_generation();
cx.set_global(theme);
cx.refresh_windows();
}
pub fn of(cx: &App) -> &Theme {
if let Some(scope) = cx.try_global::<ContentThemes>() {
match scope.active.get() {
Some(Appearance::Light) => return &scope.light,
Some(Appearance::Dark) => return &scope.dark,
None => {}
}
}
cx.global::<Theme>()
}
fn from_palette(appearance: Appearance, cx: &App) -> Self {
let mut theme = match cx.try_global::<Palette>() {
Some(palette) => (palette.0)(appearance),
None => Self::for_appearance(appearance),
};
cx.brand().apply(&mut theme);
theme
}
pub fn with_appearance<R>(
appearance: Appearance,
cx: &mut App,
build: impl FnOnce(&mut App) -> R,
) -> R {
if Self::of(cx).appearance == appearance {
return build(cx);
}
let revision = paint::palette_revision();
if cx
.try_global::<ContentThemes>()
.is_none_or(|themes| themes.revision != revision)
{
let light = Self::from_palette(Appearance::Light, cx);
let dark = Self::from_palette(Appearance::Dark, cx);
if cx.has_global::<ContentThemes>() {
let themes = cx.global_mut::<ContentThemes>();
themes.light = light;
themes.dark = dark;
themes.revision = revision;
} else {
cx.set_global(ContentThemes {
light,
dark,
revision,
active: Rc::new(Cell::new(None)),
});
}
}
let active = cx.global::<ContentThemes>().active.clone();
let previous = active.replace(Some(appearance));
let _scope = ContentScope {
active,
previous,
_paint: paint::AppearanceScope::new(appearance),
};
build(cx)
}
}
struct ContentThemes {
light: Theme,
dark: Theme,
revision: u32,
active: Rc<Cell<Option<Appearance>>>,
}
impl Global for ContentThemes {}
struct ContentScope {
active: Rc<Cell<Option<Appearance>>>,
previous: Option<Appearance>,
_paint: paint::AppearanceScope,
}
impl Drop for ContentScope {
fn drop(&mut self) {
self.active.set(self.previous);
}
}
struct Palette(Box<dyn Fn(Appearance) -> Theme>);
impl Global for Palette {}
pub(crate) fn set_palette(build: impl Fn(Appearance) -> Theme + 'static, cx: &mut App) {
cx.set_global(Palette(Box::new(build)));
}