943 lines · 33.0 KB · Rust
RawDownload
use crate::fallback_themes::zed_default_dark;use crate::{    Appearance, IconTheme, IconThemeNotFoundError, SyntaxTheme, Theme, ThemeNotFoundError,    ThemeRegistry, ThemeStyleContent, DEFAULT_ICON_THEME_NAME,};use anyhow::Result;use derive_more::{Deref, DerefMut};use gpui::{    px, App, Context, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Global, Pixels,    Subscription, Window,};use refineable::Refineable;use schemars::{    gen::SchemaGenerator,    schema::{InstanceType, Schema, SchemaObject},    JsonSchema,};use serde::{Deserialize, Serialize};use serde_json::Value;use settings::{add_references_to_properties, Settings, SettingsJsonSchemaParams, SettingsSources};use std::sync::Arc;use util::ResultExt as _; const MIN_FONT_SIZE: Pixels = px(6.0);const MIN_LINE_HEIGHT: f32 = 1.0; #[derive(    Debug,    Default,    PartialEq,    Eq,    PartialOrd,    Ord,    Hash,    Clone,    Copy,    Serialize,    Deserialize,    JsonSchema,)] /// Specifies the density of the UI./// Note: This setting is still experimental. See [this tracking issue](https://github.com/zed-industries/zed/issues/18078)#[serde(rename_all = "snake_case")]pub enum UiDensity {    /// A denser UI with tighter spacing and smaller elements.    #[serde(alias = "compact")]    Compact,    #[default]    #[serde(alias = "default")]    /// The default UI density.    Default,    #[serde(alias = "comfortable")]    /// A looser UI with more spacing and larger elements.    Comfortable,} impl UiDensity {    /// The spacing ratio of a given density.    /// TODO: Standardize usage throughout the app or remove    pub fn spacing_ratio(self) -> f32 {        match self {            UiDensity::Compact => 0.75,            UiDensity::Default => 1.0,            UiDensity::Comfortable => 1.25,        }    }} impl From<String> for UiDensity {    fn from(s: String) -> Self {        match s.as_str() {            "compact" => Self::Compact,            "default" => Self::Default,            "comfortable" => Self::Comfortable,            _ => Self::default(),        }    }} impl From<UiDensity> for String {    fn from(val: UiDensity) -> Self {        match val {            UiDensity::Compact => "compact".to_string(),            UiDensity::Default => "default".to_string(),            UiDensity::Comfortable => "comfortable".to_string(),        }    }} /// Customizable settings for the UI and theme system.#[derive(Clone, PartialEq)]pub struct ThemeSettings {    /// The UI font size. Determines the size of text in the UI,    /// as well as the size of a [gpui::Rems] unit.    ///    /// Changing this will impact the size of all UI elements.    ui_font_size: Pixels,    /// The font used for UI elements.    pub ui_font: Font,    /// The font size used for buffers, and the terminal.    ///    /// The terminal font size can be overridden using it's own setting.    buffer_font_size: Pixels,    /// The font used for buffers, and the terminal.    ///    /// The terminal font family can be overridden using it's own setting.    pub buffer_font: Font,    /// The line height for buffers, and the terminal.    ///    /// Changing this may affect the spacing of some UI elements.    ///    /// The terminal font family can be overridden using it's own setting.    pub buffer_line_height: BufferLineHeight,    /// The current theme selection.    pub theme_selection: Option<ThemeSelection>,    /// The active theme.    pub active_theme: Arc<Theme>,    /// Manual overrides for the active theme.    ///    /// Note: This setting is still experimental. See [this tracking issue](https://github.com/zed-industries/zed/issues/18078)    pub theme_overrides: Option<ThemeStyleContent>,    /// The current icon theme selection.    pub icon_theme_selection: Option<IconThemeSelection>,    /// The active icon theme.    pub active_icon_theme: Arc<IconTheme>,    /// The density of the UI.    /// Note: This setting is still experimental. See [this tracking issue](    pub ui_density: UiDensity,    /// The amount of fading applied to unnecessary code.    pub unnecessary_code_fade: f32,} impl ThemeSettings {    const DEFAULT_LIGHT_THEME: &'static str = "One Light";    const DEFAULT_DARK_THEME: &'static str = "One Dark";     /// Returns the name of the default theme for the given [`Appearance`].    pub fn default_theme(appearance: Appearance) -> &'static str {        match appearance {            Appearance::Light => Self::DEFAULT_LIGHT_THEME,            Appearance::Dark => Self::DEFAULT_DARK_THEME,        }    }     /// Reloads the current theme.    ///    /// Reads the [`ThemeSettings`] to know which theme should be loaded,    /// taking into account the current [`SystemAppearance`].    pub fn reload_current_theme(cx: &mut App) {        let mut theme_settings = ThemeSettings::get_global(cx).clone();        let system_appearance = SystemAppearance::global(cx);         if let Some(theme_selection) = theme_settings.theme_selection.clone() {            let mut theme_name = theme_selection.theme(*system_appearance);             // If the selected theme doesn't exist, fall back to a default theme            // based on the system appearance.            let theme_registry = ThemeRegistry::global(cx);            if let Err(err @ ThemeNotFoundError(_)) = theme_registry.get(theme_name) {                if theme_registry.extensions_loaded() {                    log::error!("{err}");                }                 theme_name = Self::default_theme(*system_appearance);            };             if let Some(_theme) = theme_settings.switch_theme(theme_name, cx) {                ThemeSettings::override_global(theme_settings, cx);            }        }    }     /// Reloads the current icon theme.    ///    /// Reads the [`ThemeSettings`] to know which icon theme should be loaded,    /// taking into account the current [`SystemAppearance`].    pub fn reload_current_icon_theme(cx: &mut App) {        let mut theme_settings = ThemeSettings::get_global(cx).clone();        let system_appearance = SystemAppearance::global(cx);         if let Some(icon_theme_selection) = theme_settings.icon_theme_selection.clone() {            let mut icon_theme_name = icon_theme_selection.icon_theme(*system_appearance);             // If the selected icon theme doesn't exist, fall back to the default theme.            let theme_registry = ThemeRegistry::global(cx);            if let Err(err @ IconThemeNotFoundError(_)) =                theme_registry.get_icon_theme(icon_theme_name)            {                if theme_registry.extensions_loaded() {                    log::error!("{err}");                }                 icon_theme_name = DEFAULT_ICON_THEME_NAME;            };             if let Some(_theme) = theme_settings.switch_icon_theme(icon_theme_name, cx) {                ThemeSettings::override_global(theme_settings, cx);            }        }    }} /// The appearance of the system.#[derive(Debug, Clone, Copy, Deref)]pub struct SystemAppearance(pub Appearance); impl Default for SystemAppearance {    fn default() -> Self {        Self(Appearance::Dark)    }} #[derive(Deref, DerefMut, Default)]struct GlobalSystemAppearance(SystemAppearance); impl Global for GlobalSystemAppearance {} impl SystemAppearance {    /// Initializes the [`SystemAppearance`] for the application.    pub fn init(cx: &mut App) {        *cx.default_global::<GlobalSystemAppearance>() =            GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));    }     /// Returns the global [`SystemAppearance`].    ///    /// Inserts a default [`SystemAppearance`] if one does not yet exist.    pub(crate) fn default_global(cx: &mut App) -> Self {        cx.default_global::<GlobalSystemAppearance>().0    }     /// Returns the global [`SystemAppearance`].    pub fn global(cx: &App) -> Self {        cx.global::<GlobalSystemAppearance>().0    }     /// Returns a mutable reference to the global [`SystemAppearance`].    pub fn global_mut(cx: &mut App) -> &mut Self {        cx.global_mut::<GlobalSystemAppearance>()    }} #[derive(Default)]struct BufferFontSize(Pixels); impl Global for BufferFontSize {} #[derive(Default)]pub(crate) struct UiFontSize(Pixels); impl Global for UiFontSize {} /// Represents the selection of a theme, which can be either static or dynamic.#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]#[serde(untagged)]pub enum ThemeSelection {    /// A static theme selection, represented by a single theme name.    Static(#[schemars(schema_with = "theme_name_ref")] String),    /// A dynamic theme selection, which can change based the [ThemeMode].    Dynamic {        /// The mode used to determine which theme to use.        #[serde(default)]        mode: ThemeMode,        /// The theme to use for light mode.        #[schemars(schema_with = "theme_name_ref")]        light: String,        /// The theme to use for dark mode.        #[schemars(schema_with = "theme_name_ref")]        dark: String,    },} fn theme_name_ref(_: &mut SchemaGenerator) -> Schema {    Schema::new_ref("#/definitions/ThemeName".into())} // TODO: Rename ThemeMode -> ThemeAppearanceMode/// The mode use to select a theme.////// `Light` and `Dark` will select their respective themes.////// `System` will select the theme based on the system's appearance.#[derive(Debug, PartialEq, Eq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum ThemeMode {    /// Use the specified `light` theme.    Light,     /// Use the specified `dark` theme.    Dark,     /// Use the theme based on the system's appearance.    #[default]    System,} impl ThemeSelection {    /// Returns the theme name for the selected [ThemeMode].    pub fn theme(&self, system_appearance: Appearance) -> &str {        match self {            Self::Static(theme) => theme,            Self::Dynamic { mode, light, dark } => match mode {                ThemeMode::Light => light,                ThemeMode::Dark => dark,                ThemeMode::System => match system_appearance {                    Appearance::Light => light,                    Appearance::Dark => dark,                },            },        }    }     /// Returns the [ThemeMode] for the [ThemeSelection].    pub fn mode(&self) -> Option<ThemeMode> {        match self {            ThemeSelection::Static(_) => None,            ThemeSelection::Dynamic { mode, .. } => Some(*mode),        }    }} fn icon_theme_name_ref(_: &mut SchemaGenerator) -> Schema {    Schema::new_ref("#/definitions/IconThemeName".into())} /// Represents the selection of an icon theme, which can be either static or dynamic.#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]#[serde(untagged)]pub enum IconThemeSelection {    /// A static icon theme selection, represented by a single icon theme name.    Static(#[schemars(schema_with = "icon_theme_name_ref")] String),    /// A dynamic icon theme selection, which can change based on the [`ThemeMode`].    Dynamic {        /// The mode used to determine which theme to use.        #[serde(default)]        mode: ThemeMode,        /// The icon theme to use for light mode.        #[schemars(schema_with = "icon_theme_name_ref")]        light: String,        /// The icon theme to use for dark mode.        #[schemars(schema_with = "icon_theme_name_ref")]        dark: String,    },} impl IconThemeSelection {    /// Returns the icon theme name based on the given [`Appearance`].    pub fn icon_theme(&self, system_appearance: Appearance) -> &str {        match self {            Self::Static(theme) => theme,            Self::Dynamic { mode, light, dark } => match mode {                ThemeMode::Light => light,                ThemeMode::Dark => dark,                ThemeMode::System => match system_appearance {                    Appearance::Light => light,                    Appearance::Dark => dark,                },            },        }    }     /// Returns the [`ThemeMode`] for the [`IconThemeSelection`].    pub fn mode(&self) -> Option<ThemeMode> {        match self {            IconThemeSelection::Static(_) => None,            IconThemeSelection::Dynamic { mode, .. } => Some(*mode),        }    }} /// Settings for rendering text in UI and text buffers.#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]pub struct ThemeSettingsContent {    /// The default font size for text in the UI.    #[serde(default)]    pub ui_font_size: Option<f32>,    /// The name of a font to use for rendering in the UI.    #[serde(default)]    pub ui_font_family: Option<String>,    /// The font fallbacks to use for rendering in the UI.    #[serde(default)]    #[schemars(default = "default_font_fallbacks")]    pub ui_font_fallbacks: Option<Vec<String>>,    /// The OpenType features to enable for text in the UI.    #[serde(default)]    #[schemars(default = "default_font_features")]    pub ui_font_features: Option<FontFeatures>,    /// The weight of the UI font in CSS units from 100 to 900.    #[serde(default)]    pub ui_font_weight: Option<f32>,    /// The name of a font to use for rendering in text buffers.    #[serde(default)]    pub buffer_font_family: Option<String>,    /// The font fallbacks to use for rendering in text buffers.    #[serde(default)]    #[schemars(default = "default_font_fallbacks")]    pub buffer_font_fallbacks: Option<Vec<String>>,    /// The default font size for rendering in text buffers.    #[serde(default)]    pub buffer_font_size: Option<f32>,    /// The weight of the editor font in CSS units from 100 to 900.    #[serde(default)]    pub buffer_font_weight: Option<f32>,    /// The buffer's line height.    #[serde(default)]    pub buffer_line_height: Option<BufferLineHeight>,    /// The OpenType features to enable for rendering in text buffers.    #[serde(default)]    #[schemars(default = "default_font_features")]    pub buffer_font_features: Option<FontFeatures>,    /// The name of the Zed theme to use.    #[serde(default)]    pub theme: Option<ThemeSelection>,    /// The name of the icon theme to use.    #[serde(default)]    pub icon_theme: Option<IconThemeSelection>,     /// UNSTABLE: Expect many elements to be broken.    ///    // Controls the density of the UI.    #[serde(rename = "unstable.ui_density", default)]    pub ui_density: Option<UiDensity>,     /// How much to fade out unused code.    #[serde(default)]    pub unnecessary_code_fade: Option<f32>,     /// EXPERIMENTAL: Overrides for the current theme.    ///    /// These values will override the ones on the current theme specified in `theme`.    #[serde(rename = "experimental.theme_overrides", default)]    pub theme_overrides: Option<ThemeStyleContent>,} fn default_font_features() -> Option<FontFeatures> {    Some(FontFeatures::default())} fn default_font_fallbacks() -> Option<FontFallbacks> {    Some(FontFallbacks::default())} impl ThemeSettingsContent {    /// Sets the theme for the given appearance to the theme with the specified name.    pub fn set_theme(&mut self, theme_name: String, appearance: Appearance) {        if let Some(selection) = self.theme.as_mut() {            let theme_to_update = match selection {                ThemeSelection::Static(theme) => theme,                ThemeSelection::Dynamic { mode, light, dark } => match mode {                    ThemeMode::Light => light,                    ThemeMode::Dark => dark,                    ThemeMode::System => match appearance {                        Appearance::Light => light,                        Appearance::Dark => dark,                    },                },            };             *theme_to_update = theme_name.to_string();        } else {            self.theme = Some(ThemeSelection::Static(theme_name.to_string()));        }    }     /// Sets the icon theme for the given appearance to the icon theme with the specified name.    pub fn set_icon_theme(&mut self, icon_theme_name: String, appearance: Appearance) {        if let Some(selection) = self.icon_theme.as_mut() {            let icon_theme_to_update = match selection {                IconThemeSelection::Static(theme) => theme,                IconThemeSelection::Dynamic { mode, light, dark } => match mode {                    ThemeMode::Light => light,                    ThemeMode::Dark => dark,                    ThemeMode::System => match appearance {                        Appearance::Light => light,                        Appearance::Dark => dark,                    },                },            };             *icon_theme_to_update = icon_theme_name.to_string();        } else {            self.icon_theme = Some(IconThemeSelection::Static(icon_theme_name.to_string()));        }    }     /// Sets the mode for the theme.    pub fn set_mode(&mut self, mode: ThemeMode) {        if let Some(selection) = self.theme.as_mut() {            match selection {                ThemeSelection::Static(theme) => {                    // If the theme was previously set to a single static theme,                    // we don't know whether it was a light or dark theme, so we                    // just use it for both.                    self.theme = Some(ThemeSelection::Dynamic {                        mode,                        light: theme.clone(),                        dark: theme.clone(),                    });                }

Lines 1–500 of 943.