From 3f811ebef76e0b9ad937be34f70515fe626c21a3 Mon Sep 17 00:00:00 2001 From: pml68 Date: Mon, 24 Mar 2025 11:12:00 +0100 Subject: feat: add custom theme struct with dark and light variants --- src/main.rs | 10 +- src/theme.rs | 335 ++++++++++++++++++++++++++++++++------------------- src/types/project.rs | 46 ++----- 3 files changed, 224 insertions(+), 167 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index d5715ef..c8a60c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -104,10 +104,7 @@ impl App { let task = if let Some(path) = config.last_project.clone() { if path.exists() && path.is_file() { - Task::perform( - Project::from_path(path, config.clone()), - Message::FileOpened, - ) + Task::perform(Project::from_path(path), Message::FileOpened) } else { warning_dialog(format!( "The file {} does not exist, or isn't a file.", @@ -181,7 +178,8 @@ impl App { } Err(error) => return error_dialog(error), } - } + Err(error) => Task::future(error_dialog(error)).discard(), + }, Message::DropNewElement(name, point, _) => { return iced_drop::zones_on_point( move |zones| Message::HandleNew(name.clone(), zones), @@ -405,7 +403,7 @@ impl App { Panes::Designer => match &self.designer_page { DesignerPane::DesignerView => designer_view::view( self.project.element_tree.as_ref(), - self.project.get_theme(&self.config), + self.project.get_theme(), is_focused, ), DesignerPane::CodeView => { diff --git a/src/theme.rs b/src/theme.rs index a072714..3e6092b 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -1,12 +1,14 @@ -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use iced::Color; +use iced::theme::Base; use iced::theme::palette::Extended; +use serde::Deserialize; use crate::config::Config; -const DEFAULT_THEME_CONTENT: &str = - include_str!("../assets/themes/rose_pine.toml"); +const DARK_THEME_CONTENT: &str = include_str!("../assets/themes/dark.toml"); +const LIGHT_THEME_CONTENT: &str = include_str!("../assets/themes/light.toml"); pub fn theme_index(theme_name: &str, slice: &[iced::Theme]) -> Option { slice @@ -59,115 +61,6 @@ pub fn theme_from_str( } } -fn palette_to_string(palette: &iced::theme::Palette) -> String { - format!( - r"Palette {{ - background: color!(0x{}), - text: color!(0x{}), - primary: color!(0x{}), - success: color!(0x{}), - danger: color!(0x{}), - warning: color!(0x{}), - }}", - color_to_hex(palette.background), - color_to_hex(palette.text), - color_to_hex(palette.primary), - color_to_hex(palette.success), - color_to_hex(palette.danger), - color_to_hex(palette.warning), - ) -} - -fn extended_to_string(extended: &Extended) -> String { - format!( - r" -Extended{{background:Background{{base:Pair{{color:color!(0x{}),text:color!(0x{}),}},weak:Pair{{color:color!(0x{}),text:color!(0x{}),}},strong:Pair{{color:color!(0x{}),text:color!(0x{}),}},}},primary:Primary{{base:Pair{{color:color!(0x{}),text:color!(0x{}),}},weak:Pair{{color:color!(0x{}),text:color!(0x{}),}},strong:Pair{{color:color!(0x{}),text:color!(0x{}),}},}},secondary:Secondary{{base:Pair{{color:color!(0x{}),text:color!(0x{}),}},weak:Pair{{color:color!(0x{}),text:color!(0x{}),}},strong:Pair{{color:color!(0x{}),text:color!(0x{}),}},}},success:Success{{base:Pair{{color:color!(0x{}),text:color!(0x{}),}},weak:Pair{{color:color!(0x{}),text:color!(0x{}),}},strong:Pair{{color:color!(0x{}),text:color!(0x{}),}},}},danger:Danger{{base:Pair{{color:color!(0x{}),text:color!(0x{}),}},weak:Pair{{color:color!(0x{}),text:color!(0x{}),}},strong:Pair{{color:color!(0x{}),text:color!(0x{}),}},}},warning:Warning{{base:Pair{{color:color!(0x{}),text:color!(0x{}),}},weak:Pair{{color:color!(0x{}),text:color!(0x{}),}},strong:Pair{{color:color!(0x{}),text:color!(0x{}),}},}},is_dark:true,}}", - color_to_hex(extended.background.base.color), - color_to_hex(extended.background.base.text), - color_to_hex(extended.background.weak.color), - color_to_hex(extended.background.weak.text), - color_to_hex(extended.background.strong.color), - color_to_hex(extended.background.strong.text), - color_to_hex(extended.primary.base.color), - color_to_hex(extended.primary.base.text), - color_to_hex(extended.primary.weak.color), - color_to_hex(extended.primary.weak.text), - color_to_hex(extended.primary.strong.color), - color_to_hex(extended.primary.strong.text), - color_to_hex(extended.secondary.base.color), - color_to_hex(extended.secondary.base.text), - color_to_hex(extended.secondary.weak.color), - color_to_hex(extended.secondary.weak.text), - color_to_hex(extended.secondary.strong.color), - color_to_hex(extended.secondary.strong.text), - color_to_hex(extended.success.base.color), - color_to_hex(extended.success.base.text), - color_to_hex(extended.success.weak.color), - color_to_hex(extended.success.weak.text), - color_to_hex(extended.success.strong.color), - color_to_hex(extended.success.strong.text), - color_to_hex(extended.danger.base.color), - color_to_hex(extended.danger.base.text), - color_to_hex(extended.danger.weak.color), - color_to_hex(extended.danger.weak.text), - color_to_hex(extended.danger.strong.color), - color_to_hex(extended.danger.strong.text), - color_to_hex(extended.warning.base.color), - color_to_hex(extended.warning.base.text), - color_to_hex(extended.warning.weak.color), - color_to_hex(extended.warning.weak.text), - color_to_hex(extended.warning.strong.color), - color_to_hex(extended.warning.strong.text), - ) -} - -pub fn theme_to_string(theme: &iced::Theme) -> String { - let palette = theme.palette(); - let extended = theme.extended_palette(); - - let generated_extended = Extended::generate(palette); - - if &generated_extended == extended { - format!( - r#"custom( - "{}".to_string(), - {} - )"#, - theme, - palette_to_string(&palette) - ) - } else { - format!( - r#"custom_with_fn( - "{}".to_string(), - {}, - |_| {} - )"#, - theme, - palette_to_string(&palette), - extended_to_string(extended) - ) - } -} - -fn color_to_hex(color: Color) -> String { - use std::fmt::Write; - - let mut hex = String::with_capacity(12); - - let [r, g, b, a] = color.into_rgba8(); - - let _ = write!(&mut hex, "{:02X}", r); - let _ = write!(&mut hex, "{:02X}", g); - let _ = write!(&mut hex, "{:02X}", b); - - if a < u8::MAX { - let _ = write!(&mut hex, ", {:.2}", a as f32 / 255.0); - } - - hex -} - #[derive(Debug, Clone)] pub struct Appearance { pub selected: iced::Theme, @@ -187,7 +80,158 @@ impl Default for Appearance { } } -#[derive(Debug, serde::Deserialize)] +#[derive(Debug, PartialEq, Deserialize)] +pub struct OtherTheme { + name: String, + #[serde(flatten)] + colorscheme: ColorScheme, +} + +impl Clone for OtherTheme { + fn clone(&self) -> Self { + Self { + name: self.name.clone(), + colorscheme: self.colorscheme, + } + } + + fn clone_from(&mut self, source: &Self) { + self.name = source.name.clone(); + self.colorscheme = source.colorscheme; + } +} + +impl Default for OtherTheme { + fn default() -> Self { + match dark_light::detect().unwrap_or(dark_light::Mode::Unspecified) { + dark_light::Mode::Dark | dark_light::Mode::Unspecified => { + DARK.clone() + } + dark_light::Mode::Light => LIGHT.clone(), + } + } +} + +impl Base for OtherTheme { + fn base(&self) -> iced::theme::Style { + iced::theme::Style { + background_color: self.colorscheme.surface.surface, + text_color: self.colorscheme.surface.on_surface, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct ColorScheme { + pub primary: Primary, + pub secondary: Secondary, + pub tertiary: Tertiary, + pub error: Error, + pub surface: Surface, + pub inverse: Inverse, + pub outline: Outline, +} + +pub static DARK: LazyLock = LazyLock::new(|| { + toml::from_str(DARK_THEME_CONTENT).expect("parse dark theme") +}); + +pub static LIGHT: LazyLock = LazyLock::new(|| { + toml::from_str(LIGHT_THEME_CONTENT).expect("parse light theme") +}); + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Primary { + #[serde(with = "color_serde")] + pub primary: Color, + #[serde(with = "color_serde")] + pub on_primary: Color, + #[serde(with = "color_serde")] + pub primary_container: Color, + #[serde(with = "color_serde")] + pub on_primary_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Secondary { + #[serde(with = "color_serde")] + pub secondary: Color, + #[serde(with = "color_serde")] + pub on_secondary: Color, + #[serde(with = "color_serde")] + pub secondary_container: Color, + #[serde(with = "color_serde")] + pub on_secondary_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Tertiary { + #[serde(with = "color_serde")] + pub tertiary: Color, + #[serde(with = "color_serde")] + pub on_tertiary: Color, + #[serde(with = "color_serde")] + pub tertiary_container: Color, + #[serde(with = "color_serde")] + pub on_tertiary_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Error { + #[serde(with = "color_serde")] + pub error: Color, + #[serde(with = "color_serde")] + pub on_error: Color, + #[serde(with = "color_serde")] + pub error_container: Color, + #[serde(with = "color_serde")] + pub on_error_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Surface { + #[serde(with = "color_serde")] + pub surface: Color, + #[serde(with = "color_serde")] + pub on_surface: Color, + #[serde(with = "color_serde")] + pub on_surface_variant: Color, + pub surface_container: SurfaceContainer, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct SurfaceContainer { + #[serde(with = "color_serde")] + pub lowest: Color, + #[serde(with = "color_serde")] + pub low: Color, + #[serde(with = "color_serde")] + pub base: Color, + #[serde(with = "color_serde")] + pub high: Color, + #[serde(with = "color_serde")] + pub highest: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Inverse { + #[serde(with = "color_serde")] + pub inverse_surface: Color, + #[serde(with = "color_serde")] + pub inverse_on_surface: Color, + #[serde(with = "color_serde")] + pub inverse_primary: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Outline { + #[serde(with = "color_serde")] + pub outline: Color, + #[serde(with = "color_serde")] + pub outline_variant: Color, +} + +#[derive(Debug, Deserialize)] pub struct Theme { name: String, palette: ThemePalette, @@ -200,7 +244,7 @@ impl From for iced::Theme { fn from(value: Theme) -> Self { iced::Theme::custom_with_fn( value.name.clone(), - value.palette.clone().into(), + value.palette.into(), |_| value.into(), ) } @@ -208,11 +252,12 @@ impl From for iced::Theme { impl Default for Theme { fn default() -> Self { - toml::from_str(DEFAULT_THEME_CONTENT).expect("parse default theme") + toml::from_str(include_str!("../assets/themes/rose_pine.toml")) + .expect("parse default theme") } } -#[derive(Debug, Clone, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Deserialize)] pub struct ThemePalette { #[serde(with = "color_serde")] background: Color, @@ -341,7 +386,7 @@ impl From for Extended { } } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ExtendedThemePalette { background: Option, primary: Option, @@ -351,49 +396,49 @@ struct ExtendedThemePalette { warning: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemeBackground { base: Option, weak: Option, strong: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemePrimary { base: Option, weak: Option, strong: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemeSecondary { base: Option, weak: Option, strong: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemeSuccess { base: Option, weak: Option, strong: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemeDanger { base: Option, weak: Option, strong: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemeWarning { base: Option, weak: Option, strong: Option, } -#[derive(Debug, Default, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, Deserialize)] struct ThemePair { #[serde(with = "color_serde")] color: Color, @@ -410,16 +455,56 @@ impl From for iced::theme::palette::Pair { } } +pub fn parse_argb(s: &str) -> Option { + let hex = s.strip_prefix('#').unwrap_or(s); + + let parse_channel = |from: usize, to: usize| { + let num = + usize::from_str_radix(&hex[from..=to], 16).ok()? as f32 / 255.0; + + // If we only got half a byte (one letter), expand it into a full byte (two letters) + Some(if from == to { num + num * 16.0 } else { num }) + }; + + Some(match hex.len() { + 3 => Color::from_rgb( + parse_channel(0, 0)?, + parse_channel(1, 1)?, + parse_channel(2, 2)?, + ), + 4 => Color::from_rgba( + parse_channel(1, 1)?, + parse_channel(2, 2)?, + parse_channel(3, 3)?, + parse_channel(0, 0)?, + ), + 6 => Color::from_rgb( + parse_channel(0, 1)?, + parse_channel(2, 3)?, + parse_channel(4, 5)?, + ), + 8 => Color::from_rgba( + parse_channel(2, 3)?, + parse_channel(4, 5)?, + parse_channel(6, 7)?, + parse_channel(0, 1)?, + ), + _ => None?, + }) +} + mod color_serde { use iced::Color; use serde::{Deserialize, Deserializer}; + use super::parse_argb; + pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, { Ok(String::deserialize(deserializer) - .map(|hex| Color::parse(&hex))? + .map(|hex| parse_argb(&hex))? .unwrap_or(Color::TRANSPARENT)) } } diff --git a/src/types/project.rs b/src/types/project.rs index 721783e..50cbb69 100644 --- a/src/types/project.rs +++ b/src/types/project.rs @@ -1,24 +1,19 @@ use std::path::{Path, PathBuf}; -use std::sync::Arc; extern crate fxhash; -use fxhash::FxHashMap; use iced::Theme; use rust_format::{Edition, Formatter, RustFmt}; use serde::{Deserialize, Serialize}; use super::rendered_element::RenderedElement; use crate::Error; -use crate::config::Config; -use crate::theme::{theme_from_str, theme_index, theme_to_string}; +use crate::theme::{theme_from_str, theme_index}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Project { pub title: Option, pub theme: Option, pub element_tree: Option, - #[serde(skip)] - theme_cache: FxHashMap, } impl Default for Project { @@ -33,45 +28,24 @@ impl Project { title: None, theme: None, element_tree: None, - theme_cache: FxHashMap::default(), } } - pub fn get_theme(&self, config: &Config) -> Theme { + pub fn get_theme(&self) -> Theme { match &self.theme { - Some(theme) => theme_from_str(Some(config), theme), + Some(theme) => theme_from_str(None, theme), None => Theme::default(), } } - fn theme_code(&mut self, theme: &Theme) -> String { - let theme_name = theme.to_string(); - if theme_index(&theme_name, Theme::ALL).is_none() { - (*self - .theme_cache - .entry(theme_name) - .or_insert(theme_to_string(theme))) - .to_string() - } else { - theme_name.replace(" ", "") - } - } - - pub async fn from_path( - path: PathBuf, - config: Arc, - ) -> Result<(PathBuf, Self), Error> { + pub async fn from_path(path: PathBuf) -> Result<(PathBuf, Self), Error> { let contents = tokio::fs::read_to_string(&path).await?; - let mut project: Self = serde_json::from_str(&contents)?; - - let _ = project.theme_code(&project.get_theme(&config)); + let project: Self = serde_json::from_str(&contents)?; Ok((path, project)) } - pub async fn from_file( - config: Arc, - ) -> Result<(PathBuf, Self), Error> { + pub async fn from_file() -> Result<(PathBuf, Self), Error> { let picked_file = rfd::AsyncFileDialog::new() .set_title("Open a JSON file...") .add_filter("*.json, *.JSON", &["json", "JSON"]) @@ -81,7 +55,7 @@ impl Project { let path = picked_file.path().to_owned(); - Self::from_path(path, config).await + Self::from_path(path).await } pub async fn write_to_file( @@ -108,12 +82,12 @@ impl Project { Ok(path) } - pub fn app_code(&mut self, config: &Config) -> Result { + pub fn app_code(&mut self) -> Result { match self.element_tree { Some(ref element_tree) => { let (imports, view) = element_tree.codegen(); - let theme = self.get_theme(config); - let theme_code = self.theme_code(&theme); + let theme = self.get_theme(); + let theme_code = theme.to_string().replace(" ", ""); let mut theme_imports = ""; if theme_index(&theme.to_string(), Theme::ALL).is_none() { if theme_code.contains("Extended") { -- cgit v1.2.3 From bbc151e82b86bf2d7114f0ea05cde7e8858ba610 Mon Sep 17 00:00:00 2001 From: pml68 Date: Sun, 30 Mar 2025 20:16:48 +0200 Subject: feat: add shadow color, impl `button::Catalog` and `text::Catalog` --- assets/themes/dark.toml | 16 ++-- assets/themes/light.toml | 16 ++-- src/main.rs | 20 +++++ src/theme.rs | 21 ++++-- src/theme/button.rs | 189 +++++++++++++++++++++++++++++++++++++++++++++++ src/theme/text.rs | 50 +++++++++++++ 6 files changed, 290 insertions(+), 22 deletions(-) create mode 100644 src/theme/button.rs create mode 100644 src/theme/text.rs (limited to 'src') diff --git a/assets/themes/dark.toml b/assets/themes/dark.toml index a3bde68..3c02ce8 100644 --- a/assets/themes/dark.toml +++ b/assets/themes/dark.toml @@ -1,31 +1,33 @@ name = "Dark" +shadow = "#000000" + [primary] -primary = "#6200ee" +color = "#6200ee" on_primary = "#ffffff" primary_container = "#3700b3" on_primary_container = "#ffffff" [secondary] -secondary = "#03dac6" +color = "#03dac6" on_secondary = "#ffffff" secondary_container = "#018786" on_secondary_container = "#ffffff" [tertiary] -tertiary = "#bb86fc" +color = "#bb86fc" on_tertiary = "#000000" tertiary_container = "#6200ee" on_tertiary_container = "#000000" [error] -error = "#b00020" +color = "#b00020" on_error = "#ffffff" error_container = "#cf6679" on_error_container = "#000000" [surface] -surface = "#121212" +color = "#121212" on_surface = "#ffffff" on_surface_variant = "#b0b0b0" @@ -42,5 +44,5 @@ inverse_on_surface = "#ffffff" inverse_primary = "#bb86fc" [outline] -outline = "#737373" -outline_variant = "#aaaaaa" +color = "#737373" +variant = "#aaaaaa" diff --git a/assets/themes/light.toml b/assets/themes/light.toml index 4852b8b..2842c82 100644 --- a/assets/themes/light.toml +++ b/assets/themes/light.toml @@ -1,31 +1,33 @@ name = "Dark" +shadow = "#000000" + [primary] -primary = "#6200ee" +color = "#6200ee" on_primary = "#ffffff" primary_container = "#e1bee7" on_primary_container = "#000000" [secondary] -secondary = "#03dac6" +color = "#03dac6" on_secondary = "#ffffff" secondary_container = "#018786" on_secondary_container = "#ffffff" [tertiary] -tertiary = "#bb86fc" +color = "#bb86fc" on_tertiary = "#000000" tertiary_container = "#6200ee" on_tertiary_container = "#000000" [error] -error = "#b00020" +color = "#b00020" on_error = "#ffffff" error_container = "#cf6679" on_error_container = "#000000" [surface] -surface = "#ffffff" +color = "#ffffff" on_surface = "#000000" on_surface_variant = "#757575" @@ -42,5 +44,5 @@ inverse_on_surface = "#ffffff" inverse_primary = "#bb86fc" [outline] -outline = "#757575" -outline_variant = "#b0b0b0" +color = "#757575" +variant = "#b0b0b0" diff --git a/src/main.rs b/src/main.rs index c8a60c6..7728e63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,8 @@ use types::{ Project, }; +//pub type Element<'a, Message> = iced::Element<'a, Message, OtherTheme>; + fn main() -> Result<(), Box> { let version = std::env::args() .nth(1) @@ -58,7 +60,9 @@ fn main() -> Result<(), Box> { iced::application(App::title, App::update, App::view) .font(icon::FONT) .theme(|state| state.theme.value().clone()) + //.theme(|_| theme::LIGHT.clone()) .subscription(App::subscription) + .antialiasing(true) .run_with(move || App::new(config_load))?; Ok(()) } @@ -445,5 +449,21 @@ impl App { Animation::new(&self.theme, content) .on_update(Message::SwitchTheme) .into() + //row![ + // button("filled") + // .style(theme::button::filled) + // .on_press(Message::RefreshEditorContent), + // button("elevated") + // .style(theme::button::elevated) + // .on_press(Message::RefreshEditorContent), + // button("filled tonal") + // .style(theme::button::filled_tonal) + // .on_press(Message::RefreshEditorContent), + // button("outlined") + // .style(theme::button::outlined) + // .on_press(Message::RefreshEditorContent), + //] + //.spacing(10) + //.into() } } diff --git a/src/theme.rs b/src/theme.rs index 3e6092b..6fe844c 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -1,3 +1,6 @@ +pub mod button; +pub mod text; + use std::sync::{Arc, LazyLock}; use iced::Color; @@ -115,7 +118,7 @@ impl Default for OtherTheme { impl Base for OtherTheme { fn base(&self) -> iced::theme::Style { iced::theme::Style { - background_color: self.colorscheme.surface.surface, + background_color: self.colorscheme.surface.color, text_color: self.colorscheme.surface.on_surface, } } @@ -130,6 +133,8 @@ pub struct ColorScheme { pub surface: Surface, pub inverse: Inverse, pub outline: Outline, + #[serde(with = "color_serde")] + pub shadow: Color, } pub static DARK: LazyLock = LazyLock::new(|| { @@ -143,7 +148,7 @@ pub static LIGHT: LazyLock = LazyLock::new(|| { #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Primary { #[serde(with = "color_serde")] - pub primary: Color, + pub color: Color, #[serde(with = "color_serde")] pub on_primary: Color, #[serde(with = "color_serde")] @@ -155,7 +160,7 @@ pub struct Primary { #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Secondary { #[serde(with = "color_serde")] - pub secondary: Color, + pub color: Color, #[serde(with = "color_serde")] pub on_secondary: Color, #[serde(with = "color_serde")] @@ -167,7 +172,7 @@ pub struct Secondary { #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Tertiary { #[serde(with = "color_serde")] - pub tertiary: Color, + pub color: Color, #[serde(with = "color_serde")] pub on_tertiary: Color, #[serde(with = "color_serde")] @@ -179,7 +184,7 @@ pub struct Tertiary { #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Error { #[serde(with = "color_serde")] - pub error: Color, + pub color: Color, #[serde(with = "color_serde")] pub on_error: Color, #[serde(with = "color_serde")] @@ -191,7 +196,7 @@ pub struct Error { #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Surface { #[serde(with = "color_serde")] - pub surface: Color, + pub color: Color, #[serde(with = "color_serde")] pub on_surface: Color, #[serde(with = "color_serde")] @@ -226,9 +231,9 @@ pub struct Inverse { #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] pub struct Outline { #[serde(with = "color_serde")] - pub outline: Color, + pub color: Color, #[serde(with = "color_serde")] - pub outline_variant: Color, + pub variant: Color, } #[derive(Debug, Deserialize)] diff --git a/src/theme/button.rs b/src/theme/button.rs new file mode 100644 index 0000000..ddd2c71 --- /dev/null +++ b/src/theme/button.rs @@ -0,0 +1,189 @@ +#![allow(dead_code)] +use iced::widget::button::{Catalog, Status, Style, StyleFn}; +use iced::{Background, Border, Color, Shadow, Vector}; + +use super::OtherTheme; + +impl Catalog for OtherTheme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> Self::Class<'a> { + Box::new(default) + } + + fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { + class(self, status) + } +} + +fn default(theme: &OtherTheme, status: Status) -> Style { + filled(theme, status) +} + +fn button( + foreground: Color, + background: Color, + background_hover: Color, + disabled: Color, + shadow_color: Color, + shadow_elevation: u8, + status: Status, +) -> Style { + let border = Border { + radius: 400.0.into(), + ..Default::default() + }; + + let elevation_to_offset = |elevation: u8| { + (match elevation { + 0 => 0.0, + 1 => 1.0, + 2 => 3.0, + 3 => 6.0, + 4 => 8.0, + _ => 12.0, + } as f32) + }; + + match status { + Status::Active | Status::Pressed => Style { + background: Some(Background::Color(background)), + text_color: foreground, + border, + shadow: Shadow { + color: shadow_color, + offset: Vector { + x: 0.0, + y: elevation_to_offset(shadow_elevation), + }, + blur_radius: elevation_to_offset(shadow_elevation) + * (1.0 + + 0.4_f32.powf(elevation_to_offset(shadow_elevation))), + }, + }, + Status::Hovered => Style { + background: Some(Background::Color(background_hover)), + text_color: foreground, + border, + shadow: Shadow { + color: shadow_color, + offset: Vector { + x: 0.0, + y: elevation_to_offset(shadow_elevation + 1), + }, + blur_radius: (elevation_to_offset(shadow_elevation + 1)) + * (1.0 + + 0.4_f32 + .powf(elevation_to_offset(shadow_elevation + 1))), + }, + }, + Status::Disabled => Style { + background: Some(Background::Color(Color { + a: 0.12, + ..disabled + })), + text_color: Color { + a: 0.38, + ..disabled + }, + border, + ..Default::default() + }, + } +} + +pub fn elevated(theme: &OtherTheme, status: Status) -> Style { + let surface_colors = theme.colorscheme.surface; + + let foreground = theme.colorscheme.primary.color; + let background = surface_colors.surface_container.low; + let disabled = surface_colors.on_surface; + + let shadow_color = theme.colorscheme.shadow; + + button( + foreground, + background, + background, + disabled, + shadow_color, + 1, + status, + ) +} + +pub fn filled(theme: &OtherTheme, status: Status) -> Style { + let primary_colors = theme.colorscheme.primary; + + let foreground = primary_colors.on_primary; + let background = primary_colors.color; + let disabled = theme.colorscheme.surface.on_surface; + + let shadow_color = theme.colorscheme.shadow; + + button( + foreground, + background, + background, + disabled, + shadow_color, + 0, + status, + ) +} + +pub fn filled_tonal(theme: &OtherTheme, status: Status) -> Style { + let secondary_colors = theme.colorscheme.secondary; + + let foreground = secondary_colors.on_secondary_container; + let background = secondary_colors.secondary_container; + let disabled = theme.colorscheme.surface.on_surface; + + let shadow_color = theme.colorscheme.shadow; + + button( + foreground, + background, + background, + disabled, + shadow_color, + 0, + status, + ) +} + +pub fn outlined(theme: &OtherTheme, status: Status) -> Style { + let foreground = theme.colorscheme.primary.color; + let background = Color::TRANSPARENT; + let disabled = theme.colorscheme.surface.on_surface; + + let outline = theme.colorscheme.outline.color; + + let border = match status { + Status::Active | Status::Pressed | Status::Hovered => Border { + color: outline, + width: 1.0, + radius: 400.0.into(), + }, + Status::Disabled => Border { + color: Color { + a: 0.12, + ..disabled + }, + width: 1.0, + radius: 400.0.into(), + }, + }; + + let style = button( + foreground, + background, + background, + disabled, + Color::TRANSPARENT, + 0, + status, + ); + + Style { border, ..style } +} diff --git a/src/theme/text.rs b/src/theme/text.rs new file mode 100644 index 0000000..9cbd056 --- /dev/null +++ b/src/theme/text.rs @@ -0,0 +1,50 @@ +#![allow(dead_code)] +use iced::widget::text::{Catalog, Style, StyleFn}; + +use super::OtherTheme; + +impl Catalog for OtherTheme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> Self::Class<'a> { + Box::new(none) + } + + fn style(&self, class: &Self::Class<'_>) -> Style { + class(self) + } +} + +pub fn none(_: &OtherTheme) -> Style { + Style { color: None } +} + +pub fn primary(theme: &OtherTheme) -> Style { + Style { + color: Some(theme.colorscheme.primary.on_primary), + } +} + +pub fn secondary(theme: &OtherTheme) -> Style { + Style { + color: Some(theme.colorscheme.secondary.on_secondary), + } +} + +pub fn tertiary(theme: &OtherTheme) -> Style { + Style { + color: Some(theme.colorscheme.tertiary.on_tertiary), + } +} + +pub fn error(theme: &OtherTheme) -> Style { + Style { + color: Some(theme.colorscheme.error.on_error), + } +} + +pub fn surface(theme: &OtherTheme) -> Style { + Style { + color: Some(theme.colorscheme.surface.on_surface), + } +} -- cgit v1.2.3 From 1aeba3cbd0ae7b53ffd2c47f325864e3ec3b0210 Mon Sep 17 00:00:00 2001 From: pml68 Date: Mon, 31 Mar 2025 01:05:24 +0200 Subject: fix: merge conflict blobs [skip ci] --- src/main.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 7728e63..63e9deb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -174,15 +174,12 @@ impl App { self.editor_content.perform(action); } } - Message::RefreshEditorContent => { - match self.project.app_code(&self.config) { - Ok(code) => { - self.editor_content = - text_editor::Content::with_text(&code); - } - Err(error) => return error_dialog(error), + Message::RefreshEditorContent => match self.project.app_code() { + Ok(code) => { + self.editor_content = + text_editor::Content::with_text(&code); } - Err(error) => Task::future(error_dialog(error)).discard(), + Err(error) => return error_dialog(error), }, Message::DropNewElement(name, point, _) => { return iced_drop::zones_on_point( @@ -279,7 +276,7 @@ impl App { self.is_dirty = false; self.is_loading = true; return Task::perform( - Project::from_file(self.config.clone()), + Project::from_file(), Message::FileOpened, ) .chain(close_dialog_task); @@ -309,7 +306,7 @@ impl App { self.is_loading = true; return Task::perform( - Project::from_file(self.config.clone()), + Project::from_file(), Message::FileOpened, ); } else { -- cgit v1.2.3 From e9af14434454e8512e99612271b557789f28deeb Mon Sep 17 00:00:00 2001 From: pml68 Date: Mon, 7 Apr 2025 02:05:39 +0200 Subject: refactor: move custom theme into its separate crate --- Cargo.lock | 20 ++- Cargo.toml | 27 ++-- assets/themes/dark.toml | 48 ------- assets/themes/light.toml | 48 ------- material_theme/Cargo.toml | 40 ++++++ material_theme/assets/themes/dark.toml | 48 +++++++ material_theme/assets/themes/light.toml | 48 +++++++ material_theme/src/button.rs | 209 +++++++++++++++++++++++++++++ material_theme/src/container.rs | 173 ++++++++++++++++++++++++ material_theme/src/lib.rs | 229 ++++++++++++++++++++++++++++++++ material_theme/src/text.rs | 86 ++++++++++++ material_theme/src/utils.rs | 61 +++++++++ src/main.rs | 19 --- src/theme.rs | 162 +--------------------- src/theme/button.rs | 189 -------------------------- src/theme/text.rs | 50 ------- theme_test/Cargo.toml | 8 ++ theme_test/src/main.rs | 89 +++++++++++++ 18 files changed, 1029 insertions(+), 525 deletions(-) delete mode 100644 assets/themes/dark.toml delete mode 100644 assets/themes/light.toml create mode 100644 material_theme/Cargo.toml create mode 100644 material_theme/assets/themes/dark.toml create mode 100644 material_theme/assets/themes/light.toml create mode 100644 material_theme/src/button.rs create mode 100644 material_theme/src/container.rs create mode 100644 material_theme/src/lib.rs create mode 100644 material_theme/src/text.rs create mode 100644 material_theme/src/utils.rs delete mode 100644 src/theme/button.rs delete mode 100644 src/theme/text.rs create mode 100644 theme_test/Cargo.toml create mode 100644 theme_test/src/main.rs (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index e92c3fc..2dc8556 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1971,7 +1971,6 @@ dependencies = [ name = "iced_builder" version = "0.1.0" dependencies = [ - "dark-light", "dirs-next", "embed-resource 3.0.2", "fxhash", @@ -1981,6 +1980,7 @@ dependencies = [ "iced_dialog", "iced_drop", "iced_fontello", + "material_theme", "rfd", "rust-format", "serde", @@ -2673,6 +2673,16 @@ dependencies = [ "libc", ] +[[package]] +name = "material_theme" +version = "0.14.0-dev" +dependencies = [ + "dark-light", + "iced_widget", + "serde", + "toml", +] + [[package]] name = "maybe-rayon" version = "0.1.1" @@ -4634,6 +4644,14 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "theme_test" +version = "0.0.1" +dependencies = [ + "iced", + "material_theme", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/Cargo.toml b/Cargo.toml index 39e69af..33d3b8e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,23 +16,28 @@ debug = ["iced/debug"] [dependencies] iced.workspace = true -iced_anim = { git = "https://github.com/pml68/iced_anim", features = ["derive"] } +iced_anim.workspace = true iced_custom_highlighter = { git = "https://github.com/pml68/iced_custom_highlighter", branch = "master" } iced_drop = { path = "iced_drop" } iced_dialog = { git = "https://github.com/pml68/iced_dialog", branch = "iced/personal" } -serde = { version = "1.0.217", features = ["derive"] } -serde_json = "1.0.138" -toml = "0.8.20" -tokio = { version = "1.43", features = ["fs"] } +material_theme = { path = "material_theme" } +serde.workspace = true +serde_json = "1.0.140" +toml.workspace = true +tokio = { version = "1.42.1", features = ["fs"] } tokio-stream = { version = "0.1", features = ["fs"] } # TODO: enable tokio when it actually compiles # rfd = { version = "0.15.2", default-features = false, features = ["tokio", "xdg-portal"] } rfd = "0.15.3" rust-format = "0.3.4" fxhash = "0.2.1" -thiserror = "2.0.11" +thiserror = "2.0.12" dirs-next = "2.0.0" -dark-light = "2.0.0" + +[workspace.dependencies] +iced_anim = { version = "0.2.1", features = ["derive"] } +serde = { version = "1.0.219", features = ["derive"] } +toml = "0.8.20" [workspace.dependencies.iced] git = "https://github.com/pml68/iced" @@ -46,7 +51,7 @@ iced_fontello = "0.13.2" xdg = "2.5.2" [target.'cfg(windows)'.build-dependencies] -embed-resource = "3.0.1" +embed-resource = "3.0.2" windows_exe_info = "0.5" [profile.dev] @@ -68,7 +73,7 @@ name = "iced-builder" path = "src/main.rs" [workspace] -members = ["iced_drop"] +members = ["iced_drop", "material_theme", "theme_test"] [lints.rust] missing_debug_implementations = "deny" @@ -89,3 +94,7 @@ from_over_into = "deny" needless_borrow = "deny" new_without_default = "deny" useless_conversion = "deny" + +[patch.crates-io] +iced_anim = { git = "https://github.com/pml68/iced_anim" } +iced_widget = { git = "https://github.com/pml68/iced", branch = "feat/rehighlight-on-redraw" } diff --git a/assets/themes/dark.toml b/assets/themes/dark.toml deleted file mode 100644 index 3c02ce8..0000000 --- a/assets/themes/dark.toml +++ /dev/null @@ -1,48 +0,0 @@ -name = "Dark" - -shadow = "#000000" - -[primary] -color = "#6200ee" -on_primary = "#ffffff" -primary_container = "#3700b3" -on_primary_container = "#ffffff" - -[secondary] -color = "#03dac6" -on_secondary = "#ffffff" -secondary_container = "#018786" -on_secondary_container = "#ffffff" - -[tertiary] -color = "#bb86fc" -on_tertiary = "#000000" -tertiary_container = "#6200ee" -on_tertiary_container = "#000000" - -[error] -color = "#b00020" -on_error = "#ffffff" -error_container = "#cf6679" -on_error_container = "#000000" - -[surface] -color = "#121212" -on_surface = "#ffffff" -on_surface_variant = "#b0b0b0" - -[surface.surface_container] -lowest = "#1e1e2e" -low = "#333333" -base = "#444444" -high = "#555555" -highest = "#666666" - -[inverse] -inverse_surface = "#212121" -inverse_on_surface = "#ffffff" -inverse_primary = "#bb86fc" - -[outline] -color = "#737373" -variant = "#aaaaaa" diff --git a/assets/themes/light.toml b/assets/themes/light.toml deleted file mode 100644 index 2842c82..0000000 --- a/assets/themes/light.toml +++ /dev/null @@ -1,48 +0,0 @@ -name = "Dark" - -shadow = "#000000" - -[primary] -color = "#6200ee" -on_primary = "#ffffff" -primary_container = "#e1bee7" -on_primary_container = "#000000" - -[secondary] -color = "#03dac6" -on_secondary = "#ffffff" -secondary_container = "#018786" -on_secondary_container = "#ffffff" - -[tertiary] -color = "#bb86fc" -on_tertiary = "#000000" -tertiary_container = "#6200ee" -on_tertiary_container = "#000000" - -[error] -color = "#b00020" -on_error = "#ffffff" -error_container = "#cf6679" -on_error_container = "#000000" - -[surface] -color = "#ffffff" -on_surface = "#000000" -on_surface_variant = "#757575" - -[surface.surface_container] -lowest = "#fafafa" -low = "#eeeeee" -base = "#dddddd" -high = "#cccccc" -highest = "#bbbbbb" - -[inverse] -inverse_surface = "#121212" -inverse_on_surface = "#ffffff" -inverse_primary = "#bb86fc" - -[outline] -color = "#757575" -variant = "#b0b0b0" diff --git a/material_theme/Cargo.toml b/material_theme/Cargo.toml new file mode 100644 index 0000000..0597d78 --- /dev/null +++ b/material_theme/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "material_theme" +description = "An M3 inspired theme for `iced`" +authors = ["pml68 "] +version = "0.14.0-dev" +edition = "2024" +license = "MIT" +# readme = "README.md" +repository = "https://github.com/pml68/iced_builder" +categories = ["gui"] +keywords = ["gui", "ui", "graphics", "interface", "widgets"] +rust-version = "1.85" + +[dependencies] +iced_widget = "0.14.0-dev" +serde.workspace = true +toml.workspace = true +dark-light = "2.0.0" + +[lints.rust] +unsafe_code = "deny" +unused_results = "deny" + +[lints.clippy] +type-complexity = "allow" +semicolon_if_nothing_returned = "deny" +trivially-copy-pass-by-ref = "deny" +default_trait_access = "deny" +match-wildcard-for-single-variants = "deny" +redundant-closure-for-method-calls = "deny" +filter_map_next = "deny" +manual_let_else = "deny" +unused_async = "deny" +from_over_into = "deny" +needless_borrow = "deny" +new_without_default = "deny" +useless_conversion = "deny" + +[lints.rustdoc] +broken_intra_doc_links = "forbid" diff --git a/material_theme/assets/themes/dark.toml b/material_theme/assets/themes/dark.toml new file mode 100644 index 0000000..4d23fc8 --- /dev/null +++ b/material_theme/assets/themes/dark.toml @@ -0,0 +1,48 @@ +name = "Dark" + +shadow = "#000000" + +[primary] +color = "#9bd4a1" +on_primary = "#003916" +primary_container = "#1b5129" +on_primary_container = "#b6f1bb" + +[secondary] +color = "#b8ccb6" +on_secondary = "#233425" +secondary_container = "#394b3a" +on_secondary_container = "#d3e8d1" + +[tertiary] +color = "#a1ced7" +on_tertiary = "#00363e" +tertiary_container = "#1f4d55" +on_tertiary_container = "#bdeaf4" + +[error] +color = "#ffb4ab" +on_error = "#690005" +error_container = "#93000a" +on_error_container = "#ffdad6" + +[surface] +color = "#101510" +on_surface = "#e0e4dc" +on_surface_variant = "#c1c9be" + +[surface.surface_container] +lowest = "#0b0f0b" +low = "#181d18" +base = "#1c211c" +high = "#262b26" +highest = "#313631" + +[inverse] +inverse_surface = "#e0e4dc" +inverse_on_surface = "#2d322c" +inverse_primary = "#34693f" + +[outline] +color = "#8b9389" +variant = "#414941" diff --git a/material_theme/assets/themes/light.toml b/material_theme/assets/themes/light.toml new file mode 100644 index 0000000..5288c84 --- /dev/null +++ b/material_theme/assets/themes/light.toml @@ -0,0 +1,48 @@ +name = "Light" + +shadow = "#000000" + +[primary] +color = "#34693f" +on_primary = "#ffffff" +primary_container = "#b6f1bb" +on_primary_container = "#1b5129" + +[secondary] +color = "#516351" +on_secondary = "#ffffff" +secondary_container = "#d3e8d1" +on_secondary_container = "#394b3a" + +[tertiary] +color = "#39656d" +on_tertiary = "#ffffff" +tertiary_container = "#bdeaf4" +on_tertiary_container = "#1f4d55" + +[error] +color = "#ba1a1a" +on_error = "#ffffff" +error_container = "#ffdad6" +on_error_container = "#93000a" + +[surface] +color = "#f7fbf2" +on_surface = "#181d18" +on_surface_variant = "#414941" + +[surface.surface_container] +lowest = "#ffffff" +low = "#f1f5ed" +base = "#ebefe7" +high = "#e5e9e1" +highest = "#e0e4dc" + +[inverse] +inverse_surface = "#2d322c" +inverse_on_surface = "#eef2ea" +inverse_primary = "#9bd4a1" + +[outline] +color = "#727970" +variant = "#c1c9be" diff --git a/material_theme/src/button.rs b/material_theme/src/button.rs new file mode 100644 index 0000000..051d6c9 --- /dev/null +++ b/material_theme/src/button.rs @@ -0,0 +1,209 @@ +#![allow(dead_code)] +use iced_widget::button::{Catalog, Status, Style, StyleFn}; +use iced_widget::core::{Background, Border, Color, Shadow, Vector}; + +use crate::Theme; +use crate::utils::{elevation, mix}; + +impl Catalog for Theme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> Self::Class<'a> { + Box::new(filled) + } + + fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { + class(self, status) + } +} + +fn button( + foreground: Color, + background: Color, + tone_overlay: Color, + disabled: Color, + shadow_color: Color, + shadow_elevation: u8, + status: Status, +) -> Style { + let border = Border { + radius: 400.into(), + ..Default::default() + }; + + let active = Style { + background: Some(Background::Color(background)), + text_color: foreground, + border, + shadow: Shadow { + color: shadow_color, + offset: Vector { + x: 0.0, + y: elevation(shadow_elevation), + }, + blur_radius: elevation(shadow_elevation) + * (1.0 + 0.4_f32.powf(elevation(shadow_elevation))), + }, + }; + + match status { + Status::Active => active, + Status::Pressed => Style { + background: Some(Background::Color(mix( + background, + tone_overlay, + 0.08, + ))), + ..active + }, + Status::Hovered => Style { + background: Some(Background::Color(mix( + background, + tone_overlay, + 0.1, + ))), + text_color: foreground, + border, + shadow: Shadow { + color: shadow_color, + offset: Vector { + x: 0.0, + y: elevation(shadow_elevation + 1), + }, + blur_radius: (elevation(shadow_elevation + 1)) + * (1.0 + 0.4_f32.powf(elevation(shadow_elevation + 1))), + }, + }, + Status::Disabled => Style { + background: Some(Background::Color(Color { + a: 0.12, + ..disabled + })), + text_color: Color { + a: 0.38, + ..disabled + }, + border, + ..Default::default() + }, + } +} + +pub fn elevated(theme: &Theme, status: Status) -> Style { + let surface_colors = theme.colorscheme.surface; + + let foreground = theme.colorscheme.primary.color; + let background = surface_colors.surface_container.low; + let disabled = surface_colors.on_surface; + + let shadow_color = theme.colorscheme.shadow; + + button( + foreground, + background, + foreground, + disabled, + shadow_color, + 1, + status, + ) +} + +pub fn filled(theme: &Theme, status: Status) -> Style { + let primary_colors = theme.colorscheme.primary; + + let foreground = primary_colors.on_primary; + let background = primary_colors.color; + let disabled = theme.colorscheme.surface.on_surface; + + let shadow_color = theme.colorscheme.shadow; + + button( + foreground, + background, + foreground, + disabled, + shadow_color, + 0, + status, + ) +} + +pub fn filled_tonal(theme: &Theme, status: Status) -> Style { + let secondary_colors = theme.colorscheme.secondary; + + let foreground = secondary_colors.on_secondary_container; + let background = secondary_colors.secondary_container; + let disabled = theme.colorscheme.surface.on_surface; + let shadow_color = theme.colorscheme.shadow; + + button( + foreground, + background, + foreground, + disabled, + shadow_color, + 0, + status, + ) +} + +pub fn outlined(theme: &Theme, status: Status) -> Style { + let foreground = theme.colorscheme.primary.color; + let background = Color::TRANSPARENT; + let disabled = theme.colorscheme.surface.on_surface; + + let outline = theme.colorscheme.outline.color; + + let border = match status { + Status::Active | Status::Pressed | Status::Hovered => Border { + color: outline, + width: 1.0, + radius: 400.0.into(), + }, + Status::Disabled => Border { + color: Color { + a: 0.12, + ..disabled + }, + width: 1.0, + radius: 400.0.into(), + }, + }; + + let style = button( + foreground, + background, + foreground, + disabled, + Color::TRANSPARENT, + 0, + status, + ); + + Style { border, ..style } +} + +pub fn text(theme: &Theme, status: Status) -> Style { + let foreground = theme.colorscheme.primary.color; + let background = Color::TRANSPARENT; + let disabled = theme.colorscheme.surface.on_surface; + + let style = button( + foreground, + background, + foreground, + disabled, + Color::TRANSPARENT, + 0, + status, + ); + + match status { + Status::Hovered | Status::Pressed => style, + _ => Style { + background: None, + ..style + }, + } +} diff --git a/material_theme/src/container.rs b/material_theme/src/container.rs new file mode 100644 index 0000000..a14cfd5 --- /dev/null +++ b/material_theme/src/container.rs @@ -0,0 +1,173 @@ +use iced_widget::container::{Catalog, Style, StyleFn}; +use iced_widget::core::{Background, border}; + +use super::Theme; + +impl Catalog for Theme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> Self::Class<'a> { + Box::new(transparent) + } + + fn style(&self, class: &Self::Class<'_>) -> Style { + class(self) + } +} + +pub fn transparent(_theme: &Theme) -> Style { + Style { + border: border::rounded(4), + ..Style::default() + } +} + +pub fn primary(theme: &Theme) -> Style { + let colors = theme.colorscheme.primary; + Style { + background: Some(Background::Color(colors.color)), + text_color: Some(colors.on_primary), + border: border::rounded(4), + ..Style::default() + } +} + +pub fn primary_container(theme: &Theme) -> Style { + let colors = theme.colorscheme.primary; + Style { + background: Some(Background::Color(colors.primary_container)), + text_color: Some(colors.on_primary_container), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn secondary(theme: &Theme) -> Style { + let colors = theme.colorscheme.secondary; + Style { + background: Some(Background::Color(colors.color)), + text_color: Some(colors.on_secondary), + border: border::rounded(4), + ..Style::default() + } +} + +pub fn secondary_container(theme: &Theme) -> Style { + let colors = theme.colorscheme.secondary; + Style { + background: Some(Background::Color(colors.secondary_container)), + text_color: Some(colors.on_secondary_container), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn tertiary(theme: &Theme) -> Style { + let colors = theme.colorscheme.tertiary; + Style { + background: Some(Background::Color(colors.color)), + text_color: Some(colors.on_tertiary), + border: border::rounded(4), + ..Style::default() + } +} + +pub fn tertiary_container(theme: &Theme) -> Style { + let colors = theme.colorscheme.tertiary; + Style { + background: Some(Background::Color(colors.tertiary_container)), + text_color: Some(colors.on_tertiary_container), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn error(theme: &Theme) -> Style { + let colors = theme.colorscheme.error; + Style { + background: Some(Background::Color(colors.color)), + text_color: Some(colors.on_error), + border: border::rounded(4), + ..Style::default() + } +} + +pub fn error_container(theme: &Theme) -> Style { + let colors = theme.colorscheme.error; + Style { + background: Some(Background::Color(colors.error_container)), + text_color: Some(colors.on_error_container), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn surface(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.color)), + text_color: Some(colors.on_surface), + border: border::rounded(4), + ..Style::default() + } +} + +pub fn surface_container_lowest(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.surface_container.lowest)), + text_color: Some(colors.on_surface), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn surface_container_low(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.surface_container.low)), + text_color: Some(colors.on_surface), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn surface_container(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.surface_container.base)), + text_color: Some(colors.on_surface), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn surface_container_high(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.surface_container.high)), + text_color: Some(colors.on_surface), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn surface_container_highest(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.surface_container.highest)), + text_color: Some(colors.on_surface), + border: border::rounded(8), + ..Style::default() + } +} + +pub fn inverse_surface(theme: &Theme) -> Style { + let colors = theme.colorscheme.inverse; + Style { + background: Some(Background::Color(colors.inverse_surface)), + text_color: Some(colors.inverse_on_surface), + border: border::rounded(4), + ..Style::default() + } +} diff --git a/material_theme/src/lib.rs b/material_theme/src/lib.rs new file mode 100644 index 0000000..6641b74 --- /dev/null +++ b/material_theme/src/lib.rs @@ -0,0 +1,229 @@ +use std::sync::LazyLock; + +use iced_widget::core::Color; +use iced_widget::core::theme::{Base, Style}; +use serde::Deserialize; + +pub mod button; +pub mod container; +pub mod text; +pub mod utils; + +const DARK_THEME_CONTENT: &str = include_str!("../assets/themes/dark.toml"); +const LIGHT_THEME_CONTENT: &str = include_str!("../assets/themes/light.toml"); + +#[derive(Debug, PartialEq, Deserialize)] +pub struct Theme { + pub name: String, + #[serde(flatten)] + pub colorscheme: ColorScheme, +} + +impl Theme { + pub fn new(name: impl Into, colorscheme: ColorScheme) -> Self { + Self { + name: name.into(), + colorscheme, + } + } +} + +impl Clone for Theme { + fn clone(&self) -> Self { + Self { + name: self.name.clone(), + colorscheme: self.colorscheme, + } + } + + fn clone_from(&mut self, source: &Self) { + self.name = source.name.clone(); + self.colorscheme = source.colorscheme; + } +} + +impl Default for Theme { + fn default() -> Self { + match dark_light::detect().unwrap_or(dark_light::Mode::Unspecified) { + dark_light::Mode::Dark | dark_light::Mode::Unspecified => { + DARK.clone() + } + dark_light::Mode::Light => LIGHT.clone(), + } + } +} + +impl Base for Theme { + fn base(&self) -> Style { + Style { + background_color: self.colorscheme.surface.color, + text_color: self.colorscheme.surface.on_surface, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct ColorScheme { + pub primary: Primary, + pub secondary: Secondary, + pub tertiary: Tertiary, + pub error: Error, + pub surface: Surface, + pub inverse: Inverse, + pub outline: Outline, + #[serde(with = "color_serde")] + pub shadow: Color, +} + +pub static DARK: LazyLock = LazyLock::new(|| { + toml::from_str(DARK_THEME_CONTENT).expect("parse dark theme") +}); + +pub static LIGHT: LazyLock = LazyLock::new(|| { + toml::from_str(LIGHT_THEME_CONTENT).expect("parse light theme") +}); + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Primary { + #[serde(with = "color_serde")] + pub color: Color, + #[serde(with = "color_serde")] + pub on_primary: Color, + #[serde(with = "color_serde")] + pub primary_container: Color, + #[serde(with = "color_serde")] + pub on_primary_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Secondary { + #[serde(with = "color_serde")] + pub color: Color, + #[serde(with = "color_serde")] + pub on_secondary: Color, + #[serde(with = "color_serde")] + pub secondary_container: Color, + #[serde(with = "color_serde")] + pub on_secondary_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Tertiary { + #[serde(with = "color_serde")] + pub color: Color, + #[serde(with = "color_serde")] + pub on_tertiary: Color, + #[serde(with = "color_serde")] + pub tertiary_container: Color, + #[serde(with = "color_serde")] + pub on_tertiary_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Error { + #[serde(with = "color_serde")] + pub color: Color, + #[serde(with = "color_serde")] + pub on_error: Color, + #[serde(with = "color_serde")] + pub error_container: Color, + #[serde(with = "color_serde")] + pub on_error_container: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Surface { + #[serde(with = "color_serde")] + pub color: Color, + #[serde(with = "color_serde")] + pub on_surface: Color, + #[serde(with = "color_serde")] + pub on_surface_variant: Color, + pub surface_container: SurfaceContainer, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct SurfaceContainer { + #[serde(with = "color_serde")] + pub lowest: Color, + #[serde(with = "color_serde")] + pub low: Color, + #[serde(with = "color_serde")] + pub base: Color, + #[serde(with = "color_serde")] + pub high: Color, + #[serde(with = "color_serde")] + pub highest: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Inverse { + #[serde(with = "color_serde")] + pub inverse_surface: Color, + #[serde(with = "color_serde")] + pub inverse_on_surface: Color, + #[serde(with = "color_serde")] + pub inverse_primary: Color, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Outline { + #[serde(with = "color_serde")] + pub color: Color, + #[serde(with = "color_serde")] + pub variant: Color, +} + +pub fn parse_argb(s: &str) -> Option { + let hex = s.strip_prefix('#').unwrap_or(s); + + let parse_channel = |from: usize, to: usize| { + let num = + usize::from_str_radix(&hex[from..=to], 16).ok()? as f32 / 255.0; + + // If we only got half a byte (one letter), expand it into a full byte (two letters) + Some(if from == to { num + num * 16.0 } else { num }) + }; + + Some(match hex.len() { + 3 => Color::from_rgb( + parse_channel(0, 0)?, + parse_channel(1, 1)?, + parse_channel(2, 2)?, + ), + 4 => Color::from_rgba( + parse_channel(1, 1)?, + parse_channel(2, 2)?, + parse_channel(3, 3)?, + parse_channel(0, 0)?, + ), + 6 => Color::from_rgb( + parse_channel(0, 1)?, + parse_channel(2, 3)?, + parse_channel(4, 5)?, + ), + 8 => Color::from_rgba( + parse_channel(2, 3)?, + parse_channel(4, 5)?, + parse_channel(6, 7)?, + parse_channel(0, 1)?, + ), + _ => None?, + }) +} + +mod color_serde { + use iced_widget::core::Color; + use serde::{Deserialize, Deserializer}; + + use super::parse_argb; + + pub fn deserialize<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Ok(String::deserialize(deserializer) + .map(|hex| parse_argb(&hex))? + .unwrap_or(Color::TRANSPARENT)) + } +} diff --git a/material_theme/src/text.rs b/material_theme/src/text.rs new file mode 100644 index 0000000..10b2e65 --- /dev/null +++ b/material_theme/src/text.rs @@ -0,0 +1,86 @@ +#![allow(dead_code)] +use iced_widget::text::{Catalog, Style, StyleFn}; + +use crate::Theme; + +impl Catalog for Theme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> Self::Class<'a> { + Box::new(none) + } + + fn style(&self, class: &Self::Class<'_>) -> Style { + class(self) + } +} + +pub fn none(_: &Theme) -> Style { + Style { color: None } +} + +pub fn primary(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.primary.on_primary), + } +} + +pub fn primary_container(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.primary.on_primary_container), + } +} + +pub fn secondary(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.secondary.on_secondary), + } +} + +pub fn secondary_container(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.secondary.on_secondary_container), + } +} + +pub fn tertiary(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.tertiary.on_tertiary), + } +} + +pub fn tertiary_container(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.tertiary.on_tertiary_container), + } +} + +pub fn error(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.error.on_error), + } +} + +pub fn error_container(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.error.on_error_container), + } +} + +pub fn surface(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.surface.on_surface), + } +} + +pub fn surface_variant(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.surface.on_surface_variant), + } +} + +pub fn inverse_surface(theme: &Theme) -> Style { + Style { + color: Some(theme.colorscheme.inverse.inverse_on_surface), + } +} diff --git a/material_theme/src/utils.rs b/material_theme/src/utils.rs new file mode 100644 index 0000000..c9eb78e --- /dev/null +++ b/material_theme/src/utils.rs @@ -0,0 +1,61 @@ +use iced_widget::core::Color; + +pub fn elevation(elevation_level: u8) -> f32 { + (match elevation_level { + 0 => 0.0, + 1 => 1.0, + 2 => 3.0, + 3 => 6.0, + 4 => 8.0, + _ => 12.0, + } as f32) +} + +pub fn mix(color1: Color, color2: Color, p2: f32) -> Color { + if p2 <= 0.0 { + return color1; + } else if p2 >= 1.0 { + return color2; + } + + let p1 = 1.0 - p2; + + if color1.a != 1.0 || color2.a != 1.0 { + let a = color1.a * p1 + color2.a * p2; + if a > 0.0 { + let c1 = color1.into_linear().map(|c| c * color1.a * p1); + let c2 = color2.into_linear().map(|c| c * color2.a * p2); + + let [r, g, b] = + [c1[0] + c2[0], c1[1] + c2[1], c1[2] + c2[2]].map(|u| u / a); + + return Color::from_linear_rgba(r, g, b, a); + } + } + + let c1 = color1.into_linear().map(|c| c * p1); + let c2 = color2.into_linear().map(|c| c * p2); + + Color::from_linear_rgba( + c1[0] + c2[0], + c1[1] + c2[1], + c1[2] + c2[2], + c1[3] + c2[3], + ) +} + +#[cfg(test)] +mod tests { + use super::{Color, mix}; + + #[test] + fn mixing_works() { + let base = Color::from_rgba(1.0, 0.0, 0.0, 0.7); + let overlay = Color::from_rgba(0.0, 1.0, 0.0, 0.2); + + assert_eq!( + mix(base, overlay, 0.75).into_rgba8(), + Color::from_linear_rgba(0.53846, 0.46154, 0.0, 0.325).into_rgba8() + ); + } +} diff --git a/src/main.rs b/src/main.rs index 63e9deb..6ab4da9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,8 +35,6 @@ use types::{ Project, }; -//pub type Element<'a, Message> = iced::Element<'a, Message, OtherTheme>; - fn main() -> Result<(), Box> { let version = std::env::args() .nth(1) @@ -60,7 +58,6 @@ fn main() -> Result<(), Box> { iced::application(App::title, App::update, App::view) .font(icon::FONT) .theme(|state| state.theme.value().clone()) - //.theme(|_| theme::LIGHT.clone()) .subscription(App::subscription) .antialiasing(true) .run_with(move || App::new(config_load))?; @@ -446,21 +443,5 @@ impl App { Animation::new(&self.theme, content) .on_update(Message::SwitchTheme) .into() - //row![ - // button("filled") - // .style(theme::button::filled) - // .on_press(Message::RefreshEditorContent), - // button("elevated") - // .style(theme::button::elevated) - // .on_press(Message::RefreshEditorContent), - // button("filled tonal") - // .style(theme::button::filled_tonal) - // .on_press(Message::RefreshEditorContent), - // button("outlined") - // .style(theme::button::outlined) - // .on_press(Message::RefreshEditorContent), - //] - //.spacing(10) - //.into() } } diff --git a/src/theme.rs b/src/theme.rs index 6fe844c..232f309 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -1,18 +1,11 @@ -pub mod button; -pub mod text; - -use std::sync::{Arc, LazyLock}; +use std::sync::Arc; use iced::Color; -use iced::theme::Base; use iced::theme::palette::Extended; use serde::Deserialize; use crate::config::Config; -const DARK_THEME_CONTENT: &str = include_str!("../assets/themes/dark.toml"); -const LIGHT_THEME_CONTENT: &str = include_str!("../assets/themes/light.toml"); - pub fn theme_index(theme_name: &str, slice: &[iced::Theme]) -> Option { slice .iter() @@ -83,159 +76,6 @@ impl Default for Appearance { } } -#[derive(Debug, PartialEq, Deserialize)] -pub struct OtherTheme { - name: String, - #[serde(flatten)] - colorscheme: ColorScheme, -} - -impl Clone for OtherTheme { - fn clone(&self) -> Self { - Self { - name: self.name.clone(), - colorscheme: self.colorscheme, - } - } - - fn clone_from(&mut self, source: &Self) { - self.name = source.name.clone(); - self.colorscheme = source.colorscheme; - } -} - -impl Default for OtherTheme { - fn default() -> Self { - match dark_light::detect().unwrap_or(dark_light::Mode::Unspecified) { - dark_light::Mode::Dark | dark_light::Mode::Unspecified => { - DARK.clone() - } - dark_light::Mode::Light => LIGHT.clone(), - } - } -} - -impl Base for OtherTheme { - fn base(&self) -> iced::theme::Style { - iced::theme::Style { - background_color: self.colorscheme.surface.color, - text_color: self.colorscheme.surface.on_surface, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct ColorScheme { - pub primary: Primary, - pub secondary: Secondary, - pub tertiary: Tertiary, - pub error: Error, - pub surface: Surface, - pub inverse: Inverse, - pub outline: Outline, - #[serde(with = "color_serde")] - pub shadow: Color, -} - -pub static DARK: LazyLock = LazyLock::new(|| { - toml::from_str(DARK_THEME_CONTENT).expect("parse dark theme") -}); - -pub static LIGHT: LazyLock = LazyLock::new(|| { - toml::from_str(LIGHT_THEME_CONTENT).expect("parse light theme") -}); - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Primary { - #[serde(with = "color_serde")] - pub color: Color, - #[serde(with = "color_serde")] - pub on_primary: Color, - #[serde(with = "color_serde")] - pub primary_container: Color, - #[serde(with = "color_serde")] - pub on_primary_container: Color, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Secondary { - #[serde(with = "color_serde")] - pub color: Color, - #[serde(with = "color_serde")] - pub on_secondary: Color, - #[serde(with = "color_serde")] - pub secondary_container: Color, - #[serde(with = "color_serde")] - pub on_secondary_container: Color, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Tertiary { - #[serde(with = "color_serde")] - pub color: Color, - #[serde(with = "color_serde")] - pub on_tertiary: Color, - #[serde(with = "color_serde")] - pub tertiary_container: Color, - #[serde(with = "color_serde")] - pub on_tertiary_container: Color, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Error { - #[serde(with = "color_serde")] - pub color: Color, - #[serde(with = "color_serde")] - pub on_error: Color, - #[serde(with = "color_serde")] - pub error_container: Color, - #[serde(with = "color_serde")] - pub on_error_container: Color, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Surface { - #[serde(with = "color_serde")] - pub color: Color, - #[serde(with = "color_serde")] - pub on_surface: Color, - #[serde(with = "color_serde")] - pub on_surface_variant: Color, - pub surface_container: SurfaceContainer, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct SurfaceContainer { - #[serde(with = "color_serde")] - pub lowest: Color, - #[serde(with = "color_serde")] - pub low: Color, - #[serde(with = "color_serde")] - pub base: Color, - #[serde(with = "color_serde")] - pub high: Color, - #[serde(with = "color_serde")] - pub highest: Color, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Inverse { - #[serde(with = "color_serde")] - pub inverse_surface: Color, - #[serde(with = "color_serde")] - pub inverse_on_surface: Color, - #[serde(with = "color_serde")] - pub inverse_primary: Color, -} - -#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] -pub struct Outline { - #[serde(with = "color_serde")] - pub color: Color, - #[serde(with = "color_serde")] - pub variant: Color, -} - #[derive(Debug, Deserialize)] pub struct Theme { name: String, diff --git a/src/theme/button.rs b/src/theme/button.rs deleted file mode 100644 index ddd2c71..0000000 --- a/src/theme/button.rs +++ /dev/null @@ -1,189 +0,0 @@ -#![allow(dead_code)] -use iced::widget::button::{Catalog, Status, Style, StyleFn}; -use iced::{Background, Border, Color, Shadow, Vector}; - -use super::OtherTheme; - -impl Catalog for OtherTheme { - type Class<'a> = StyleFn<'a, Self>; - - fn default<'a>() -> Self::Class<'a> { - Box::new(default) - } - - fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { - class(self, status) - } -} - -fn default(theme: &OtherTheme, status: Status) -> Style { - filled(theme, status) -} - -fn button( - foreground: Color, - background: Color, - background_hover: Color, - disabled: Color, - shadow_color: Color, - shadow_elevation: u8, - status: Status, -) -> Style { - let border = Border { - radius: 400.0.into(), - ..Default::default() - }; - - let elevation_to_offset = |elevation: u8| { - (match elevation { - 0 => 0.0, - 1 => 1.0, - 2 => 3.0, - 3 => 6.0, - 4 => 8.0, - _ => 12.0, - } as f32) - }; - - match status { - Status::Active | Status::Pressed => Style { - background: Some(Background::Color(background)), - text_color: foreground, - border, - shadow: Shadow { - color: shadow_color, - offset: Vector { - x: 0.0, - y: elevation_to_offset(shadow_elevation), - }, - blur_radius: elevation_to_offset(shadow_elevation) - * (1.0 - + 0.4_f32.powf(elevation_to_offset(shadow_elevation))), - }, - }, - Status::Hovered => Style { - background: Some(Background::Color(background_hover)), - text_color: foreground, - border, - shadow: Shadow { - color: shadow_color, - offset: Vector { - x: 0.0, - y: elevation_to_offset(shadow_elevation + 1), - }, - blur_radius: (elevation_to_offset(shadow_elevation + 1)) - * (1.0 - + 0.4_f32 - .powf(elevation_to_offset(shadow_elevation + 1))), - }, - }, - Status::Disabled => Style { - background: Some(Background::Color(Color { - a: 0.12, - ..disabled - })), - text_color: Color { - a: 0.38, - ..disabled - }, - border, - ..Default::default() - }, - } -} - -pub fn elevated(theme: &OtherTheme, status: Status) -> Style { - let surface_colors = theme.colorscheme.surface; - - let foreground = theme.colorscheme.primary.color; - let background = surface_colors.surface_container.low; - let disabled = surface_colors.on_surface; - - let shadow_color = theme.colorscheme.shadow; - - button( - foreground, - background, - background, - disabled, - shadow_color, - 1, - status, - ) -} - -pub fn filled(theme: &OtherTheme, status: Status) -> Style { - let primary_colors = theme.colorscheme.primary; - - let foreground = primary_colors.on_primary; - let background = primary_colors.color; - let disabled = theme.colorscheme.surface.on_surface; - - let shadow_color = theme.colorscheme.shadow; - - button( - foreground, - background, - background, - disabled, - shadow_color, - 0, - status, - ) -} - -pub fn filled_tonal(theme: &OtherTheme, status: Status) -> Style { - let secondary_colors = theme.colorscheme.secondary; - - let foreground = secondary_colors.on_secondary_container; - let background = secondary_colors.secondary_container; - let disabled = theme.colorscheme.surface.on_surface; - - let shadow_color = theme.colorscheme.shadow; - - button( - foreground, - background, - background, - disabled, - shadow_color, - 0, - status, - ) -} - -pub fn outlined(theme: &OtherTheme, status: Status) -> Style { - let foreground = theme.colorscheme.primary.color; - let background = Color::TRANSPARENT; - let disabled = theme.colorscheme.surface.on_surface; - - let outline = theme.colorscheme.outline.color; - - let border = match status { - Status::Active | Status::Pressed | Status::Hovered => Border { - color: outline, - width: 1.0, - radius: 400.0.into(), - }, - Status::Disabled => Border { - color: Color { - a: 0.12, - ..disabled - }, - width: 1.0, - radius: 400.0.into(), - }, - }; - - let style = button( - foreground, - background, - background, - disabled, - Color::TRANSPARENT, - 0, - status, - ); - - Style { border, ..style } -} diff --git a/src/theme/text.rs b/src/theme/text.rs deleted file mode 100644 index 9cbd056..0000000 --- a/src/theme/text.rs +++ /dev/null @@ -1,50 +0,0 @@ -#![allow(dead_code)] -use iced::widget::text::{Catalog, Style, StyleFn}; - -use super::OtherTheme; - -impl Catalog for OtherTheme { - type Class<'a> = StyleFn<'a, Self>; - - fn default<'a>() -> Self::Class<'a> { - Box::new(none) - } - - fn style(&self, class: &Self::Class<'_>) -> Style { - class(self) - } -} - -pub fn none(_: &OtherTheme) -> Style { - Style { color: None } -} - -pub fn primary(theme: &OtherTheme) -> Style { - Style { - color: Some(theme.colorscheme.primary.on_primary), - } -} - -pub fn secondary(theme: &OtherTheme) -> Style { - Style { - color: Some(theme.colorscheme.secondary.on_secondary), - } -} - -pub fn tertiary(theme: &OtherTheme) -> Style { - Style { - color: Some(theme.colorscheme.tertiary.on_tertiary), - } -} - -pub fn error(theme: &OtherTheme) -> Style { - Style { - color: Some(theme.colorscheme.error.on_error), - } -} - -pub fn surface(theme: &OtherTheme) -> Style { - Style { - color: Some(theme.colorscheme.surface.on_surface), - } -} diff --git a/theme_test/Cargo.toml b/theme_test/Cargo.toml new file mode 100644 index 0000000..34008eb --- /dev/null +++ b/theme_test/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "theme_test" +version = "0.0.1" +edition = "2024" + +[dependencies] +iced.workspace = true +material_theme = { path = "../material_theme" } diff --git a/theme_test/src/main.rs b/theme_test/src/main.rs new file mode 100644 index 0000000..c4735be --- /dev/null +++ b/theme_test/src/main.rs @@ -0,0 +1,89 @@ +use iced::Element; +use iced::widget::{button, column, container, row, text}; +use material_theme::Theme; +use material_theme::button::{ + elevated, filled_tonal, outlined, text as text_style, +}; +use material_theme::container::{ + error, error_container, inverse_surface, primary, primary_container, + secondary, secondary_container, surface, surface_container, + surface_container_high, surface_container_highest, surface_container_low, + surface_container_lowest, tertiary, tertiary_container, +}; +use material_theme::text::surface_variant; + +fn main() { + iced::application("Theme Test", (), view) + .theme(|_| material_theme::DARK.clone()) + .run() + .unwrap(); +} + +#[derive(Debug, Clone)] +enum Message { + Noop, +} + +fn view(_: &()) -> Element<'_, Message, Theme> { + container( + row![ + column![ + button("Disabled"), + button("Filled").on_press(Message::Noop), + button("Filled Tonal") + .on_press(Message::Noop) + .style(filled_tonal), + button("Elevated").on_press(Message::Noop).style(elevated), + button("Outlined").on_press(Message::Noop).style(outlined), + button("Text").on_press(Message::Noop).style(text_style), + button("Text Disabled").style(text_style), + ] + .spacing(10), + column![ + text("None"), + container("Primary").padding(8).style(primary), + container("Primary Container") + .padding(8) + .style(primary_container), + container("Secondary").padding(8).style(secondary), + container("Secondary Container") + .padding(8) + .style(secondary_container), + container("Tertiary").padding(8).style(tertiary), + container("Tertiary Container") + .padding(8) + .style(tertiary_container), + container("Error").padding(8).style(error), + container("Error Container") + .padding(8) + .style(error_container), + container("Surface").padding(8).style(surface), + container(text("Surface Variant").style(surface_variant)) + .padding(8) + .style(surface), + container("Inverse Surface") + .padding(8) + .style(inverse_surface), + container("Surface Container Lowest") + .padding(8) + .style(surface_container_lowest), + container("Surface Container Low") + .padding(8) + .style(surface_container_low), + container("Surface Container") + .padding(8) + .style(surface_container), + container("Surface Container High") + .padding(8) + .style(surface_container_high), + container("Surface Container Highest") + .padding(8) + .style(surface_container_highest), + ] + .spacing(10) + ] + .spacing(20), + ) + .padding(12) + .into() +} -- cgit v1.2.3 From de7647108e831b9201483b665c99d6527964d2ce Mon Sep 17 00:00:00 2001 From: pml68 Date: Mon, 7 Apr 2025 23:42:37 +0200 Subject: fix: custom theme Default changing between calls, missing `apply_options`s --- material_theme/src/lib.rs | 15 ++++++++++----- src/theme.rs | 6 ++++-- 2 files changed, 14 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/material_theme/src/lib.rs b/material_theme/src/lib.rs index 38a94b0..930e511 100644 --- a/material_theme/src/lib.rs +++ b/material_theme/src/lib.rs @@ -69,12 +69,17 @@ impl Clone for Theme { impl Default for Theme { fn default() -> Self { - match dark_light::detect().unwrap_or(dark_light::Mode::Unspecified) { - dark_light::Mode::Dark | dark_light::Mode::Unspecified => { - DARK.clone() + static DEFAULT: LazyLock = LazyLock::new(|| { + match dark_light::detect().unwrap_or(dark_light::Mode::Unspecified) + { + dark_light::Mode::Dark | dark_light::Mode::Unspecified => { + DARK.clone() + } + dark_light::Mode::Light => LIGHT.clone(), } - dark_light::Mode::Light => LIGHT.clone(), - } + }); + + DEFAULT.clone() } } diff --git a/src/theme.rs b/src/theme.rs index 232f309..b721ddc 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -6,6 +6,9 @@ use serde::Deserialize; use crate::config::Config; +const DEFAULT_THEME_CONTENT: &str = + include_str!("../assets/themes/rose_pine.toml"); + pub fn theme_index(theme_name: &str, slice: &[iced::Theme]) -> Option { slice .iter() @@ -97,8 +100,7 @@ impl From for iced::Theme { impl Default for Theme { fn default() -> Self { - toml::from_str(include_str!("../assets/themes/rose_pine.toml")) - .expect("parse default theme") + toml::from_str(DEFAULT_THEME_CONTENT).expect("parse default theme") } } -- cgit v1.2.3 From c6a76e63604b16b9a14d5de6bd0ea91eea7f9bf2 Mon Sep 17 00:00:00 2001 From: pml68 Date: Tue, 8 Apr 2025 01:13:38 +0200 Subject: feat(material_theme): implement Catalog for iced_dialog (`dialog` feature) --- Cargo.lock | 2 ++ Cargo.toml | 3 +- material_theme/Cargo.toml | 3 ++ material_theme/src/lib.rs | 74 ++++++++++++++++++++++++++--------------------- src/main.rs | 17 ++++++----- src/panes/element_list.rs | 11 +++---- 6 files changed, 61 insertions(+), 49 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 2dc8556..b2ab721 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2678,6 +2678,8 @@ name = "material_theme" version = "0.14.0-dev" dependencies = [ "dark-light", + "iced_anim", + "iced_dialog", "iced_widget", "serde", "toml", diff --git a/Cargo.toml b/Cargo.toml index 33d3b8e..63e5f89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ iced.workspace = true iced_anim.workspace = true iced_custom_highlighter = { git = "https://github.com/pml68/iced_custom_highlighter", branch = "master" } iced_drop = { path = "iced_drop" } -iced_dialog = { git = "https://github.com/pml68/iced_dialog", branch = "iced/personal" } +iced_dialog.workspace = true material_theme = { path = "material_theme" } serde.workspace = true serde_json = "1.0.140" @@ -36,6 +36,7 @@ dirs-next = "2.0.0" [workspace.dependencies] iced_anim = { version = "0.2.1", features = ["derive"] } +iced_dialog = { git = "https://github.com/pml68/iced_dialog", branch = "iced/personal" } serde = { version = "1.0.219", features = ["derive"] } toml = "0.8.20" diff --git a/material_theme/Cargo.toml b/material_theme/Cargo.toml index 5a48dc0..e88ce92 100644 --- a/material_theme/Cargo.toml +++ b/material_theme/Cargo.toml @@ -14,12 +14,15 @@ rust-version = "1.85" [features] default = [] animate = ["dep:iced_anim"] +dialog = ["dep:iced_dialog"] [dependencies] iced_widget = "0.14.0-dev" serde.workspace = true toml.workspace = true dark-light = "2.0.0" +iced_dialog.workspace = true +iced_dialog.optional = true [dependencies.iced_anim] workspace = true diff --git a/material_theme/src/lib.rs b/material_theme/src/lib.rs index 930e511..87cf353 100644 --- a/material_theme/src/lib.rs +++ b/material_theme/src/lib.rs @@ -28,31 +28,6 @@ impl Theme { } } -#[cfg(feature = "animate")] -impl iced_anim::Animate for Theme { - fn components() -> usize { - ColorScheme::components() - } - - fn update(&mut self, components: &mut impl Iterator) { - let mut colors = self.colorscheme; - colors.update(components); - - *self = Theme::new("Animating Theme", colors); - } - - fn distance_to(&self, end: &Self) -> Vec { - self.colorscheme.distance_to(&end.colorscheme) - } - - fn lerp(&mut self, start: &Self, end: &Self, progress: f32) { - let mut colors = self.colorscheme; - colors.lerp(&start.colorscheme, &end.colorscheme, progress); - - *self = Theme::new("Animating Theme", colors); - } -} - impl Clone for Theme { fn clone(&self) -> Self { Self { @@ -92,6 +67,47 @@ impl Base for Theme { } } +#[cfg(feature = "animate")] +impl iced_anim::Animate for Theme { + fn components() -> usize { + ColorScheme::components() + } + + fn update(&mut self, components: &mut impl Iterator) { + let mut colors = self.colorscheme; + colors.update(components); + + *self = Theme::new("Animating Theme", colors); + } + + fn distance_to(&self, end: &Self) -> Vec { + self.colorscheme.distance_to(&end.colorscheme) + } + + fn lerp(&mut self, start: &Self, end: &Self, progress: f32) { + let mut colors = self.colorscheme; + colors.lerp(&start.colorscheme, &end.colorscheme, progress); + + *self = Theme::new("Animating Theme", colors); + } +} + +#[cfg(feature = "dialog")] +impl iced_dialog::dialog::Catalog for Theme { + fn default_container<'a>() + -> ::Class<'a> { + Box::new(container::surface) + } +} + +pub static DARK: LazyLock = LazyLock::new(|| { + toml::from_str(DARK_THEME_CONTENT).expect("parse dark theme") +}); + +pub static LIGHT: LazyLock = LazyLock::new(|| { + toml::from_str(LIGHT_THEME_CONTENT).expect("parse light theme") +}); + #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] #[cfg_attr(feature = "animate", derive(iced_anim::Animate))] pub struct ColorScheme { @@ -106,14 +122,6 @@ pub struct ColorScheme { pub shadow: Color, } -pub static DARK: LazyLock = LazyLock::new(|| { - toml::from_str(DARK_THEME_CONTENT).expect("parse dark theme") -}); - -pub static LIGHT: LazyLock = LazyLock::new(|| { - toml::from_str(LIGHT_THEME_CONTENT).expect("parse light theme") -}); - #[derive(Debug, Clone, Copy, PartialEq, Deserialize)] #[cfg_attr(feature = "animate", derive(iced_anim::Animate))] pub struct Primary { diff --git a/src/main.rs b/src/main.rs index 6ab4da9..3895dbc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,8 +31,7 @@ use iced_dialog::dialog::Dialog; use panes::{code_view, designer_view, element_list}; use tokio::runtime; use types::{ - Action, DesignerPane, DialogAction, DialogButtons, ElementName, Message, - Project, + Action, DesignerPane, DialogAction, DialogButtons, Message, Project, }; fn main() -> Result<(), Box> { @@ -79,7 +78,6 @@ struct App { dialog_content: String, dialog_buttons: DialogButtons, dialog_action: DialogAction, - element_list: &'static [ElementName], editor_content: text_editor::Content, } @@ -132,7 +130,6 @@ impl App { dialog_content: String::new(), dialog_buttons: DialogButtons::None, dialog_action: DialogAction::None, - element_list: ElementName::ALL, editor_content: text_editor::Content::new(), }, task, @@ -408,9 +405,7 @@ impl App { code_view::view(&self.editor_content, is_focused) } }, - Panes::ElementList => { - element_list::view(self.element_list, is_focused) - } + Panes::ElementList => element_list::view(is_focused), } }, ) @@ -438,7 +433,13 @@ impl App { DialogButtons::OkCancel => vec![ok_button(), cancel_button()], }, ) - .title(self.dialog_title); + .title(self.dialog_title) + .container_style(|theme| container::Style { + background: Some( + theme.extended_palette().background.strong.color.into(), + ), + ..Default::default() + }); Animation::new(&self.theme, content) .on_update(Message::SwitchTheme) diff --git a/src/panes/element_list.rs b/src/panes/element_list.rs index 10eea66..594c203 100644 --- a/src/panes/element_list.rs +++ b/src/panes/element_list.rs @@ -5,13 +5,13 @@ use iced_drop::droppable; use super::style; use crate::types::{ElementName, Message}; -fn items_list_view(items: &[ElementName]) -> Element<'_, Message> { +fn items_list_view<'a>() -> Element<'a, Message> { let mut column = Column::new() .spacing(20) .align_x(Alignment::Center) .width(Length::Fill); - for item in items { + for item in ElementName::ALL { column = column.push( droppable(text(item.clone().to_string())).on_drop(|point, rect| { Message::DropNewElement(item.clone(), point, rect) @@ -25,11 +25,8 @@ fn items_list_view(items: &[ElementName]) -> Element<'_, Message> { .into() } -pub fn view( - element_list: &[ElementName], - is_focused: bool, -) -> pane_grid::Content<'_, Message> { - let items_list = items_list_view(element_list); +pub fn view<'a>(is_focused: bool) -> pane_grid::Content<'a, Message> { + let items_list = items_list_view(); let content = column![items_list] .align_x(Alignment::Center) .height(Length::Fill) -- cgit v1.2.3 From 53dc5464c2f595d1a32174598e280428d3265f15 Mon Sep 17 00:00:00 2001 From: pml68 Date: Tue, 8 Apr 2025 19:40:45 +0200 Subject: feat(material_theme): impl `menu::Catalog`, change `dialog::Catalog` impl --- material_theme/src/dialog.rs | 25 ++++++++++ material_theme/src/lib.rs | 11 ++--- material_theme/src/menu.rs | 29 ++++++++++++ src/types/rendered_element.rs | 105 +++++++++++++++++++++++++++--------------- 4 files changed, 126 insertions(+), 44 deletions(-) create mode 100644 material_theme/src/dialog.rs create mode 100644 material_theme/src/menu.rs (limited to 'src') diff --git a/material_theme/src/dialog.rs b/material_theme/src/dialog.rs new file mode 100644 index 0000000..68c61b5 --- /dev/null +++ b/material_theme/src/dialog.rs @@ -0,0 +1,25 @@ +use iced_widget::container::Style; +use iced_widget::core::{Background, border}; + +use super::{Theme, text}; + +impl iced_dialog::dialog::Catalog for Theme { + fn default_container<'a>() + -> ::Class<'a> { + Box::new(default_container) + } + + fn default_title<'a>() -> ::Class<'a> { + Box::new(text::surface) + } +} + +pub fn default_container(theme: &Theme) -> Style { + let colors = theme.colorscheme.surface; + Style { + background: Some(Background::Color(colors.surface_container.high)), + text_color: Some(colors.on_surface_variant), + border: border::rounded(28), + ..Style::default() + } +} diff --git a/material_theme/src/lib.rs b/material_theme/src/lib.rs index 273ef9a..a4eea24 100644 --- a/material_theme/src/lib.rs +++ b/material_theme/src/lib.rs @@ -6,6 +6,9 @@ use serde::Deserialize; pub mod button; pub mod container; +#[cfg(feature = "dialog")] +pub mod dialog; +pub mod menu; pub mod scrollable; pub mod text; pub mod utils; @@ -93,14 +96,6 @@ impl iced_anim::Animate for Theme { } } -#[cfg(feature = "dialog")] -impl iced_dialog::dialog::Catalog for Theme { - fn default_container<'a>() - -> ::Class<'a> { - Box::new(container::surface) - } -} - pub static DARK: LazyLock = LazyLock::new(|| { toml::from_str(DARK_THEME_CONTENT).expect("parse dark theme") }); diff --git a/material_theme/src/menu.rs b/material_theme/src/menu.rs new file mode 100644 index 0000000..d1bebec --- /dev/null +++ b/material_theme/src/menu.rs @@ -0,0 +1,29 @@ +use iced_widget::core::{Background, border}; +use iced_widget::overlay::menu::{Catalog, Style, StyleFn}; + +use super::Theme; + +impl Catalog for Theme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> ::Class<'a> { + Box::new(default) + } + + fn style(&self, class: &::Class<'_>) -> Style { + class(self) + } +} + +pub fn default(theme: &Theme) -> Style { + let surface = theme.colorscheme.surface; + let secondary = theme.colorscheme.secondary; + + Style { + border: border::rounded(4), + background: Background::Color(surface.surface_container.base), + text_color: surface.on_surface, + selected_background: Background::Color(secondary.secondary_container), + selected_text_color: secondary.on_secondary_container, + } +} diff --git a/src/types/rendered_element.rs b/src/types/rendered_element.rs index 0a78dcd..77b76e4 100755 --- a/src/types/rendered_element.rs +++ b/src/types/rendered_element.rs @@ -317,53 +317,86 @@ impl<'a> From for Element<'a, Message> { let child_elements = copy.child_elements.unwrap_or_default(); let content: Element<'a, Message> = match copy.name { - ElementName::Text(s) => { - if s.is_empty() { - widget::text("New Text").apply_options(copy.options).into() - } else { - widget::text(s).apply_options(copy.options).into() - } - } - ElementName::Button(s) => { - if s.is_empty() { - widget::button(widget::text("New Button")) - .apply_options(copy.options) - .into() - } else { - widget::button(widget::text(s)) - .apply_options(copy.options) - .into() - } + ElementName::Text(s) => if s.is_empty() { + widget::text("New Text") + } else { + widget::text(s) } + .apply_options(copy.options) + .into(), + ElementName::Button(s) => widget::button(if s.is_empty() { + widget::text("New Button") + } else { + widget::text(s) + }) + .apply_options(copy.options) + .into(), ElementName::Svg(p) => { widget::svg(p).apply_options(copy.options).into() } ElementName::Image(p) => { widget::image(p).apply_options(copy.options).into() } - ElementName::Container => { - widget::container(if child_elements.len() == 1 { - child_elements[0].clone().into() - } else { - Element::from("") - }) - .apply_options(copy.options) - .padding(20) - .into() + ElementName::Container => if child_elements.len() == 1 { + widget::container(child_elements[0].clone()) + } else { + widget::container("New Container") + .padding(20) + .style(|theme| widget::container::Style { + border: iced::border::rounded(4).color( + theme.extended_palette().background.strongest.text, + ), + ..Default::default() + }) } - ElementName::Row => widget::Row::from_vec( - child_elements.into_iter().map(Into::into).collect(), - ) - .padding(20) - .apply_options(copy.options) - .into(), - ElementName::Column => widget::Column::from_vec( - child_elements.into_iter().map(Into::into).collect(), - ) - .padding(20) .apply_options(copy.options) .into(), + ElementName::Row => { + if !child_elements.is_empty() { + widget::Row::with_children( + child_elements.into_iter().map(Into::into), + ) + .apply_options(copy.options) + .into() + } else { + widget::container( + widget::row!["New Row"] + .padding(20) + .apply_options(copy.options), + ) + .style(|theme| widget::container::Style { + border: iced::border::rounded(4).color( + theme.extended_palette().background.strongest.text, + ), + ..Default::default() + }) + .into() + } + } + ElementName::Column => { + if !child_elements.is_empty() { + widget::Column::with_children( + child_elements.into_iter().map(Into::into), + ) + .apply_options(copy.options) + .into() + } else { + widget::container( + widget::column!["New Column"] + .padding(20) + .apply_options(copy.options), + ) + .style(|theme| widget::container::Style { + border: iced::border::rounded(4).color( + theme.extended_palette().background.strongest.text, + ), + ..Default::default() + }) + .into() + } + } }; + iced_drop::droppable(content) .id(value.id().clone()) .drag_hide(true) -- cgit v1.2.3 From 941eb51e043b6b847089130625c2df10b0674154 Mon Sep 17 00:00:00 2001 From: pml68 Date: Wed, 9 Apr 2025 00:29:34 +0200 Subject: feat: update `iced`, make designer view more usable --- Cargo.lock | 252 +++++++++++++++++++++++------------------- Cargo.toml | 4 +- src/main.rs | 18 ++- src/panes/designer_view.rs | 19 +++- src/types/rendered_element.rs | 42 ++++--- 5 files changed, 193 insertions(+), 142 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index b2ab721..a324ccd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,6 +57,12 @@ dependencies = [ "zerocopy 0.7.35", ] +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + [[package]] name = "aligned-vec" version = "0.5.0" @@ -105,15 +111,6 @@ version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" -[[package]] -name = "approx" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" -dependencies = [ - "num-traits", -] - [[package]] name = "arbitrary" version = "1.4.1" @@ -569,12 +566,6 @@ version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" -[[package]] -name = "by_address" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" - [[package]] name = "bytemuck" version = "1.22.0" @@ -1316,12 +1307,6 @@ dependencies = [ "zune-inflate", ] -[[package]] -name = "fast-srgb8" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1" - [[package]] name = "fastrand" version = "2.3.0" @@ -1767,9 +1752,9 @@ dependencies = [ [[package]] name = "half" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7db2ff139bba50379da6aa0766b52fdcb62cb5b263009b09ed58ba604e14bbd1" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" dependencies = [ "cfg-if", "crunchy", @@ -1784,6 +1769,12 @@ dependencies = [ "foldhash", ] +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "heck" version = "0.5.0" @@ -1938,11 +1929,14 @@ dependencies = [ [[package]] name = "iced" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "iced_core", + "iced_debug", + "iced_devtools", "iced_futures", "iced_renderer", + "iced_runtime", "iced_widget", "iced_winit", "image", @@ -1967,6 +1961,21 @@ dependencies = [ "syn", ] +[[package]] +name = "iced_beacon" +version = "0.14.0-dev" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" +dependencies = [ + "bincode", + "futures", + "iced_core", + "log", + "semver", + "serde", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "iced_builder" version = "0.1.0" @@ -1996,7 +2005,7 @@ dependencies = [ [[package]] name = "iced_core" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "bitflags 2.9.0", "bytes", @@ -2005,8 +2014,8 @@ dependencies = [ "lilt", "log", "num-traits", - "palette", "rustc-hash 2.1.1", + "serde", "smol_str", "thiserror 1.0.69", "web-time", @@ -2022,6 +2031,26 @@ dependencies = [ "two-face", ] +[[package]] +name = "iced_debug" +version = "0.14.0-dev" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" +dependencies = [ + "iced_beacon", + "iced_core", + "log", +] + +[[package]] +name = "iced_devtools" +version = "0.14.0-dev" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" +dependencies = [ + "iced_debug", + "iced_program", + "iced_widget", +] + [[package]] name = "iced_dialog" version = "0.14.0-dev" @@ -2055,7 +2084,7 @@ dependencies = [ [[package]] name = "iced_futures" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "futures", "iced_core", @@ -2069,7 +2098,7 @@ dependencies = [ [[package]] name = "iced_graphics" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "bitflags 2.9.0", "bytemuck", @@ -2086,10 +2115,19 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "iced_program" +version = "0.14.0-dev" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" +dependencies = [ + "iced_graphics", + "iced_runtime", +] + [[package]] name = "iced_renderer" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "iced_graphics", "iced_tiny_skia", @@ -2101,20 +2139,20 @@ dependencies = [ [[package]] name = "iced_runtime" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "bytes", "iced_core", + "iced_debug", "iced_futures", "raw-window-handle", - "sipper", "thiserror 1.0.69", ] [[package]] name = "iced_tiny_skia" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "bytemuck", "cosmic-text", @@ -2130,7 +2168,7 @@ dependencies = [ [[package]] name = "iced_wgpu" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "bitflags 2.9.0", "bytemuck", @@ -2149,12 +2187,13 @@ dependencies = [ [[package]] name = "iced_widget" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ "iced_renderer", "iced_runtime", "log", "num-traits", + "ouroboros", "rustc-hash 2.1.1", "thiserror 1.0.69", "unicode-segmentation", @@ -2163,11 +2202,10 @@ dependencies = [ [[package]] name = "iced_winit" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#1a84a8019cbd95ae1b1c88f75aeb0a15f0f3caf2" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#add48e518b3423bed980983ddc373cfb8f5e8980" dependencies = [ - "iced_futures", - "iced_graphics", - "iced_runtime", + "iced_debug", + "iced_program", "log", "rustc-hash 2.1.1", "thiserror 1.0.69", @@ -2758,9 +2796,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5" +checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" dependencies = [ "adler2", "simd-adler32", @@ -3347,36 +3385,36 @@ dependencies = [ ] [[package]] -name = "owned_ttf_parser" -version = "0.25.0" +name = "ouroboros" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec719bbf3b2a81c109a4e20b1f129b5566b7dce654bc3872f6a05abf82b2c4" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" dependencies = [ - "ttf-parser 0.25.1", + "aliasable", + "ouroboros_macro", + "static_assertions", ] [[package]] -name = "palette" -version = "0.7.6" +name = "ouroboros_macro" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cbf71184cc5ecc2e4e1baccdb21026c20e5fc3dcf63028a086131b3ab00b6e6" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" dependencies = [ - "approx", - "fast-srgb8", - "palette_derive", - "phf", + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn", ] [[package]] -name = "palette_derive" -version = "0.7.6" +name = "owned_ttf_parser" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5030daf005bface118c096f510ffb781fc28f9ab6a32ab224d8631be6851d30" +checksum = "22ec719bbf3b2a81c109a4e20b1f129b5566b7dce654bc3872f6a05abf82b2c4" dependencies = [ - "by_address", - "proc-macro2", - "quote", - "syn", + "ttf-parser 0.25.1", ] [[package]] @@ -3430,48 +3468,6 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" -[[package]] -name = "phf" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" -dependencies = [ - "phf_macros", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" -dependencies = [ - "siphasher", -] - [[package]] name = "pico-args" version = "0.5.0" @@ -3600,6 +3596,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "version_check", + "yansi", +] + [[package]] name = "profiling" version = "1.0.16" @@ -4176,6 +4185,9 @@ name = "semver" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" +dependencies = [ + "serde", +] [[package]] name = "serde" @@ -4308,16 +4320,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" -[[package]] -name = "sipper" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bccb4192828b3d9a08e0b5a73f17795080dfb278b50190216e3ae2132cf4f95" -dependencies = [ - "futures", - "pin-project-lite", -] - [[package]] name = "skrifa" version = "0.26.6" @@ -4484,7 +4486,7 @@ version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "rustversion", @@ -4612,7 +4614,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" dependencies = [ "cfg-expr", - "heck", + "heck 0.5.0", "pkg-config", "toml", "version-compare", @@ -4790,9 +4792,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.44.1" +version = "1.44.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f382da615b842244d4b8738c82ed1275e6c5dd90c459a30941cd07080b06c91a" +checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" dependencies = [ "backtrace", "bytes", @@ -4800,9 +4802,21 @@ dependencies = [ "mio", "pin-project-lite", "socket2", + "tokio-macros", "windows-sys 0.52.0", ] +[[package]] +name = "tokio-macros" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tokio-native-tls" version = "0.3.1" @@ -6029,9 +6043,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e97b544156e9bebe1a0ffbc03484fc1ffe3100cbce3ffb17eac35f7cdd7ab36" +checksum = "63d3fcd9bba44b03821e7d699eeee959f3126dcc4aa8e4ae18ec617c2a5cea10" dependencies = [ "memchr", ] @@ -6161,6 +6175,12 @@ dependencies = [ "lzma-sys", ] +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + [[package]] name = "yazi" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 63e5f89..e48a39c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ material_theme = { path = "material_theme" } serde.workspace = true serde_json = "1.0.140" toml.workspace = true -tokio = { version = "1.42.1", features = ["fs"] } +tokio = { version = "1.44.2", features = ["fs"] } tokio-stream = { version = "0.1", features = ["fs"] } # TODO: enable tokio when it actually compiles # rfd = { version = "0.15.2", default-features = false, features = ["tokio", "xdg-portal"] } @@ -43,7 +43,7 @@ toml = "0.8.20" [workspace.dependencies.iced] git = "https://github.com/pml68/iced" branch = "feat/rehighlight-on-redraw" -features = ["image", "svg", "advanced", "tokio"] +features = ["image", "svg", "advanced", "tokio", "lazy"] [build-dependencies] iced_fontello = "0.13.2" diff --git a/src/main.rs b/src/main.rs index 3895dbc..d58329a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,12 +54,18 @@ fn main() -> Result<(), Box> { rt.block_on(Config::load()) }; - iced::application(App::title, App::update, App::view) - .font(icon::FONT) - .theme(|state| state.theme.value().clone()) - .subscription(App::subscription) - .antialiasing(true) - .run_with(move || App::new(config_load))?; + iced::application( + move || App::new(config_load.clone()), + App::update, + App::view, + ) + .title(App::title) + .font(icon::FONT) + .theme(|state| state.theme.value().clone()) + .subscription(App::subscription) + .antialiasing(true) + .run()?; + Ok(()) } diff --git a/src/panes/designer_view.rs b/src/panes/designer_view.rs index 6340f73..69ff750 100644 --- a/src/panes/designer_view.rs +++ b/src/panes/designer_view.rs @@ -1,16 +1,29 @@ -use iced::widget::{Space, button, container, pane_grid, row, text, themer}; +use iced::widget::{ + Space, button, center, container, pane_grid, responsive, row, text, themer, +}; use iced::{Alignment, Element, Length}; use super::style; use crate::types::{DesignerPane, Message, RenderedElement}; pub fn view<'a>( - element_tree: Option<&RenderedElement>, + element_tree: Option<&'a RenderedElement>, designer_theme: iced::Theme, is_focused: bool, ) -> pane_grid::Content<'a, Message> { let el_tree: Element<'a, Message> = match element_tree { - Some(tree) => tree.clone().into(), + Some(tree) => responsive(|size| { + center( + container(tree.clone()) + .style(|theme| { + container::background(theme.palette().background) + }) + .height(size.height * 0.5) + .width(size.height * 0.8), + ) + .into() + }) + .into(), None => text("Open a project or begin creating one").into(), }; let content = container(themer(designer_theme, el_tree)) diff --git a/src/types/rendered_element.rs b/src/types/rendered_element.rs index 77b76e4..bd8187e 100755 --- a/src/types/rendered_element.rs +++ b/src/types/rendered_element.rs @@ -340,15 +340,19 @@ impl<'a> From for Element<'a, Message> { ElementName::Container => if child_elements.len() == 1 { widget::container(child_elements[0].clone()) } else { - widget::container("New Container") - .padding(20) - .style(|theme| widget::container::Style { - border: iced::border::rounded(4).color( - theme.extended_palette().background.strongest.text, - ), + widget::container("New Container").style( + |theme: &iced::Theme| widget::container::Style { + border: iced::Border { + color: theme.palette().text, + + width: 2.0, + radius: 4.into(), + }, ..Default::default() - }) + }, + ) } + .padding(20) .apply_options(copy.options) .into(), ElementName::Row => { @@ -356,6 +360,7 @@ impl<'a> From for Element<'a, Message> { widget::Row::with_children( child_elements.into_iter().map(Into::into), ) + .padding(20) .apply_options(copy.options) .into() } else { @@ -364,10 +369,13 @@ impl<'a> From for Element<'a, Message> { .padding(20) .apply_options(copy.options), ) - .style(|theme| widget::container::Style { - border: iced::border::rounded(4).color( - theme.extended_palette().background.strongest.text, - ), + .style(|theme: &iced::Theme| widget::container::Style { + border: iced::Border { + color: theme.palette().text, + + width: 2.0, + radius: 4.into(), + }, ..Default::default() }) .into() @@ -378,6 +386,7 @@ impl<'a> From for Element<'a, Message> { widget::Column::with_children( child_elements.into_iter().map(Into::into), ) + .padding(20) .apply_options(copy.options) .into() } else { @@ -386,10 +395,13 @@ impl<'a> From for Element<'a, Message> { .padding(20) .apply_options(copy.options), ) - .style(|theme| widget::container::Style { - border: iced::border::rounded(4).color( - theme.extended_palette().background.strongest.text, - ), + .style(|theme: &iced::Theme| widget::container::Style { + border: iced::Border { + color: theme.palette().text, + + width: 2.0, + radius: 4.into(), + }, ..Default::default() }) .into() -- cgit v1.2.3 From de43465ddb50dd6b0c44d8de7a05aa16ba38d312 Mon Sep 17 00:00:00 2001 From: pml68 Date: Tue, 15 Apr 2025 01:44:00 +0200 Subject: chore(deps): update `iced_dialog` --- Cargo.lock | 18 +++++++++--------- crates/material_theme/src/dialog.rs | 30 +++++++++++++++++++++++------- src/dialogs.rs | 4 ++-- theme_test/src/main.rs | 7 ++----- 4 files changed, 36 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 7a48765..c8379a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -107,9 +107,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.97" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" [[package]] name = "arbitrary" @@ -860,9 +860,9 @@ dependencies = [ [[package]] name = "cosmic-text" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1db686e755000c93f73a3acc78be56a71e3efb83ed92886f45faea2b9485bad7" +checksum = "da46a9d5a8905cc538a4a5bceb6a4510de7a51049c5588c0114efce102bcbbe8" dependencies = [ "bitflags 2.9.0", "fontdb 0.16.2", @@ -1733,9 +1733,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5017294ff4bb30944501348f6f8e42e6ad28f42c8bbef7a74029aff064a4e3c2" +checksum = "75249d144030531f8dee69fe9cea04d3edf809a017ae445e2abdff6629e86633" dependencies = [ "atomic-waker", "bytes", @@ -2054,7 +2054,7 @@ dependencies = [ [[package]] name = "iced_dialog" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced_dialog?branch=iced%2Fpersonal#c0f931f38ac83e77cfb937d4166fa8d2a23988cf" +source = "git+https://github.com/pml68/iced_dialog?branch=iced%2Fpersonal#a41468011f8e4f566e9301565f3276fb10cc9551" dependencies = [ "iced_core", "iced_widget", @@ -3778,9 +3778,9 @@ dependencies = [ [[package]] name = "ravif" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2413fd96bd0ea5cdeeb37eaf446a22e6ed7b981d792828721e74ded1980a45c6" +checksum = "d6a5f31fcf7500f9401fea858ea4ab5525c99f2322cfcee732c0e6c74208c0c6" dependencies = [ "avif-serialize", "imgref", diff --git a/crates/material_theme/src/dialog.rs b/crates/material_theme/src/dialog.rs index 68c61b5..a022548 100644 --- a/crates/material_theme/src/dialog.rs +++ b/crates/material_theme/src/dialog.rs @@ -1,25 +1,41 @@ -use iced_widget::container::Style; +use iced_dialog::dialog::{Catalog, Style, StyleFn}; +use iced_widget::container; use iced_widget::core::{Background, border}; use super::{Theme, text}; -impl iced_dialog::dialog::Catalog for Theme { - fn default_container<'a>() - -> ::Class<'a> { +impl Catalog for Theme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> ::Class<'a> { + Box::new(default) + } + + fn default_container<'a>() -> ::Class<'a> { Box::new(default_container) } fn default_title<'a>() -> ::Class<'a> { Box::new(text::surface) } + + fn style(&self, class: &::Class<'_>) -> Style { + class(self) + } } -pub fn default_container(theme: &Theme) -> Style { +pub fn default_container(theme: &Theme) -> container::Style { let colors = theme.colorscheme.surface; - Style { + container::Style { background: Some(Background::Color(colors.surface_container.high)), text_color: Some(colors.on_surface_variant), border: border::rounded(28), - ..Style::default() + ..container::Style::default() + } +} + +pub fn default(theme: &Theme) -> Style { + Style { + backdrop_color: theme.colorscheme.scrim, } } diff --git a/src/dialogs.rs b/src/dialogs.rs index 08513fd..a623f35 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -9,11 +9,11 @@ pub const WARNING_TITLE: &str = "Heads up!"; pub const ERROR_TITLE: &str = "Oops! Something went wrong."; pub fn ok_button<'a>() -> Element<'a, Message> { - button("Ok").on_press(Message::DialogOk).into() + button("Ok", Message::DialogOk).into() } pub fn cancel_button<'a>() -> Element<'a, Message> { - button("Cancel").on_press(Message::DialogCancel).into() + button("Cancel", Message::DialogCancel).into() } pub fn error_dialog(description: impl Into) -> Task { diff --git a/theme_test/src/main.rs b/theme_test/src/main.rs index 9826fe9..bcf16de 100644 --- a/theme_test/src/main.rs +++ b/theme_test/src/main.rs @@ -126,12 +126,9 @@ impl State { let dialog = dialog(self.show_dialog, base, iced::widget::text("Say Hi!")) .title("This is a Dialog.") - .push_button( - iced_dialog::button("Hi!").on_press(Message::CloseDialog), - ) - .backdrop(|theme| theme.colorscheme.scrim) + .push_button(iced_dialog::button("Hi!", Message::CloseDialog)) .width(280) - .height(187); + .height(186); Animation::new(&self.theme, dialog) .on_update(Message::SwitchTheme) -- cgit v1.2.3 From 427be61dc78a38586ee4829c0b706d07d3d9cbf0 Mon Sep 17 00:00:00 2001 From: pml68 Date: Wed, 16 Apr 2025 20:08:04 +0200 Subject: feat: center the window by default --- src/main.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index d58329a..c7e6314 100644 --- a/src/main.rs +++ b/src/main.rs @@ -64,6 +64,7 @@ fn main() -> Result<(), Box> { .theme(|state| state.theme.value().clone()) .subscription(App::subscription) .antialiasing(true) + .centered() .run()?; Ok(()) -- cgit v1.2.3 From 1683717e93899d4c90641e605bfc96cbc2bf5ef1 Mon Sep 17 00:00:00 2001 From: pml68 Date: Fri, 18 Apr 2025 00:52:13 +0200 Subject: fix: `iced` 0.14 codegen --- Cargo.lock | 43 +++++++++++++++++++++---------------------- src/types/project.rs | 2 +- src/types/rendered_element.rs | 13 ++++++++++--- 3 files changed, 32 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index e8a5b71..4f0a992 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,7 +187,7 @@ dependencies = [ "enumflags2", "futures-channel", "futures-util", - "rand 0.9.0", + "rand 0.9.1", "raw-window-handle", "serde", "serde_repr", @@ -1945,7 +1945,7 @@ dependencies = [ [[package]] name = "iced" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_core", "iced_debug", @@ -1980,7 +1980,7 @@ dependencies = [ [[package]] name = "iced_beacon" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "bincode", "futures", @@ -2021,7 +2021,7 @@ dependencies = [ [[package]] name = "iced_core" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "bitflags 2.9.0", "bytes", @@ -2050,7 +2050,7 @@ dependencies = [ [[package]] name = "iced_debug" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_beacon", "iced_core", @@ -2060,7 +2060,7 @@ dependencies = [ [[package]] name = "iced_devtools" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_debug", "iced_program", @@ -2100,7 +2100,7 @@ dependencies = [ [[package]] name = "iced_futures" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "futures", "iced_core", @@ -2114,7 +2114,7 @@ dependencies = [ [[package]] name = "iced_graphics" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "bitflags 2.9.0", "bytemuck", @@ -2135,7 +2135,7 @@ dependencies = [ [[package]] name = "iced_program" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_graphics", "iced_runtime", @@ -2144,7 +2144,7 @@ dependencies = [ [[package]] name = "iced_renderer" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_graphics", "iced_tiny_skia", @@ -2156,7 +2156,7 @@ dependencies = [ [[package]] name = "iced_runtime" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "bytes", "iced_core", @@ -2169,7 +2169,7 @@ dependencies = [ [[package]] name = "iced_tiny_skia" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "bytemuck", "cosmic-text", @@ -2186,7 +2186,7 @@ dependencies = [ [[package]] name = "iced_wgpu" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "bitflags 2.9.0", "bytemuck", @@ -2207,7 +2207,7 @@ dependencies = [ [[package]] name = "iced_widget" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_renderer", "iced_runtime", @@ -2225,7 +2225,7 @@ dependencies = [ [[package]] name = "iced_winit" version = "0.14.0-dev" -source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#4f933c3b8919a115fa82d9aee94ec5b1c81c4dfe" +source = "git+https://github.com/pml68/iced?branch=feat%2Frehighlight-on-redraw#b6433c4637ddf4697154feeb14c66e06200e4e1b" dependencies = [ "iced_debug", "iced_program", @@ -3665,9 +3665,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] @@ -3781,13 +3781,12 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", - "zerocopy 0.8.24", ] [[package]] @@ -4602,9 +4601,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "svg_fmt" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d813d71d82c4cbc1742135004e4a79fd870214c155443451c139c9470a0aa" +checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" [[package]] name = "svgtypes" diff --git a/src/types/project.rs b/src/types/project.rs index 50cbb69..145ab18 100644 --- a/src/types/project.rs +++ b/src/types/project.rs @@ -103,7 +103,7 @@ use iced::{{widget::{{{imports}}},Element}}; {theme_imports} fn main() -> iced::Result {{ - iced::application("{}", State::update, State::view).theme(State::theme).run() + iced::application(State::default, State::update, State::view).title("{}").theme(State::theme).run() }} #[derive(Default)] diff --git a/src/types/rendered_element.rs b/src/types/rendered_element.rs index bd8187e..9639299 100755 --- a/src/types/rendered_element.rs +++ b/src/types/rendered_element.rs @@ -223,7 +223,14 @@ impl RenderedElement { match &self.name { ElementName::Container => { imports = format!("{imports}container,"); - view = format!("{view}\ncontainer({elements}){options}"); + view = format!( + "{view}\ncontainer({}){options}", + if elements.is_empty() { + String::from("\"\"") + } else { + elements.to_string() + } + ); } ElementName::Row => { imports = format!("{imports}row,"); @@ -237,7 +244,7 @@ impl RenderedElement { imports = format!("{imports}text,"); view = format!( "{view}\ntext(\"{}\"){options}", - if *string == String::new() { + if string.is_empty() { "New Text" } else { string @@ -248,7 +255,7 @@ impl RenderedElement { imports = format!("{imports}button,"); view = format!( "{view}\nbutton(\"{}\"){options}", - if *string == String::new() { + if string.is_empty() { "New Button" } else { string -- cgit v1.2.3 From f7274ea5efea2055f8f71d7cde7fc7e2704648cd Mon Sep 17 00:00:00 2001 From: pml68 Date: Fri, 18 Apr 2025 00:54:08 +0200 Subject: refactor: load config in `IcedBuilder::init` instead of `main` --- src/main.rs | 66 +++++++++++++++++++++++++++++++----------------------------- src/types.rs | 2 ++ 2 files changed, 36 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index c7e6314..0f1a1bf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,7 +29,6 @@ use iced_anim::transition::Easing; use iced_anim::{Animated, Animation}; use iced_dialog::dialog::Dialog; use panes::{code_view, designer_view, element_list}; -use tokio::runtime; use types::{ Action, DesignerPane, DialogAction, DialogButtons, Message, Project, }; @@ -46,23 +45,15 @@ fn main() -> Result<(), Box> { return Ok(()); } - let config_load = { - let rt = runtime::Builder::new_current_thread() - .enable_all() - .build()?; - - rt.block_on(Config::load()) - }; - iced::application( - move || App::new(config_load.clone()), - App::update, - App::view, + IcedBuilder::init, + IcedBuilder::update, + IcedBuilder::view, ) - .title(App::title) + .title(IcedBuilder::title) .font(icon::FONT) .theme(|state| state.theme.value().clone()) - .subscription(App::subscription) + .subscription(IcedBuilder::subscription) .antialiasing(true) .centered() .run()?; @@ -70,7 +61,7 @@ fn main() -> Result<(), Box> { Ok(()) } -struct App { +struct IcedBuilder { is_dirty: bool, is_loading: bool, project_path: Option, @@ -94,8 +85,8 @@ enum Panes { ElementList, } -impl App { - fn new(config_load: Result) -> (Self, Task) { +impl IcedBuilder { + fn init() -> (Self, Task) { let state = pane_grid::State::with_configuration( pane_grid::Configuration::Split { axis: pane_grid::Axis::Vertical, @@ -105,22 +96,9 @@ impl App { }, ); - let config = Arc::new(config_load.unwrap_or_default()); + let config = Arc::new(Config::default()); let theme = config.selected_theme(); - let task = if let Some(path) = config.last_project.clone() { - if path.exists() && path.is_file() { - Task::perform(Project::from_path(path), Message::FileOpened) - } else { - warning_dialog(format!( - "The file {} does not exist, or isn't a file.", - path.to_string_lossy() - )) - } - } else { - Task::none() - }; - ( Self { is_dirty: false, @@ -139,7 +117,7 @@ impl App { dialog_action: DialogAction::None, editor_content: text_editor::Content::new(), }, - task, + Task::perform(Config::load(), Message::ConfigLoad), ) } @@ -165,6 +143,30 @@ impl App { fn update(&mut self, message: Message) -> Task { match message { + Message::ConfigLoad(result) => match result { + Ok(config) => { + self.config = Arc::new(config); + + self.theme.update(self.config.selected_theme().into()); + return if let Some(path) = self.config.last_project.clone() + { + if path.exists() && path.is_file() { + Task::perform( + Project::from_path(path), + Message::FileOpened, + ) + } else { + warning_dialog(format!( + "The file {} does not exist, or isn't a file.", + path.to_string_lossy() + )) + } + } else { + Task::none() + }; + } + Err(error) => return error_dialog(error), + }, Message::SwitchTheme(event) => self.theme.update(event), Message::CopyCode => { return clipboard::write(self.editor_content.text()); diff --git a/src/types.rs b/src/types.rs index a7fae1c..adb788e 100644 --- a/src/types.rs +++ b/src/types.rs @@ -12,9 +12,11 @@ pub use project::Project; pub use rendered_element::*; use crate::Error; +use crate::config::Config; #[derive(Debug, Clone)] pub enum Message { + ConfigLoad(Result), SwitchTheme(Event), CopyCode, SwitchPage(DesignerPane), -- cgit v1.2.3 From ec063de6a3cccd6d51bd494573fb0b2c40cfc7a6 Mon Sep 17 00:00:00 2001 From: pml68 Date: Fri, 18 Apr 2025 00:54:37 +0200 Subject: feat(debug): add custom "Code Generation" Comet debug metric --- src/types/project.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/types/project.rs b/src/types/project.rs index 145ab18..91b2bb1 100644 --- a/src/types/project.rs +++ b/src/types/project.rs @@ -83,7 +83,10 @@ impl Project { } pub fn app_code(&mut self) -> Result { - match self.element_tree { + use iced::debug; + let codegen = debug::time("Code Generation"); + + let result = match self.element_tree { Some(ref element_tree) => { let (imports, view) = element_tree.codegen(); let theme = self.get_theme(); @@ -137,6 +140,9 @@ impl State {{ Ok(rustfmt.format_str(app_code)?) } None => Err("No element tree present".into()), - } + }; + + codegen.finish(); + result } } -- cgit v1.2.3 From bbecf293208ba61bb3d57d57afd7373797007bfe Mon Sep 17 00:00:00 2001 From: pml68 Date: Sun, 20 Apr 2025 01:05:54 +0200 Subject: feat: use `pane_grid::Controls` for PaneGrid titlebar controls --- fonts/icons.toml | 1 + fonts/icons.ttf | Bin 6348 -> 6504 bytes src/icon.rs | 6 +++++- src/panes/code_view.rs | 49 +++++++++++++++++++++++++++++---------------- src/panes/designer_view.rs | 29 ++++++++++++++++++--------- 5 files changed, 57 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/fonts/icons.toml b/fonts/icons.toml index a70c0e7..3092001 100644 --- a/fonts/icons.toml +++ b/fonts/icons.toml @@ -4,3 +4,4 @@ module = "icon" save = "entypo-floppy" open = "fontawesome-folder-open-empty" copy = "fontawesome-file-code" +switch = "entypo-switch" diff --git a/fonts/icons.ttf b/fonts/icons.ttf index 7af6b0e..e1aba57 100644 Binary files a/fonts/icons.ttf and b/fonts/icons.ttf differ diff --git a/src/icon.rs b/src/icon.rs index 9dc0a89..3fbeb83 100644 --- a/src/icon.rs +++ b/src/icon.rs @@ -1,6 +1,6 @@ // Generated automatically by iced_fontello at build time. // Do not edit manually. Source: ../fonts/icons.toml -// 02c7558d187cdc056fdd0e6a638ef805fa10f5955f834575e51d75acd35bc70e +// 915ea6b0646871c0f04350f201f27f28881b61f3bd6ef292a415d67a211739c1 use iced::widget::{text, Text}; use iced::Font; @@ -18,6 +18,10 @@ pub fn save<'a>() -> Text<'a> { icon("\u{1F4BE}") } +pub fn switch<'a>() -> Text<'a> { + icon("\u{21C6}") +} + fn icon(codepoint: &str) -> Text<'_> { text(codepoint).font(Font::with_name("icons")) } diff --git a/src/panes/code_view.rs b/src/panes/code_view.rs index 551347c..85b0bbe 100644 --- a/src/panes/code_view.rs +++ b/src/panes/code_view.rs @@ -22,25 +22,40 @@ pub fn view( editor_content: &text_editor::Content, is_focused: bool, ) -> pane_grid::Content<'_, Message> { - let title = row![ - text("Generated Code"), - Space::with_width(Length::Fill), - tip( - button(icon::copy()) - .on_press(Message::CopyCode) - .padding([2, 7]) - .style(button::text), - "Copy", - tip::Position::FollowCursor - ), - Space::with_width(20), - button("Switch to Designer view") - .on_press(Message::SwitchPage(DesignerPane::DesignerView)) - ] - .align_y(Alignment::Center); - let title_bar = pane_grid::TitleBar::new(title) + let title_bar = pane_grid::TitleBar::new(text("Generated Code").center()) + .controls(pane_grid::Controls::dynamic( + row![ + tip( + button(icon::copy()) + .on_press(Message::CopyCode) + .padding([2, 7]) + .style(button::text), + "Copy", + tip::Position::FollowCursor + ), + Space::with_width(20), + button("Switch to Designer view") + .on_press(Message::SwitchPage(DesignerPane::DesignerView)) + ] + .align_y(Alignment::Center), + row![ + tip( + button(icon::copy()) + .on_press(Message::CopyCode) + .padding([2, 7]) + .style(button::text), + "Copy", + tip::Position::FollowCursor + ), + Space::with_width(20), + button(icon::switch()) + .on_press(Message::SwitchPage(DesignerPane::DesignerView)) + ] + .align_y(Alignment::Center), + )) .padding(10) .style(style::title_bar); + pane_grid::Content::new( text_editor(editor_content) .on_action(Message::EditorAction) diff --git a/src/panes/designer_view.rs b/src/panes/designer_view.rs index 69ff750..af72022 100644 --- a/src/panes/designer_view.rs +++ b/src/panes/designer_view.rs @@ -1,9 +1,10 @@ use iced::widget::{ - Space, button, center, container, pane_grid, responsive, row, text, themer, + button, center, container, pane_grid, responsive, row, text, themer, }; use iced::{Alignment, Element, Length}; use super::style; +use crate::icon; use crate::types::{DesignerPane, Message, RenderedElement}; pub fn view<'a>( @@ -24,22 +25,30 @@ pub fn view<'a>( .into() }) .into(), - None => text("Open a project or begin creating one").into(), + None => center("Open a project or begin creating one").into(), }; + let content = container(themer(designer_theme, el_tree)) .id(iced::widget::container::Id::new("drop_zone")) .height(Length::Fill) .width(Length::Fill); - let title = row![ - text("Designer"), - Space::with_width(Length::Fill), - button("Switch to Code view") - .on_press(Message::SwitchPage(DesignerPane::CodeView)), - ] - .align_y(Alignment::Center); - let title_bar = pane_grid::TitleBar::new(title) + + let title_bar = pane_grid::TitleBar::new(text("Designer").center()) + .controls(pane_grid::Controls::dynamic( + row![ + button("Switch to Code view") + .on_press(Message::SwitchPage(DesignerPane::CodeView),) + ] + .align_y(Alignment::Center), + row![ + button(icon::switch()) + .on_press(Message::SwitchPage(DesignerPane::CodeView),) + ] + .align_y(Alignment::Center), + )) .padding(10) .style(style::title_bar); + pane_grid::Content::new(content) .title_bar(title_bar) .style(if is_focused { -- cgit v1.2.3 From c3c05cef555de305729e53cef8b8e660e31eaf27 Mon Sep 17 00:00:00 2001 From: pml68 Date: Tue, 22 Apr 2025 14:33:36 +0200 Subject: refactor: apply some clippy suggestions --- Cargo.lock | 99 ++++++++++++++++------------------- crates/material_theme/src/button.rs | 4 +- crates/material_theme/src/checkbox.rs | 6 +-- crates/material_theme/src/lib.rs | 5 +- crates/material_theme/src/utils.rs | 6 ++- src/panes/code_view.rs | 2 +- 6 files changed, 59 insertions(+), 63 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 4f0a992..fd31403 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -534,11 +534,11 @@ dependencies = [ [[package]] name = "block2" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d59b4c170e16f0405a2e95aff44432a0d41aa97675f3d52623effe95792a037" +checksum = "340d2f0bdb2a43c1d3cd40513185b2bd7def0aa1052f956455114bc98f82dcf2" dependencies = [ - "objc2 0.6.0", + "objc2 0.6.1", ] [[package]] @@ -1070,9 +1070,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a0d569e003ff27784e0e14e4a594048698e0c0f0b66cabcb51511be55a7caa0" dependencies = [ "bitflags 2.9.0", - "block2 0.6.0", + "block2 0.6.1", "libc", - "objc2 0.6.0", + "objc2 0.6.1", +] + +[[package]] +name = "dispatch2" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec" +dependencies = [ + "bitflags 2.9.0", + "objc2 0.6.1", ] [[package]] @@ -1160,20 +1170,6 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" -[[package]] -name = "embed-resource" -version = "2.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b68b6f9f63a0b6a38bc447d4ce84e2b388f3ec95c99c641c8ff0dd3ef89a6379" -dependencies = [ - "cc", - "memchr", - "rustc_version", - "toml", - "vswhom", - "winreg", -] - [[package]] name = "embed-resource" version = "3.0.2" @@ -1997,7 +1993,7 @@ name = "iced_builder" version = "0.1.0" dependencies = [ "dirs-next", - "embed-resource 3.0.2", + "embed-resource", "fxhash", "iced", "iced_anim", @@ -2611,9 +2607,9 @@ dependencies = [ [[package]] name = "libm" -version = "0.2.11" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" +checksum = "c9627da5196e5d8ed0b0495e61e518847578da83483c37288316d9b2e03a7f72" [[package]] name = "libredox" @@ -2675,12 +2671,6 @@ dependencies = [ "scopeguard", ] -[[package]] -name = "lockfree-object-pool" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9374ef4228402d4b7e403e5838cb880d9ee663314b0a900d5a6aabf0c213552e" - [[package]] name = "log" version = "0.4.27" @@ -3124,9 +3114,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3531f65190d9cff863b77a99857e74c314dd16bf56c538c4b57c7cbc3f3a6e59" +checksum = "88c6597e14493ab2e44ce58f2fdecf095a51f12ca57bec060a11c57332520551" dependencies = [ "objc2-encode", ] @@ -3149,14 +3139,14 @@ dependencies = [ [[package]] name = "objc2-app-kit" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5906f93257178e2f7ae069efb89fbd6ee94f0592740b5f8a1512ca498814d0fb" +checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc" dependencies = [ "bitflags 2.9.0", - "block2 0.6.0", - "objc2 0.6.0", - "objc2-foundation 0.3.0", + "block2 0.6.1", + "objc2 0.6.1", + "objc2-foundation 0.3.1", ] [[package]] @@ -3197,12 +3187,13 @@ dependencies = [ [[package]] name = "objc2-core-foundation" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daeaf60f25471d26948a1c2f840e3f7d86f4109e3af4e8e4b5cd70c39690d925" +checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166" dependencies = [ "bitflags 2.9.0", - "objc2 0.6.0", + "dispatch2 0.3.0", + "objc2 0.6.1", ] [[package]] @@ -3250,12 +3241,12 @@ dependencies = [ [[package]] name = "objc2-foundation" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a21c6c9014b82c39515db5b396f91645182611c97d24637cf56ac01e5f8d998" +checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c" dependencies = [ "bitflags 2.9.0", - "objc2 0.6.0", + "objc2 0.6.1", "objc2-core-foundation", ] @@ -4035,14 +4026,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80c844748fdc82aae252ee4594a89b6e7ebef1063de7951545564cbc4e57075d" dependencies = [ "ashpd 0.11.0", - "block2 0.6.0", - "dispatch2", + "block2 0.6.1", + "dispatch2 0.2.0", "js-sys", "log", - "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2 0.6.1", + "objc2-app-kit 0.3.1", "objc2-core-foundation", - "objc2-foundation 0.3.0", + "objc2-foundation 0.3.1", "pollster", "raw-window-handle", "urlencoding", @@ -4383,9 +4374,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.2" +version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" dependencies = [ "libc", ] @@ -5952,12 +5943,12 @@ checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" [[package]] name = "windows_exe_info" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0960cd3c8e7c1a55327ac8206395748c8145dc56c524057d1d50ab80300f49f" +checksum = "3a7c2cd292e8e58e012eaf18f18f6b64ef74e0b90677b4f9e1f15bfca24056c7" dependencies = [ "camino", - "embed-resource 2.5.1", + "embed-resource", ] [[package]] @@ -6515,15 +6506,13 @@ dependencies = [ [[package]] name = "zopfli" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5019f391bac5cf252e93bbcc53d039ffd62c7bfb7c150414d61369afe57e946" +checksum = "edfc5ee405f504cd4984ecc6f14d02d55cfda60fa4b689434ef4102aae150cd7" dependencies = [ "bumpalo", "crc32fast", - "lockfree-object-pool", "log", - "once_cell", "simd-adler32", ] diff --git a/crates/material_theme/src/button.rs b/crates/material_theme/src/button.rs index 21d77b7..e1369eb 100644 --- a/crates/material_theme/src/button.rs +++ b/crates/material_theme/src/button.rs @@ -143,7 +143,7 @@ pub fn outlined(theme: &Theme, status: Status) -> Style { Status::Active | Status::Pressed | Status::Hovered => Border { color: outline, width: 1.0, - radius: 400.0.into(), + radius: 400.into(), }, Status::Disabled => Border { color: Color { @@ -151,7 +151,7 @@ pub fn outlined(theme: &Theme, status: Status) -> Style { ..disabled }, width: 1.0, - radius: 400.0.into(), + radius: 400.into(), }, }; diff --git a/crates/material_theme/src/checkbox.rs b/crates/material_theme/src/checkbox.rs index ac1f974..ff038b0 100644 --- a/crates/material_theme/src/checkbox.rs +++ b/crates/material_theme/src/checkbox.rs @@ -18,7 +18,7 @@ impl Catalog for Theme { pub fn styled( background_color: Color, - background_hover: Option, + background_unchecked: Option, icon_color: Color, border_color: Color, text_color: Option, @@ -28,7 +28,7 @@ pub fn styled( background: Background::Color(if is_checked { background_color } else { - background_hover.unwrap_or(Color::TRANSPARENT) + background_unchecked.unwrap_or(Color::TRANSPARENT) }), icon_color, border: if is_checked { @@ -37,7 +37,7 @@ pub fn styled( Border { color: border_color, width: 2.0, - radius: border::radius(2), + radius: 2.into(), } }, text_color, diff --git a/crates/material_theme/src/lib.rs b/crates/material_theme/src/lib.rs index 416c958..13f13b1 100644 --- a/crates/material_theme/src/lib.rs +++ b/crates/material_theme/src/lib.rs @@ -24,6 +24,7 @@ pub mod slider; #[cfg(feature = "svg")] pub mod svg; pub mod text; +pub mod text_editor; pub mod text_input; pub mod toggler; pub mod utils; @@ -59,7 +60,7 @@ impl Clone for Theme { } fn clone_from(&mut self, source: &Self) { - self.name = source.name.clone(); + self.name.clone_from(&source.name); self.colorscheme = source.colorscheme; } } @@ -142,6 +143,7 @@ pub struct ColorScheme { pub scrim: Color, } +#[allow(clippy::cast_precision_loss)] macro_rules! from_argb { ($hex:expr) => {{ let hex = $hex as u32; @@ -155,6 +157,7 @@ macro_rules! from_argb { }}; } +#[allow(clippy::cast_precision_loss)] impl ColorScheme { const DARK: Self = Self { primary: Primary { diff --git a/crates/material_theme/src/utils.rs b/crates/material_theme/src/utils.rs index f35396f..5ad137e 100644 --- a/crates/material_theme/src/utils.rs +++ b/crates/material_theme/src/utils.rs @@ -1,5 +1,7 @@ use iced_widget::core::{Color, Shadow, Vector}; +const COLOR_ERROR_MARGIN: f32 = 0.0001; + pub const HOVERED_LAYER_OPACITY: f32 = 0.08; pub const PRESSED_LAYER_OPACITY: f32 = 0.1; @@ -95,7 +97,9 @@ pub fn mix(color1: Color, color2: Color, p2: f32) -> Color { let p1 = 1.0 - p2; - if color1.a != 1.0 || color2.a != 1.0 { + if (color1.a - 1.0).abs() > COLOR_ERROR_MARGIN + || (color2.a - 1.0) > COLOR_ERROR_MARGIN + { let a = color1.a * p1 + color2.a * p2; if a > 0.0 { let c1 = color1.into_linear().map(|c| c * color1.a * p1); diff --git a/src/panes/code_view.rs b/src/panes/code_view.rs index 85b0bbe..890af8a 100644 --- a/src/panes/code_view.rs +++ b/src/panes/code_view.rs @@ -71,7 +71,7 @@ pub fn view( palette.background.base.color, ), border: Border { - radius: 2.0.into(), + radius: 2.into(), width: 1.0, color: palette.background.strong.color, }, -- cgit v1.2.3 From f9f854f124d4676e8c79adeda6bfaceba586805f Mon Sep 17 00:00:00 2001 From: pml68 Date: Fri, 25 Apr 2025 11:30:46 +0200 Subject: feat(material_theme): create an iced `Palette` for `iced::theme::Base` impl --- Cargo.toml | 3 ++- crates/material_theme/src/lib.rs | 44 +++++++++++++++++++++++++--------------- src/main.rs | 2 +- theme_test/Cargo.toml | 1 + 4 files changed, 32 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/Cargo.toml b/Cargo.toml index a4abf56..0a7d769 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,8 @@ toml = "0.8.20" [workspace.dependencies.iced] git = "https://github.com/pml68/iced" branch = "feat/rehighlight-on-redraw" -features = ["image", "svg", "advanced", "tokio", "lazy"] +default-features = false +features = ["wgpu", "tiny-skia", "web-colors", "auto-detect-theme", "image", "svg", "advanced", "tokio", "lazy"] [build-dependencies] iced_fontello = "0.13.2" diff --git a/crates/material_theme/src/lib.rs b/crates/material_theme/src/lib.rs index 25b6a9c..569b06c 100644 --- a/crates/material_theme/src/lib.rs +++ b/crates/material_theme/src/lib.rs @@ -29,6 +29,20 @@ pub mod text_input; pub mod toggler; pub mod utils; +#[allow(clippy::cast_precision_loss)] +macro_rules! from_argb { + ($hex:expr) => {{ + let hex = $hex as u32; + + let a = ((hex & 0xff000000) >> 24) as f32 / 255.0; + let r = (hex & 0x00ff0000) >> 16; + let g = (hex & 0x0000ff00) >> 8; + let b = (hex & 0x000000ff); + + ::iced_widget::core::color!(r as u8, g as u8, b as u8, a) + }}; +} + #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Theme { @@ -89,8 +103,20 @@ impl Base for Theme { } fn palette(&self) -> Option { - // TODO: create a Palette - None + let colors = self.colorscheme; + + Some(iced_widget::theme::Palette { + background: colors.surface.color, + text: colors.surface.on_surface, + primary: colors.primary.color, + success: colors.primary.primary_container, + warning: utils::mix( + from_argb!(0xffffff00), + colors.primary.color, + 0.25, + ), + danger: colors.error.color, + }) } } @@ -133,20 +159,6 @@ pub struct ColorScheme { pub scrim: Color, } -#[allow(clippy::cast_precision_loss)] -macro_rules! from_argb { - ($hex:expr) => {{ - let hex = $hex as u32; - - let a = ((hex & 0xff000000) >> 24) as f32 / 255.0; - let r = (hex & 0x00ff0000) >> 16; - let g = (hex & 0x0000ff00) >> 8; - let b = (hex & 0x000000ff); - - ::iced_widget::core::color!(r as u8, g as u8, b as u8, a) - }}; -} - #[allow(clippy::cast_precision_loss)] impl ColorScheme { const DARK: Self = Self { diff --git a/src/main.rs b/src/main.rs index 0f1a1bf..5014077 100644 --- a/src/main.rs +++ b/src/main.rs @@ -146,8 +146,8 @@ impl IcedBuilder { Message::ConfigLoad(result) => match result { Ok(config) => { self.config = Arc::new(config); - self.theme.update(self.config.selected_theme().into()); + return if let Some(path) = self.config.last_project.clone() { if path.exists() && path.is_file() { diff --git a/theme_test/Cargo.toml b/theme_test/Cargo.toml index 29fcdc8..300a7af 100644 --- a/theme_test/Cargo.toml +++ b/theme_test/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] iced.workspace = true +iced.features = ["debug"] iced_anim.workspace = true iced_dialog.workspace = true material_theme = { path = "../crates/material_theme", features = ["dialog", "animate"] } -- cgit v1.2.3 From 9dfb469d1ba975e59f39f3bb799b019204315784 Mon Sep 17 00:00:00 2001 From: pml68 Date: Mon, 28 Apr 2025 10:57:42 +0200 Subject: feat: switch to modified `iced_fontello` for custom Theme support --- Cargo.lock | 10 +- Cargo.toml | 8 +- crates/iced_fontello/.gitignore | 2 + crates/iced_fontello/Cargo.toml | 18 ++ crates/iced_fontello/README.md | 109 +++++++++++ crates/iced_fontello/src/lib.rs | 394 ++++++++++++++++++++++++++++++++++++++++ src/icon.rs | 4 +- 7 files changed, 534 insertions(+), 11 deletions(-) create mode 100644 crates/iced_fontello/.gitignore create mode 100644 crates/iced_fontello/Cargo.toml create mode 100644 crates/iced_fontello/README.md create mode 100644 crates/iced_fontello/src/lib.rs (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 9154eb4..02b475d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2082,8 +2082,6 @@ dependencies = [ [[package]] name = "iced_fontello" version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1088f296a44a5c7e51ae5e533954429bfa479d44b304cb7c370480994abab7ef" dependencies = [ "reqwest", "serde", @@ -3737,9 +3735,9 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" [[package]] name = "quick-xml" -version = "0.37.4" +version = "0.37.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4ce8c88de324ff838700f36fb6ab86c96df0e3c4ab6ef3a9b2044465cce1369" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" dependencies = [ "memchr", ] @@ -4619,9 +4617,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.100" +version = "2.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 0a7d769..9ffaa5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ iced_anim.workspace = true iced_custom_highlighter = { git = "https://github.com/pml68/iced_custom_highlighter", branch = "master" } iced_drop = { path = "crates/iced_drop" } iced_dialog.workspace = true -material_theme = { path = "crates/material_theme" } +material_theme = { path = "crates/material_theme", features = ["animate", "serde", "dialog", "image", "svg"] } serde.workspace = true serde_json = "1.0.140" toml.workspace = true @@ -38,16 +38,16 @@ dirs-next = "2.0.0" iced_anim = { version = "0.2.1", features = ["derive"] } iced_dialog = { git = "https://github.com/pml68/iced_dialog", branch = "iced/personal" } serde = { version = "1.0.219", features = ["derive"] } -toml = "0.8.20" +toml = "0.8.21" [workspace.dependencies.iced] git = "https://github.com/pml68/iced" branch = "feat/rehighlight-on-redraw" default-features = false -features = ["wgpu", "tiny-skia", "web-colors", "auto-detect-theme", "image", "svg", "advanced", "tokio", "lazy"] +features = ["wgpu", "tiny-skia", "web-colors", "auto-detect-theme", "advanced", "tokio", "image", "svg", "lazy"] [build-dependencies] -iced_fontello = "0.13.2" +iced_fontello = { path = "crates/iced_fontello" } [target.'cfg(target_os = "macos")'.dependencies] xdg = "2.5.2" diff --git a/crates/iced_fontello/.gitignore b/crates/iced_fontello/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/crates/iced_fontello/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/crates/iced_fontello/Cargo.toml b/crates/iced_fontello/Cargo.toml new file mode 100644 index 0000000..8c170a1 --- /dev/null +++ b/crates/iced_fontello/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "iced_fontello" +version = "0.13.2" +edition = "2021" +description = "Generate type-safe icon fonts for `iced` at compile time" +repository = "https://github.com/hecrj/iced_fontello" +license = "MIT" +categories = ["gui"] +keywords = ["gui", "ui", "graphics", "interface", "widgets"] +rust-version = "1.85" + +[dependencies] +reqwest = { version = "0.12", features = ["blocking", "json", "multipart"] } +sha2 = "0.10" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8" +zip = "2" diff --git a/crates/iced_fontello/README.md b/crates/iced_fontello/README.md new file mode 100644 index 0000000..52a59c1 --- /dev/null +++ b/crates/iced_fontello/README.md @@ -0,0 +1,109 @@ +
+ +# iced_fontello + +[![Documentation](https://docs.rs/iced_fontello/badge.svg)](https://docs.rs/iced_fontello) +[![Crates.io](https://img.shields.io/crates/v/iced_fontello.svg)](https://crates.io/crates/iced_fontello) +[![License](https://img.shields.io/crates/l/iced_fontello.svg)](https://github.com/hecrj/iced_fontello/blob/master/LICENSE) +[![Downloads](https://img.shields.io/crates/d/iced_fontello.svg)](https://crates.io/crates/iced_fontello) +[![Test Status](https://img.shields.io/github/actions/workflow/status/hecrj/iced_fontello/test.yml?branch=master&event=push&label=test)](https://github.com/hecrj/iced_fontello/actions) +[![Discourse](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscourse.iced.rs%2Fsite%2Fstatistics.json&query=%24.users_count&suffix=%20users&label=discourse&color=5e7ce2)](https://discourse.iced.rs/) +[![Discord Server](https://img.shields.io/discord/628993209984614400?label=&labelColor=6A7EC2&logo=discord&logoColor=ffffff&color=7389D8)](https://discord.gg/3xZJ65GAhd) + +A compile-time, type-safe icon font generator for [`iced`]. +Powered by [Fontello]. + +[`iced`]: https://github.com/iced-rs/iced +[Fontello]: https://github.com/fontello/fontello + +
+ +## Usage +Create a `.toml` file somewhere in your crate with the font definition: + +```toml +# fonts/example-icons.toml +module = "icon" + +[glyphs] +edit = "fontawesome-pencil" +save = "entypo-floppy" +trash = "typicons-trash" +``` + +The `module` value defines the Rust module that will be generated in your `src` +directory containing a type-safe API to use the font. + +Each entry in the `[glyphs]` section corresponds to an icon. The keys will be +used as names for the functions of the module of the font; while the values +specify the glyph for that key using the format: `-`. You can browse +the available glyphs in [Fontello] or [the `fonts.json` file](fonts.json). + +Next, add `iced_fontello` to your `build-dependencies`: + +```rust +[build-dependencies] +iced_fontello = "0.13" +``` + +Then, call `iced_fontello::build` in your [build script](https://doc.rust-lang.org/cargo/reference/build-scripts.html), +passing the path of your font definition: + +```rust +pub fn main() { + println!("cargo::rerun-if-changed=fonts/example-icons.toml"); + iced_fontello::build("fonts/example-icons.toml").expect("Build example-icons font"); +} +``` + +The library will generate the font and save its `.ttf` file right next to its definition. +In this example, the library would generate `fonts/example-icons.ttf`. + +Finally, it will generate a type-safe `iced` API that lets you use the font. In our example: + +```rust +// Generated automatically by iced_fontello at build time. +// Do not edit manually. +// d24460a00249b2acd0ccc64c3176452c546ad12d1038974e974d7bdb4cdb4a8f +use iced::widget::{text, Text}; +use iced::Font; + +pub const FONT: &[u8] = include_bytes!("../fonts/example-icons.ttf"); + +pub fn edit<'a>() -> Text<'a> { + icon("\u{270E}") +} + +pub fn save<'a>() -> Text<'a> { + icon("\u{1F4BE}") +} + +pub fn trash<'a>() -> Text<'a> { + icon("\u{E10A}") +} + +fn icon<'a>(codepoint: &'a str) -> Text<'a> { + text(codepoint).font(Font::with_name("example-icons")) +} +``` + +Now you can simply add `mod icon;` to your `lib.rs` or `main.rs` file and enjoy your new font: + +```rust +mod icon; + +use iced::widget::row; + +// ... + +row![icon::edit(), icon::save(), icon::trash()].spacing(10) + +// ... +``` + +Check out [the full example](example) to see it all in action. + +## Packaging +If you plan to package your crate, you must make sure you include the generated module +and font file in the final package. `build` is effectively a no-op when the module and +the font already exist and are up-to-date. diff --git a/crates/iced_fontello/src/lib.rs b/crates/iced_fontello/src/lib.rs new file mode 100644 index 0000000..2b39647 --- /dev/null +++ b/crates/iced_fontello/src/lib.rs @@ -0,0 +1,394 @@ +#![allow(clippy::needless_doctest_main)] +//! A compile-time, type-safe icon font generator for [`iced`]. +//! Powered by [Fontello]. +//! +//! [`iced`]: https://github.com/iced-rs/iced +//! [Fontello]: https://github.com/fontello/fontello +//! +//! # Usage +//! Create a `.toml` file somewhere in your crate with the font definition: +//! +//! ```toml +//! # fonts/example-icons.toml +//! module = "icon" +//! +//! [glyphs] +//! edit = "fontawesome-pencil" +//! save = "entypo-floppy" +//! trash = "typicons-trash" +//! ``` +//! +//! The `module` value defines the Rust module that will be generated in your `src` +//! directory containing a type-safe API to use the font. +//! +//! Each entry in the `[glyphs]` section corresponds to an icon. The keys will be +//! used as names for the functions of the module of the font; while the values +//! specify the glyph for that key using the format: `-`. You can browse +//! the available glyphs in [Fontello] or [the `fonts.json` file](fonts.json). +//! +//! Next, add `iced_fontello` to your `build-dependencies`: +//! +//! ```toml +//! [build-dependencies] +//! iced_fontello = "0.13" +//! ``` +//! +//! Then, call `iced_fontello::build` in your [build script](https://doc.rust-lang.org/cargo/reference/build-scripts.html), +//! passing the path of your font definition: +//! +//! ```rust,no_run +//! pub fn main() { +//! println!("cargo::rerun-if-changed=fonts/example-icons.toml"); +//! iced_fontello::build("fonts/example-icons.toml").expect("Build example-icons font"); +//! } +//! ``` +//! +//! The library will generate the font and save its `.ttf` file right next to its definition. +//! In this example, the library would generate `fonts/example-icons.ttf`. +//! +//! Finally, it will generate a type-safe `iced` API that lets you use the font. In our example: +//! +//! ```rust,ignore +//! // Generated automatically by iced_fontello at build time. +//! // Do not edit manually. +//! // d24460a00249b2acd0ccc64c3176452c546ad12d1038974e974d7bdb4cdb4a8f +//! use iced::widget::{text, Text}; +//! use iced::Font; +//! +//! pub const FONT: &[u8] = include_bytes!("../fonts/example-icons.ttf"); +//! +//! pub fn edit<'a>() -> Text<'a> { +//! icon("\u{270E}") +//! } +//! +//! pub fn save<'a>() -> Text<'a> { +//! icon("\u{1F4BE}") +//! } +//! +//! pub fn trash<'a>() -> Text<'a> { +//! icon("\u{E10A}") +//! } +//! +//! fn icon<'a>(codepoint: &'a str) -> Text<'a> { +//! text(codepoint).font(Font::with_name("example-icons")) +//! } +//! ``` +//! +//! Now you can simply add `mod icon;` to your `lib.rs` or `main.rs` file and enjoy your new font: +//! +//! ```rust,ignore +//! mod icon; +//! +//! use iced::widget::row; +//! +//! // ... +//! +//! row![icon::edit(), icon::save(), icon::trash()].spacing(10) +//! +//! // ... +//! ``` +//! +//! Check out [the full example](example) to see it all in action. +//! +//! # Packaging +//! If you plan to package your crate, you must make sure you include the generated module +//! and font file in the final package. `build` is effectively a no-op when the module and +//! the font already exist and are up-to-date. +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::{fs, io}; + +use reqwest::blocking as reqwest; +use serde::{Deserialize, Serialize}; + +pub fn build(path: impl AsRef) -> Result<(), Error> { + let path = path.as_ref(); + + let definition: Definition = { + let contents = fs::read_to_string(path).unwrap_or_else(|error| { + panic!( + "Font definition {path} could not be read: {error}", + path = path.display() + ) + }); + + toml::from_str(&contents).unwrap_or_else(|error| { + panic!( + "Font definition {path} is invalid: {error}", + path = path.display() + ) + }) + }; + + let fonts = parse_fonts(); + + let glyphs: BTreeMap = definition + .glyphs + .into_iter() + .map(|(name, id)| { + let Some((font_name, glyph)) = id.split_once('-') else { + panic!( + "Invalid glyph identifier: \"{id}\"\n\ + Glyph identifier must have \"-\" format" + ) + }; + + let Some(font) = fonts.get(font_name) else { + panic!( + "Font \"{font_name}\" was not found. Available fonts are:\n{}", + fonts + .keys() + .map(|name| format!("- {name}")) + .collect::>() + .join("\n") + ); + }; + + let Some(glyph) = font.glyphs.get(glyph) else { + // TODO: Display similarly named candidates + panic!( + "Glyph \"{glyph}\" was not found. Available glyphs are:\n{}", + font.glyphs + .keys() + .map(|name| format!("- {name}")) + .collect::>() + .join("\n") + ); + }; + + ( + name, + ChosenGlyph { + uid: glyph.uid.clone(), + css: glyph.name.clone(), + code: glyph.code, + src: font.name.clone(), + }, + ) + }) + .collect(); + + #[derive(Serialize)] + struct Config { + name: String, + css_prefix_text: &'static str, + css_use_suffix: bool, + hinting: bool, + units_per_em: u32, + ascent: u32, + glyphs: Vec, + } + + #[derive(Clone, Serialize)] + struct ChosenGlyph { + uid: Id, + css: String, + code: u64, + src: String, + } + + let file_name = path + .file_stem() + .expect("Get file stem from definition path") + .to_string_lossy() + .into_owned(); + + let config = Config { + name: file_name.clone(), + css_prefix_text: "icon-", + css_use_suffix: false, + hinting: true, + units_per_em: 1000, + ascent: 850, + glyphs: glyphs.values().cloned().collect(), + }; + + let hash = { + use sha2::Digest as _; + + let mut hasher = sha2::Sha256::new(); + hasher.update( + serde_json::to_string(&config).expect("Serialize config as JSON"), + ); + + format!("{:x}", hasher.finalize()) + }; + + let module_target = PathBuf::new() + .join("src") + .join(definition.module.replace("::", "/")) + .with_extension("rs"); + + let module_contents = + fs::read_to_string(&module_target).unwrap_or_default(); + let module_hash = module_contents + .lines() + .nth(2) + .unwrap_or_default() + .trim_start_matches("// "); + + if hash != module_hash || !path.with_extension("ttf").exists() { + let client = reqwest::Client::new(); + let session = client + .post("https://fontello.com/") + .multipart( + reqwest::multipart::Form::new().part( + "config", + reqwest::multipart::Part::text( + serde_json::to_string(&config) + .expect("Serialize Fontello config"), + ) + .file_name("config.json"), + ), + ) + .send() + .and_then(reqwest::Response::error_for_status) + .and_then(reqwest::Response::text) + .expect("Create Fontello session"); + + let font = client + .get(format!("https://fontello.com/{session}/get")) + .send() + .and_then(reqwest::Response::error_for_status) + .and_then(reqwest::Response::bytes) + .expect("Download Fontello font"); + + let mut archive = zip::ZipArchive::new(io::Cursor::new(font)) + .expect("Parse compressed font"); + + let mut font_file = (0..archive.len()) + .find(|i| { + let file = + archive.by_index(*i).expect("Access zip archive by index"); + + file.name().ends_with(&format!("{file_name}.ttf")) + }) + .and_then(|i| archive.by_index(i).ok()) + .expect("Find font file in zipped archive"); + + io::copy( + &mut font_file, + &mut fs::File::create(path.with_extension("ttf")) + .expect("Create font file"), + ) + .expect("Extract font file"); + } + + let relative_path = PathBuf::from( + std::iter::repeat("../") + .take(definition.module.split("::").count()) + .collect::(), + ); + + let mut module = String::new(); + + module.push_str(&format!( + "// Generated automatically by iced_fontello at build time.\n\ + // Do not edit manually. Source: {source}\n\ + // {hash}\n\ + use iced::Font;\n\ + use iced::widget::text;\n\n\ + use crate::widget::Text;\n\n\ + pub const FONT: &[u8] = include_bytes!(\"{path}\");\n\n", + source = relative_path.join(path.with_extension("toml")).display(), + path = relative_path.join(path.with_extension("ttf")).display() + )); + + for (name, glyph) in glyphs { + module.push_str(&format!( + "\ +pub fn {name}<'a>() -> Text<'a> {{ + icon(\"\\u{{{code:X}}}\") +}}\n\n", + code = glyph.code + )); + } + + module.push_str(&format!( + "\ +fn icon(codepoint: &str) -> Text<'_> {{ + text(codepoint).font(Font::with_name(\"{file_name}\")) +}}\n" + )); + + if module != module_contents { + if let Some(directory) = module_target.parent() { + fs::create_dir_all(directory) + .expect("Create parent directory of font module"); + } + + fs::write(module_target, module).expect("Write font module"); + } + + Ok(()) +} + +#[derive(Debug, Clone)] +pub enum Error {} + +#[derive(Debug, Clone, Deserialize)] +struct Definition { + module: String, + glyphs: BTreeMap, +} + +#[derive(Debug, Clone)] +struct Font { + name: String, + glyphs: BTreeMap, +} + +#[derive(Debug, Clone, Deserialize)] +struct Glyph { + uid: Id, + code: u64, + #[serde(rename = "css")] + name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +struct Id(String); + +fn parse_fonts() -> BTreeMap { + #[derive(Deserialize)] + struct ItemSchema { + font: FontSchema, + glyphs: Vec, + } + + #[derive(Deserialize)] + struct FontSchema { + fontname: String, + } + + let items: Vec = + serde_json::from_str(include_str!("../fonts.json")) + .expect("Deserialize fonts"); + + items + .into_iter() + .map(|item| { + ( + item.font.fontname.clone(), + Font { + name: item.font.fontname, + glyphs: item + .glyphs + .into_iter() + .map(|glyph| (glyph.name.clone(), glyph)) + .collect(), + }, + ) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_parses_fonts() { + assert!(!parse_fonts().is_empty()); + } +} diff --git a/src/icon.rs b/src/icon.rs index 3fbeb83..d218943 100644 --- a/src/icon.rs +++ b/src/icon.rs @@ -1,8 +1,10 @@ // Generated automatically by iced_fontello at build time. // Do not edit manually. Source: ../fonts/icons.toml // 915ea6b0646871c0f04350f201f27f28881b61f3bd6ef292a415d67a211739c1 -use iced::widget::{text, Text}; use iced::Font; +use iced::widget::text; + +use crate::widget::Text; pub const FONT: &[u8] = include_bytes!("../fonts/icons.ttf"); -- cgit v1.2.3 From e17ce59fa4c907511f38795c342b2232a7bba26d Mon Sep 17 00:00:00 2001 From: pml68 Date: Mon, 28 Apr 2025 10:59:52 +0200 Subject: feat: switch to fully custom, Material3-based theme --- assets/themes/rose_pine.toml | 41 ----- src/appearance.rs | 46 ++++++ src/config.rs | 41 +++-- src/dialogs.rs | 4 +- src/main.rs | 23 ++- src/options.rs | 2 +- src/panes/code_view.rs | 46 +++--- src/panes/designer_view.rs | 7 +- src/panes/element_list.rs | 7 +- src/panes/style.rs | 23 +-- src/theme.rs | 357 ------------------------------------------ src/types.rs | 6 +- src/types/project.rs | 18 +-- src/types/rendered_element.rs | 30 +--- src/widget.rs | 18 ++- theme_test/src/main.rs | 2 +- 16 files changed, 155 insertions(+), 516 deletions(-) delete mode 100644 assets/themes/rose_pine.toml create mode 100644 src/appearance.rs delete mode 100644 src/theme.rs (limited to 'src') diff --git a/assets/themes/rose_pine.toml b/assets/themes/rose_pine.toml deleted file mode 100644 index e4540fb..0000000 --- a/assets/themes/rose_pine.toml +++ /dev/null @@ -1,41 +0,0 @@ -name = "Rosé Pine" - -dark = true - -[palette] -background = "#26233a" -text = "#e0def4" -primary = "#9ccfd8" -success = "#f6c177" -danger = "#eb6f92" -warning = "#e4b363" - -[background] -base = { color = "#191724", text = "#e0def4" } -weak = { color = "#1f1d2e", text = "#e0def4" } -strong = { color = "#26233a", text = "#f4ebd3" } - -[primary] -base = { color = "#eb6f92", text = "#000000" } -weak = { color = "#f6c177", text = "#000000" } -strong = { color = "#ebbcba", text = "#000000" } - -[secondary] -base = { color = "#31748f", text = "#ffffff" } -weak = { color = "#9ccfd8", text = "#000000" } -strong = { color = "#c4a7e7", text = "#000000" } - -[success] -base = { color = "#9ccfd8", text = "#000000" } -weak = { color = "#6e6a86", text = "#ffffff" } -strong = { color = "#908caa", text = "#000000" } - -[danger] -base = { color = "#eb6f92", text = "#ffffff" } -weak = { color = "#f6c177", text = "#ffffff" } -strong = { color = "#524f67", text = "#ffffff" } - -[warning] -base = { color = "#e4b363", text = "#ffffff" } -weak = { color = "#f4e1a1", text = "#000000" } -strong = { color = "#d8a343", text = "#ffffff" } diff --git a/src/appearance.rs b/src/appearance.rs new file mode 100644 index 0000000..78e782d --- /dev/null +++ b/src/appearance.rs @@ -0,0 +1,46 @@ +use std::sync::Arc; + +use material_theme::Theme; + +pub fn iced_theme_from_str(theme_name: &str) -> iced::Theme { + match theme_name { + "Light" => iced::Theme::Light, + "Dark" => iced::Theme::Dark, + "Dracula" => iced::Theme::Dracula, + "Nord" => iced::Theme::Nord, + "Solarized Light" => iced::Theme::SolarizedLight, + "Solarized Dark" => iced::Theme::SolarizedDark, + "Gruvbox Light" => iced::Theme::GruvboxLight, + "Gruvbox Dark" => iced::Theme::GruvboxDark, + "Catppuccin Latte" => iced::Theme::CatppuccinLatte, + "Catppuccin Frappé" => iced::Theme::CatppuccinFrappe, + "Catppuccin Macchiato" => iced::Theme::CatppuccinMacchiato, + "Catppuccin Mocha" => iced::Theme::CatppuccinMocha, + "Tokyo Night" => iced::Theme::TokyoNight, + "Tokyo Night Storm" => iced::Theme::TokyoNightStorm, + "Tokyo Night Light" => iced::Theme::TokyoNightLight, + "Kanagawa Wave" => iced::Theme::KanagawaWave, + "Kanagawa Dragon" => iced::Theme::KanagawaDragon, + "Kanagawa Lotus" => iced::Theme::KanagawaLotus, + "Moonfly" => iced::Theme::Moonfly, + "Nightfly" => iced::Theme::Nightfly, + "Oxocarbon" => iced::Theme::Oxocarbon, + "Ferra" => iced::Theme::Ferra, + _ => iced::Theme::default(), + } +} + +#[derive(Debug, Clone)] +pub struct Appearance { + pub selected: Theme, + pub all: Arc<[Theme]>, +} + +impl Default for Appearance { + fn default() -> Self { + Self { + selected: Theme::default(), + all: Theme::ALL.into(), + } + } +} diff --git a/src/config.rs b/src/config.rs index 1da1239..7f6f8ce 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,26 +1,36 @@ // (c) 2022-2024 Cory Forsstrom, Casper Rogild Storm, Calvin Lee, Andrew Baldwin, Reza Alizadeh Majd // (c) 2024-2025 Polesznyák Márk László -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use material_theme::Theme; use serde::Deserialize; use tokio_stream::StreamExt; use tokio_stream::wrappers::ReadDirStream; -use crate::theme::{Appearance, Theme, theme_from_str, theme_index}; +use crate::appearance::Appearance; use crate::{Error, environment}; #[derive(Debug, Clone, Default)] pub struct Config { - pub theme: Appearance, - pub last_project: Option, + theme: Appearance, + last_project: Option, } impl Config { - pub fn selected_theme(&self) -> iced::Theme { + pub fn selected_theme(&self) -> Theme { self.theme.selected.clone() } + pub fn themes(&self) -> Arc<[Theme]> { + self.theme.all.clone() + } + + pub fn last_project(&self) -> Option<&Path> { + self.last_project.as_deref() + } + pub fn config_dir() -> PathBuf { let dir = environment::config_dir(); @@ -67,7 +77,7 @@ impl Config { last_project, } = toml::from_str(content.as_ref())?; - let theme = Self::load_theme(theme).await.unwrap_or_default(); + let theme = Self::load_appearance(&theme).await.unwrap_or_default(); Ok(Self { theme, @@ -75,7 +85,9 @@ impl Config { }) } - pub async fn load_theme(theme_name: String) -> Result { + pub async fn load_appearance( + theme_name: &str, + ) -> Result { use tokio::fs; let read_entry = async move |entry: fs::DirEntry| { @@ -83,15 +95,16 @@ impl Config { let theme: Theme = toml::from_str(content.as_ref()).ok()?; - Some(iced::Theme::from(theme)) + Some(theme) }; - let mut selected = Theme::default().into(); - let mut all = iced::Theme::ALL.to_owned(); - all.push(Theme::default().into()); + let mut selected = Theme::default(); + let mut all = Theme::ALL.to_owned(); - if theme_index(&theme_name, iced::Theme::ALL).is_some() { - selected = theme_from_str(None, &theme_name); + if let Some(index) = + Theme::ALL.iter().position(|t| t.name() == theme_name) + { + selected = Theme::ALL[index].clone(); } let mut stream = @@ -102,7 +115,7 @@ impl Config { }; if let Some(theme) = read_entry(entry).await { - if theme.to_string() == theme_name { + if theme.name() == theme_name { selected = theme.clone(); } all.push(theme); diff --git a/src/dialogs.rs b/src/dialogs.rs index a623f35..c1933ec 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -1,8 +1,8 @@ -use iced::{Element, Task}; +use iced::Task; use iced_dialog::button; use crate::Message; -use crate::types::{DialogAction, DialogButtons}; +use crate::types::{DialogAction, DialogButtons, Element}; pub const UNSAVED_CHANGES_TITLE: &str = "Unsaved changes"; pub const WARNING_TITLE: &str = "Heads up!"; diff --git a/src/main.rs b/src/main.rs index 5014077..1ac1d67 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod appearance; mod config; mod dialogs; mod environment; @@ -6,7 +7,6 @@ mod error; mod icon; mod options; mod panes; -mod theme; mod types; mod values; mod widget; @@ -24,13 +24,15 @@ use iced::advanced::widget::Id; use iced::widget::{ Column, container, pane_grid, pick_list, row, text, text_editor, }; -use iced::{Alignment, Element, Length, Task, Theme, clipboard, keyboard}; +use iced::{Alignment, Length, Task, clipboard, keyboard}; use iced_anim::transition::Easing; use iced_anim::{Animated, Animation}; use iced_dialog::dialog::Dialog; +use material_theme::Theme; use panes::{code_view, designer_view, element_list}; use types::{ - Action, DesignerPane, DialogAction, DialogButtons, Message, Project, + Action, DesignerPane, DialogAction, DialogButtons, Element, Message, + Project, }; fn main() -> Result<(), Box> { @@ -148,11 +150,10 @@ impl IcedBuilder { self.config = Arc::new(config); self.theme.update(self.config.selected_theme().into()); - return if let Some(path) = self.config.last_project.clone() - { + return if let Some(path) = self.config.last_project() { if path.exists() && path.is_file() { Task::perform( - Project::from_path(path), + Project::from_path(path.to_owned()), Message::FileOpened, ) } else { @@ -394,7 +395,7 @@ impl IcedBuilder { fn view(&self) -> Element<'_, Message> { let header = row![pick_list( - self.config.theme.all.clone(), + self.config.themes(), Some(self.theme.target()), |theme| Message::SwitchTheme(theme.into()) )] @@ -442,13 +443,7 @@ impl IcedBuilder { DialogButtons::OkCancel => vec![ok_button(), cancel_button()], }, ) - .title(self.dialog_title) - .container_style(|theme| container::Style { - background: Some( - theme.extended_palette().background.strong.color.into(), - ), - ..Default::default() - }); + .title(self.dialog_title); Animation::new(&self.theme, content) .on_update(Message::SwitchTheme) diff --git a/src/options.rs b/src/options.rs index 2dc25d7..931182a 100644 --- a/src/options.rs +++ b/src/options.rs @@ -258,7 +258,7 @@ impl ApplyOptions for Row<'_, Message> { } } -impl ApplyOptions for Image { +impl ApplyOptions for Image<'_, Handle> { fn apply_options(self, options: BTreeMap>) -> Self { let mut image = self; diff --git a/src/panes/code_view.rs b/src/panes/code_view.rs index 890af8a..5999b8f 100644 --- a/src/panes/code_view.rs +++ b/src/panes/code_view.rs @@ -1,27 +1,36 @@ use iced::advanced::text::highlighter::Format; -use iced::widget::{Space, button, pane_grid, row, text, text_editor}; -use iced::{Alignment, Background, Border, Font, Length, Theme}; +use iced::border::Radius; +use iced::widget::{button, pane_grid, row, text, text_editor}; +use iced::{Alignment, Border, Font, Length}; use iced_custom_highlighter::{Highlight, Highlighter, Scope, Settings}; +use material_theme::Theme; use super::style; use crate::icon; use crate::types::{DesignerPane, Message}; use crate::widget::tip; +// TODO: implement a highlight style for the material theme fn highlight_style(theme: &Theme, scope: &Scope) -> Format { + let theme = if theme.is_dark() { + iced::Theme::SolarizedDark + } else { + iced::Theme::SolarizedLight + }; + match scope { Scope::Custom { .. } | Scope::Other => Format { color: Some(theme.extended_palette().primary.strong.color), font: None, }, - _ => Highlight::default_style(theme, scope), + _ => Highlight::default_style(&theme, scope), } } pub fn view( editor_content: &text_editor::Content, is_focused: bool, -) -> pane_grid::Content<'_, Message> { +) -> pane_grid::Content<'_, Message, Theme> { let title_bar = pane_grid::TitleBar::new(text("Generated Code").center()) .controls(pane_grid::Controls::dynamic( row![ @@ -29,28 +38,28 @@ pub fn view( button(icon::copy()) .on_press(Message::CopyCode) .padding([2, 7]) - .style(button::text), + .style(material_theme::button::text), "Copy", tip::Position::FollowCursor ), - Space::with_width(20), button("Switch to Designer view") .on_press(Message::SwitchPage(DesignerPane::DesignerView)) ] + .spacing(20) .align_y(Alignment::Center), row![ tip( button(icon::copy()) .on_press(Message::CopyCode) .padding([2, 7]) - .style(button::text), + .style(material_theme::button::text), "Copy", tip::Position::FollowCursor ), - Space::with_width(20), button(icon::switch()) .on_press(Message::SwitchPage(DesignerPane::DesignerView)) ] + .spacing(20) .align_y(Alignment::Center), )) .padding(10) @@ -60,25 +69,22 @@ pub fn view( text_editor(editor_content) .on_action(Message::EditorAction) .font(Font::MONOSPACE) - .highlight_with::( + .highlight_with::>( Settings::new(vec![], highlight_style, "rs"), Highlight::to_format, ) .style(|theme, _| { - let palette = theme.extended_palette(); + let style = material_theme::text_editor::default( + theme, + text_editor::Status::Active, + ); + text_editor::Style { - background: Background::Color( - palette.background.base.color, - ), border: Border { - radius: 2.into(), - width: 1.0, - color: palette.background.strong.color, + radius: Radius::default(), + ..style.border }, - icon: palette.background.weak.text, - placeholder: palette.background.strong.color, - value: palette.background.base.text, - selection: palette.primary.weak.color, + ..style } }) .height(Length::Fill) diff --git a/src/panes/designer_view.rs b/src/panes/designer_view.rs index af72022..0255b40 100644 --- a/src/panes/designer_view.rs +++ b/src/panes/designer_view.rs @@ -1,7 +1,8 @@ use iced::widget::{ button, center, container, pane_grid, responsive, row, text, themer, }; -use iced::{Alignment, Element, Length}; +use iced::{Alignment, Length}; +use material_theme::Theme; use super::style; use crate::icon; @@ -11,8 +12,8 @@ pub fn view<'a>( element_tree: Option<&'a RenderedElement>, designer_theme: iced::Theme, is_focused: bool, -) -> pane_grid::Content<'a, Message> { - let el_tree: Element<'a, Message> = match element_tree { +) -> pane_grid::Content<'a, Message, Theme> { + let el_tree: iced::Element<'a, Message> = match element_tree { Some(tree) => responsive(|size| { center( container(tree.clone()) diff --git a/src/panes/element_list.rs b/src/panes/element_list.rs index 594c203..0e5dbfe 100644 --- a/src/panes/element_list.rs +++ b/src/panes/element_list.rs @@ -1,9 +1,10 @@ use iced::widget::{Column, column, container, pane_grid, text}; -use iced::{Alignment, Element, Length}; +use iced::{Alignment, Length}; use iced_drop::droppable; +use material_theme::Theme; use super::style; -use crate::types::{ElementName, Message}; +use crate::types::{Element, ElementName, Message}; fn items_list_view<'a>() -> Element<'a, Message> { let mut column = Column::new() @@ -25,7 +26,7 @@ fn items_list_view<'a>() -> Element<'a, Message> { .into() } -pub fn view<'a>(is_focused: bool) -> pane_grid::Content<'a, Message> { +pub fn view<'a>(is_focused: bool) -> pane_grid::Content<'a, Message, Theme> { let items_list = items_list_view(); let content = column![items_list] .align_x(Alignment::Center) diff --git a/src/panes/style.rs b/src/panes/style.rs index 1eefb2d..acca6f9 100644 --- a/src/panes/style.rs +++ b/src/panes/style.rs @@ -1,24 +1,25 @@ use iced::widget::container::Style; -use iced::{Border, Theme}; +use iced::{Background, Border}; +use material_theme::Theme; pub fn title_bar(theme: &Theme) -> Style { - let palette = theme.extended_palette(); + let surface = theme.colors().surface; Style { - text_color: Some(palette.background.strong.text), - background: Some(palette.background.strong.color.into()), + text_color: Some(surface.on_surface), + background: Some(Background::Color(surface.surface_container.high)), ..Default::default() } } pub fn pane_active(theme: &Theme) -> Style { - let palette = theme.extended_palette(); + let surface = theme.colors().surface; Style { - background: Some(palette.background.weak.color.into()), + background: Some(Background::Color(surface.surface_container.low)), border: Border { width: 1.0, - color: palette.background.strong.color, + color: surface.surface_container.high, ..Border::default() }, ..Default::default() @@ -26,13 +27,13 @@ pub fn pane_active(theme: &Theme) -> Style { } pub fn pane_focused(theme: &Theme) -> Style { - let palette = theme.extended_palette(); + let surface = theme.colors().surface; Style { - background: Some(palette.background.weak.color.into()), + background: Some(Background::Color(surface.surface_container.low)), border: Border { - width: 4.0, - color: palette.background.strong.color, + width: 2.0, + color: surface.surface_container.high, ..Border::default() }, ..Default::default() diff --git a/src/theme.rs b/src/theme.rs deleted file mode 100644 index b721ddc..0000000 --- a/src/theme.rs +++ /dev/null @@ -1,357 +0,0 @@ -use std::sync::Arc; - -use iced::Color; -use iced::theme::palette::Extended; -use serde::Deserialize; - -use crate::config::Config; - -const DEFAULT_THEME_CONTENT: &str = - include_str!("../assets/themes/rose_pine.toml"); - -pub fn theme_index(theme_name: &str, slice: &[iced::Theme]) -> Option { - slice - .iter() - .position(|theme| theme.to_string() == theme_name) -} - -pub fn theme_from_str( - config: Option<&Config>, - theme_name: &str, -) -> iced::Theme { - match theme_name { - "Light" => iced::Theme::Light, - "Dark" => iced::Theme::Dark, - "Dracula" => iced::Theme::Dracula, - "Nord" => iced::Theme::Nord, - "Solarized Light" => iced::Theme::SolarizedLight, - "Solarized Dark" => iced::Theme::SolarizedDark, - "Gruvbox Light" => iced::Theme::GruvboxLight, - "Gruvbox Dark" => iced::Theme::GruvboxDark, - "Catppuccin Latte" => iced::Theme::CatppuccinLatte, - "Catppuccin Frappé" => iced::Theme::CatppuccinFrappe, - "Catppuccin Macchiato" => iced::Theme::CatppuccinMacchiato, - "Catppuccin Mocha" => iced::Theme::CatppuccinMocha, - "Tokyo Night" => iced::Theme::TokyoNight, - "Tokyo Night Storm" => iced::Theme::TokyoNightStorm, - "Tokyo Night Light" => iced::Theme::TokyoNightLight, - "Kanagawa Wave" => iced::Theme::KanagawaWave, - "Kanagawa Dragon" => iced::Theme::KanagawaDragon, - "Kanagawa Lotus" => iced::Theme::KanagawaLotus, - "Moonfly" => iced::Theme::Moonfly, - "Nightfly" => iced::Theme::Nightfly, - "Oxocarbon" => iced::Theme::Oxocarbon, - "Ferra" => iced::Theme::Ferra, - _ => { - if let Some(config) = config { - if theme_name == config.theme.selected.to_string() { - config.theme.selected.clone() - } else if let Some(index) = - theme_index(theme_name, &config.theme.all) - { - config.theme.all[index].clone() - } else { - iced::Theme::default() - } - } else { - iced::Theme::default() - } - } - } -} - -#[derive(Debug, Clone)] -pub struct Appearance { - pub selected: iced::Theme, - pub all: Arc<[iced::Theme]>, -} - -impl Default for Appearance { - fn default() -> Self { - Self { - selected: Theme::default().into(), - all: { - let mut themes = iced::Theme::ALL.to_owned(); - themes.push(Theme::default().into()); - themes.into() - }, - } - } -} - -#[derive(Debug, Deserialize)] -pub struct Theme { - name: String, - palette: ThemePalette, - dark: Option, - #[serde(flatten)] - extended: Option, -} - -impl From for iced::Theme { - fn from(value: Theme) -> Self { - iced::Theme::custom_with_fn( - value.name.clone(), - value.palette.into(), - |_| value.into(), - ) - } -} - -impl Default for Theme { - fn default() -> Self { - toml::from_str(DEFAULT_THEME_CONTENT).expect("parse default theme") - } -} - -#[derive(Debug, Clone, Copy, Deserialize)] -pub struct ThemePalette { - #[serde(with = "color_serde")] - background: Color, - #[serde(with = "color_serde")] - text: Color, - #[serde(with = "color_serde")] - primary: Color, - #[serde(with = "color_serde")] - success: Color, - #[serde(with = "color_serde")] - danger: Color, - #[serde(with = "color_serde")] - warning: Color, -} - -impl Default for ThemePalette { - fn default() -> Self { - let palette = iced::Theme::default().palette(); - Self { - background: palette.background, - text: palette.text, - primary: palette.primary, - success: palette.success, - danger: palette.danger, - warning: palette.warning, - } - } -} - -impl From for iced::theme::Palette { - fn from(palette: ThemePalette) -> Self { - iced::theme::Palette { - background: palette.background, - text: palette.text, - primary: palette.primary, - success: palette.success, - danger: palette.danger, - warning: palette.warning, - } - } -} - -impl From for Extended { - fn from(theme: Theme) -> Self { - let mut extended = Extended::generate(theme.palette.into()); - - if let Some(is_dark) = theme.dark { - extended.is_dark = is_dark; - } - - if let Some(extended_palette) = theme.extended { - if let Some(background) = extended_palette.background { - if let Some(base) = background.base { - extended.background.base = base.into(); - } - if let Some(weak) = background.weak { - extended.background.weak = weak.into(); - } - if let Some(strong) = background.strong { - extended.background.strong = strong.into(); - } - } - - if let Some(primary) = extended_palette.primary { - if let Some(base) = primary.base { - extended.primary.base = base.into(); - } - if let Some(weak) = primary.weak { - extended.primary.weak = weak.into(); - } - if let Some(strong) = primary.strong { - extended.primary.strong = strong.into(); - } - } - - if let Some(secondary) = extended_palette.secondary { - if let Some(base) = secondary.base { - extended.secondary.base = base.into(); - } - if let Some(weak) = secondary.weak { - extended.secondary.weak = weak.into(); - } - if let Some(strong) = secondary.strong { - extended.secondary.strong = strong.into(); - } - } - - if let Some(success) = extended_palette.success { - if let Some(base) = success.base { - extended.success.base = base.into(); - } - if let Some(weak) = success.weak { - extended.success.weak = weak.into(); - } - if let Some(strong) = success.strong { - extended.success.strong = strong.into(); - } - } - - if let Some(danger) = extended_palette.danger { - if let Some(base) = danger.base { - extended.danger.base = base.into(); - } - if let Some(weak) = danger.weak { - extended.danger.weak = weak.into(); - } - if let Some(strong) = danger.strong { - extended.danger.strong = strong.into(); - } - } - - if let Some(warning) = extended_palette.warning { - if let Some(base) = warning.base { - extended.warning.base = base.into(); - } - if let Some(weak) = warning.weak { - extended.warning.weak = weak.into(); - } - if let Some(strong) = warning.strong { - extended.warning.strong = strong.into(); - } - } - } - - extended - } -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ExtendedThemePalette { - background: Option, - primary: Option, - secondary: Option, - success: Option, - danger: Option, - warning: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemeBackground { - base: Option, - weak: Option, - strong: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemePrimary { - base: Option, - weak: Option, - strong: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemeSecondary { - base: Option, - weak: Option, - strong: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemeSuccess { - base: Option, - weak: Option, - strong: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemeDanger { - base: Option, - weak: Option, - strong: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemeWarning { - base: Option, - weak: Option, - strong: Option, -} - -#[derive(Debug, Clone, Copy, Default, Deserialize)] -struct ThemePair { - #[serde(with = "color_serde")] - color: Color, - #[serde(with = "color_serde")] - text: Color, -} - -impl From for iced::theme::palette::Pair { - fn from(pair: ThemePair) -> Self { - Self { - color: pair.color, - text: pair.text, - } - } -} - -pub fn parse_argb(s: &str) -> Option { - let hex = s.strip_prefix('#').unwrap_or(s); - - let parse_channel = |from: usize, to: usize| { - let num = - usize::from_str_radix(&hex[from..=to], 16).ok()? as f32 / 255.0; - - // If we only got half a byte (one letter), expand it into a full byte (two letters) - Some(if from == to { num + num * 16.0 } else { num }) - }; - - Some(match hex.len() { - 3 => Color::from_rgb( - parse_channel(0, 0)?, - parse_channel(1, 1)?, - parse_channel(2, 2)?, - ), - 4 => Color::from_rgba( - parse_channel(1, 1)?, - parse_channel(2, 2)?, - parse_channel(3, 3)?, - parse_channel(0, 0)?, - ), - 6 => Color::from_rgb( - parse_channel(0, 1)?, - parse_channel(2, 3)?, - parse_channel(4, 5)?, - ), - 8 => Color::from_rgba( - parse_channel(2, 3)?, - parse_channel(4, 5)?, - parse_channel(6, 7)?, - parse_channel(0, 1)?, - ), - _ => None?, - }) -} - -mod color_serde { - use iced::Color; - use serde::{Deserialize, Deserializer}; - - use super::parse_argb; - - pub fn deserialize<'de, D>(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - Ok(String::deserialize(deserializer) - .map(|hex| parse_argb(&hex))? - .unwrap_or(Color::TRANSPARENT)) - } -} diff --git a/src/types.rs b/src/types.rs index adb788e..608f285 100644 --- a/src/types.rs +++ b/src/types.rs @@ -8,16 +8,20 @@ pub use element_name::ElementName; use iced::advanced::widget::Id; use iced::widget::{pane_grid, text_editor}; use iced_anim::Event; +use material_theme::Theme; pub use project::Project; pub use rendered_element::*; use crate::Error; use crate::config::Config; +pub type Element<'a, Message> = iced::Element<'a, Message, Theme>; + +#[allow(clippy::large_enum_variant)] #[derive(Debug, Clone)] pub enum Message { ConfigLoad(Result), - SwitchTheme(Event), + SwitchTheme(Event), CopyCode, SwitchPage(DesignerPane), EditorAction(text_editor::Action), diff --git a/src/types/project.rs b/src/types/project.rs index 91b2bb1..11789ac 100644 --- a/src/types/project.rs +++ b/src/types/project.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use super::rendered_element::RenderedElement; use crate::Error; -use crate::theme::{theme_from_str, theme_index}; +use crate::appearance::iced_theme_from_str; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Project { @@ -33,8 +33,8 @@ impl Project { pub fn get_theme(&self) -> Theme { match &self.theme { - Some(theme) => theme_from_str(None, theme), - None => Theme::default(), + Some(theme) => iced_theme_from_str(theme), + None => iced::Theme::default(), } } @@ -90,20 +90,10 @@ impl Project { Some(ref element_tree) => { let (imports, view) = element_tree.codegen(); let theme = self.get_theme(); - let theme_code = theme.to_string().replace(" ", ""); - let mut theme_imports = ""; - if theme_index(&theme.to_string(), Theme::ALL).is_none() { - if theme_code.contains("Extended") { - theme_imports = "use iced::{{color,theme::{{Palette,palette::{{Extended,Background,Primary,Secondary,Success,Danger,Warning,Pair}}}}}};\n"; - } else { - theme_imports = "use iced::{{color,theme::Palette}};\n"; - } - } let app_code = format!( r#"// Automatically generated by iced Builder use iced::{{widget::{{{imports}}},Element}}; -{theme_imports} fn main() -> iced::Result {{ iced::application(State::default, State::update, State::view).title("{}").theme(State::theme).run() @@ -130,7 +120,7 @@ impl State {{ Some(ref t) => t, None => "New app", }, - theme_code + theme.to_string().replace(" ", "") ); let config = rust_format::Config::new_str() .edition(Edition::Rust2021) diff --git a/src/types/rendered_element.rs b/src/types/rendered_element.rs index 9639299..020aa46 100755 --- a/src/types/rendered_element.rs +++ b/src/types/rendered_element.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use iced::advanced::widget::Id; -use iced::{Element, Length, widget}; +use iced::{Element, widget}; use serde::{Deserialize, Serialize}; use crate::Error; @@ -171,34 +171,6 @@ impl RenderedElement { self } - pub fn text_view<'a>(self) -> Element<'a, Message> { - let mut children = widget::column![]; - - if let Some(els) = self.child_elements.clone() { - for el in els { - children = children.push(el.clone().text_view()); - } - } - iced_drop::droppable( - widget::container( - widget::column![ - widget::text(self.name.clone().to_string()), - children - ] - .width(Length::Fill) - .spacing(10), - ) - .padding(10) - .style(widget::container::bordered_box), - ) - .id(self.id().clone()) - .drag_hide(true) - .on_drop(move |point, rect| { - Message::MoveElement(self.clone(), point, rect) - }) - .into() - } - pub fn codegen(&self) -> (String, String) { let mut imports = String::new(); let mut view = String::new(); diff --git a/src/widget.rs b/src/widget.rs index f1eb0f3..859d25e 100644 --- a/src/widget.rs +++ b/src/widget.rs @@ -1,5 +1,7 @@ -use iced::Element; -use iced::widget::{container, text, tooltip}; +use iced::widget::{self, container, text, tooltip}; +use material_theme::Theme; + +use crate::types::Element; pub mod tip { pub use super::tooltip::Position; @@ -12,10 +14,16 @@ pub fn tip<'a, Message: 'a>( ) -> Element<'a, Message> { tooltip( target, - container(text(tip).size(14)) - .padding(5) - .style(container::rounded_box), + container(text(tip).size(14)).padding(5).style(|theme| { + let base = material_theme::container::surface_container_low(theme); + container::Style { + border: iced::border::rounded(4), + ..base + } + }), position, ) .into() } + +pub type Text<'a> = widget::Text<'a, Theme>; diff --git a/theme_test/src/main.rs b/theme_test/src/main.rs index b4a7731..cba4377 100644 --- a/theme_test/src/main.rs +++ b/theme_test/src/main.rs @@ -18,7 +18,7 @@ use material_theme::text::surface_variant; fn main() -> iced::Result { iced::application(State::default, State::update, State::view) - .theme(|state| *state.theme.value()) + .theme(|state| state.theme.value().clone()) .run() } -- cgit v1.2.3 From 9ecd689c2b708894b9cf88576aa8dfa5b5797a63 Mon Sep 17 00:00:00 2001 From: pml68 Date: Tue, 29 Apr 2025 23:33:07 +0200 Subject: style: `theme` -> `appearance` --- src/config.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/config.rs b/src/config.rs index 7f6f8ce..369a505 100644 --- a/src/config.rs +++ b/src/config.rs @@ -14,17 +14,17 @@ use crate::{Error, environment}; #[derive(Debug, Clone, Default)] pub struct Config { - theme: Appearance, + appearance: Appearance, last_project: Option, } impl Config { pub fn selected_theme(&self) -> Theme { - self.theme.selected.clone() + self.appearance.selected.clone() } pub fn themes(&self) -> Arc<[Theme]> { - self.theme.all.clone() + self.appearance.all.clone() } pub fn last_project(&self) -> Option<&Path> { @@ -77,10 +77,11 @@ impl Config { last_project, } = toml::from_str(content.as_ref())?; - let theme = Self::load_appearance(&theme).await.unwrap_or_default(); + let appearance = + Self::load_appearance(&theme).await.unwrap_or_default(); Ok(Self { - theme, + appearance, last_project, }) } -- cgit v1.2.3