diff --git a/Cargo.toml b/Cargo.toml index ebea333..115aa1a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,8 +6,9 @@ version = "0.1.0" edition = "2021" [features] -default = ["tracing-output"] +default = ["tracing-output", "roboto-flex"] tracing-output = ["dep:tracing-subscriber"] +roboto-flex = [] [dependencies] kludgine = { git = "https://github.com/khonsulabs/kludgine", features = [ diff --git a/assets/OFL.txt b/assets/OFL.txt new file mode 100644 index 0000000..f6ebd5a --- /dev/null +++ b/assets/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2017 The Roboto Flex Project Authors (https://github.com/TypeNetwork/Roboto-Flex) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/RobotoFlex.ttf b/assets/RobotoFlex.ttf new file mode 100644 index 0000000..c39aafb Binary files /dev/null and b/assets/RobotoFlex.ttf differ diff --git a/examples/login.rs b/examples/login.rs index 81d0d98..5ca2f9a 100644 --- a/examples/login.rs +++ b/examples/login.rs @@ -22,10 +22,7 @@ fn main() -> gooey::Result { let password_field = "Password" .align_left() - .and( - // TODO secure input - password.clone().into_input(), - ) + .and(password.clone().into_input()) .into_rows(); let buttons = "Cancel" diff --git a/src/animation.rs b/src/animation.rs index 51c46d1..e2c8a0e 100644 --- a/src/animation.rs +++ b/src/animation.rs @@ -41,7 +41,7 @@ pub mod easings; use std::cmp::Ordering; use std::fmt::{Debug, Display}; -use std::ops::{ControlFlow, Deref, Div, Mul}; +use std::ops::{ControlFlow, Deref, Div, Mul, Sub}; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::str::FromStr; use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; @@ -52,7 +52,8 @@ use alot::{LotId, Lots}; use derive_more::From; use intentional::Cast; use kempt::Set; -use kludgine::figures::Ranged; +use kludgine::figures::units::{Lp, Px, UPx}; +use kludgine::figures::{Ranged, UnscaledUnit}; use kludgine::Color; use crate::animation::easings::Linear; @@ -733,6 +734,27 @@ impl PercentBetween for bool { } } +macro_rules! impl_unscaled_lerp { + ($wrapper:ident) => { + impl LinearInterpolate for $wrapper { + fn lerp(&self, target: &Self, percent: f32) -> Self { + Self::from_unscaled(self.into_unscaled().lerp(&target.into_unscaled(), percent)) + } + } + + impl PercentBetween for $wrapper { + fn percent_between(&self, min: &Self, max: &Self) -> ZeroToOne { + self.into_unscaled() + .percent_between(&min.into_unscaled(), &max.into_unscaled()) + } + } + }; +} + +impl_unscaled_lerp!(Px); +impl_unscaled_lerp!(Lp); +impl_unscaled_lerp!(UPx); + #[test] fn integer_lerps() { #[track_caller] @@ -815,7 +837,7 @@ pub trait PercentBetween { } macro_rules! impl_percent_between { - ($type:ident, $float:ident) => { + ($type:ident, $float:ident, $sub:ident) => { impl PercentBetween for $type { fn percent_between(&self, min: &Self, max: &Self) -> ZeroToOne { assert!(min <= max, "percent_between requires min <= max"); @@ -824,27 +846,27 @@ macro_rules! impl_percent_between { "self must satisfy min <= self <= max" ); - let range = *max - *min; - ZeroToOne::from((*self - *min) as $float / range as $float) + let range = max.$sub(*min); + ZeroToOne::from(self.$sub(*min) as $float / range as $float) } } }; } -impl_percent_between!(u8, f32); -impl_percent_between!(u16, f32); -impl_percent_between!(u32, f32); -impl_percent_between!(u64, f32); -impl_percent_between!(u128, f64); -impl_percent_between!(usize, f64); -impl_percent_between!(i8, f32); -impl_percent_between!(i16, f32); -impl_percent_between!(i32, f32); -impl_percent_between!(i64, f32); -impl_percent_between!(i128, f64); -impl_percent_between!(isize, f64); -impl_percent_between!(f32, f32); -impl_percent_between!(f64, f64); +impl_percent_between!(u8, f32, saturating_sub); +impl_percent_between!(u16, f32, saturating_sub); +impl_percent_between!(u32, f32, saturating_sub); +impl_percent_between!(u64, f32, saturating_sub); +impl_percent_between!(u128, f64, saturating_sub); +impl_percent_between!(usize, f64, saturating_sub); +impl_percent_between!(i8, f32, saturating_sub); +impl_percent_between!(i16, f32, saturating_sub); +impl_percent_between!(i32, f32, saturating_sub); +impl_percent_between!(i64, f32, saturating_sub); +impl_percent_between!(i128, f64, saturating_sub); +impl_percent_between!(isize, f64, saturating_sub); +impl_percent_between!(f32, f32, sub); +impl_percent_between!(f64, f64, sub); impl PercentBetween for Color { fn percent_between(&self, min: &Self, max: &Self) -> ZeroToOne { diff --git a/src/context.rs b/src/context.rs index 7d17c9b..87f0d59 100644 --- a/src/context.rs +++ b/src/context.rs @@ -15,7 +15,10 @@ use kludgine::shapes::{Shape, StrokeOptions}; use kludgine::{Color, Kludgine}; use crate::graphics::Graphics; -use crate::styles::components::{CornerRadius, HighlightColor, LayoutOrder, WidgetBackground}; +use crate::styles::components::{ + CornerRadius, FontFamily, FontStyle, FontWeight, HighlightColor, LayoutOrder, TextSize, + WidgetBackground, +}; use crate::styles::{ComponentDefinition, Styles, Theme, ThemePair}; use crate::utils::IgnorePoison; use crate::value::{Dynamic, IntoValue, Value}; @@ -574,6 +577,25 @@ impl<'context, 'window, 'clip, 'gfx, 'pass> GraphicsContext<'context, 'window, ' self.stroke_outline::(color, StrokeOptions::lp_wide(Lp::points(2))); } + /// Applies the current style settings for font family, text size, font + /// style, and font weight. + pub fn apply_current_font_settings(&mut self) { + self.gfx + .set_available_font_family(&self.widget.get(&FontFamily)); + self.gfx.set_font_size(self.widget.get(&TextSize)); + self.gfx.set_font_style(self.widget.get(&FontStyle)); + self.gfx.set_font_weight(self.widget.get(&FontWeight)); + } + + // /// Applies the current style settings for font family, text size, font + // /// style, and font weight. + // pub fn apply_current_font_settings_to<'a>(&self, attrs: Attrs<'a>) -> Attrs<'a> { + // attrs.set_available_font_family(&self.widget.get(&FontFamily)); + // attrs.set_font_size(self.widget.get(&TextSize)); + // attrs.set_font_style(self.widget.get(&FontStyle)); + // attrs.set_font_weight(self.widget.get(&FontWeight)); + // } + /// Invokes [`Widget::redraw()`](crate::widget::Widget::redraw) on this /// context's widget. /// @@ -590,6 +612,8 @@ impl<'context, 'window, 'clip, 'gfx, 'pass> GraphicsContext<'context, 'window, ' let background = self.get(&WidgetBackground); self.gfx.fill(background); + self.apply_current_font_settings(); + self.current_node .tree .note_widget_rendered(self.current_node.node_id); diff --git a/src/graphics.rs b/src/graphics.rs index 8689f4a..4dc73f3 100644 --- a/src/graphics.rs +++ b/src/graphics.rs @@ -1,5 +1,7 @@ use std::ops::{Deref, DerefMut}; +use ahash::{HashSet, HashSetExt}; +use kludgine::cosmic_text::FamilyOwned; use kludgine::figures::units::{Px, UPx}; use kludgine::figures::{ self, Fraction, IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, ScreenUnit, Size, Zero, @@ -11,6 +13,8 @@ use kludgine::{ cosmic_text, ClipGuard, Color, Drawable, Kludgine, ShaderScalable, ShapeSource, TextureSource, }; +use crate::styles::FontFamilyList; + /// A 2d graphics context pub struct Graphics<'clip, 'gfx, 'pass> { renderer: RenderContext<'clip, 'gfx, 'pass>, @@ -57,6 +61,36 @@ impl<'clip, 'gfx, 'pass> Graphics<'clip, 'gfx, 'pass> { ) } + pub(crate) fn inner_find_available_font_family( + db: &cosmic_text::fontdb::Database, + list: &FontFamilyList, + ) -> Option { + let mut fonts = HashSet::new(); + for (family, _) in db.faces().filter_map(|f| f.families.first()) { + fonts.insert(family.clone()); + } + + list.iter() + .find(|family| match family { + FamilyOwned::Name(name) => fonts.contains(name), + _ => true, + }) + .cloned() + } + + /// Returns the first font family in `list` that is currently in the font + /// system, or None if no font families match. + pub fn find_available_font_family(&mut self, list: &FontFamilyList) -> Option { + Self::inner_find_available_font_family(self.font_system().db(), list) + } + + /// Sets the font family to the first family in `list`. + pub fn set_available_font_family(&mut self, list: &FontFamilyList) { + if let Some(family) = self.find_available_font_family(list) { + self.set_font_family(family); + } + } + /// Returns the underlying renderer. /// /// Note: Kludgine graphics contexts only support clipping. This type adds diff --git a/src/styles.rs b/src/styles.rs index 785926f..f3383d9 100644 --- a/src/styles.rs +++ b/src/styles.rs @@ -5,12 +5,14 @@ use std::borrow::Cow; use std::collections::hash_map; use std::fmt::Debug; use std::ops::{ - Add, Bound, Div, Mul, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, + Add, Bound, Deref, Div, Mul, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, + RangeToInclusive, }; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use ahash::AHashMap; +use kludgine::cosmic_text::{FamilyOwned, Style, Weight}; use kludgine::figures::units::{Lp, Px, UPx}; use kludgine::figures::{Fraction, IntoSigned, IntoUnsigned, Rect, ScreenScale, Size, Zero}; use kludgine::shapes::CornerRadii; @@ -57,8 +59,15 @@ impl Styles { /// Adds a [`Component`] for the name provided and returns self. #[must_use] - pub fn with(mut self, name: &impl NamedComponent, component: impl IntoComponentValue) -> Self { - self.insert(name, component); + pub fn with( + mut self, + name: &C, + component: impl IntoValue, + ) -> Self + where + Value: IntoComponentValue, + { + self.insert(name, component.into_value()); self } @@ -126,9 +135,13 @@ where } } -impl IntoComponentValue for Value { +impl IntoComponentValue for Value +where + T: Clone, + Component: From, +{ fn into_component_value(self) -> Value { - self + self.map_each(|v| Component::from(v.clone())) } } @@ -207,6 +220,12 @@ pub enum Component { /// A description of the depth of a /// [`Container`](crate::widgets::Container). ContainerLevel(ContainerLevel), + /// A font family. + FontFamily(FamilyOwned), + /// The weight (boldness) of a font. + FontWeight(Weight), + /// The style of a font. + FontStyle(Style), /// A custom component type. Custom(CustomComponent), @@ -224,6 +243,75 @@ impl Component { } } +impl From for Component { + fn from(value: FamilyOwned) -> Self { + Self::FontFamily(value) + } +} + +impl TryFrom for FamilyOwned { + type Error = Component; + + fn try_from(value: Component) -> Result { + match value { + Component::FontFamily(family) => Ok(family), + other => Err(other), + } + } +} + +impl RequireInvalidation for FamilyOwned { + fn requires_invalidation(&self) -> bool { + true + } +} + +impl From for Component { + fn from(value: Weight) -> Self { + Self::FontWeight(value) + } +} + +impl TryFrom for Weight { + type Error = Component; + + fn try_from(value: Component) -> Result { + match value { + Component::FontWeight(weight) => Ok(weight), + other => Err(other), + } + } +} + +impl RequireInvalidation for Weight { + fn requires_invalidation(&self) -> bool { + true + } +} + +impl From