Skip to main content

skia_safe/core/
font_arguments.rs

1//! Represents a set of actual arguments for a font, including a variation position and a color
2//! palette.
3
4use std::{fmt, marker::PhantomData, mem};
5
6use skia_bindings::{
7    self as sb, SkFontArguments, SkFontArguments_Palette, SkFontArguments_VariationPosition,
8};
9
10use crate::prelude::*;
11
12/// Represents a set of actual arguments for a font.
13#[repr(C)]
14pub struct FontArguments<'vp, 'p> {
15    args: SkFontArguments,
16    pd_vp: PhantomData<&'vp [variation_position::Coordinate]>,
17    pd_p: PhantomData<&'p [palette::Override]>,
18}
19
20native_transmutable!(SkFontArguments, FontArguments<'_, '_>);
21
22/// Represents a position in the variation design space.
23///
24/// Any axis not specified uses the default value.
25/// Any specified axis not actually present in the font is ignored.
26#[derive(Clone, Debug)]
27pub struct VariationPosition<'a> {
28    pub coordinates: &'a [variation_position::Coordinate],
29}
30
31pub mod variation_position {
32    //! A single axis/value pair in a [`crate::font_arguments::VariationPosition`].
33    use crate::FourByteTag;
34    use skia_bindings::SkFontArguments_VariationPosition_Coordinate;
35
36    /// A single axis/value pair in a [`crate::font_arguments::VariationPosition`].
37    #[derive(Copy, Clone, PartialEq, Default, Debug)]
38    #[repr(C)]
39    pub struct Coordinate {
40        pub axis: FourByteTag,
41        pub value: f32,
42    }
43
44    native_transmutable!(SkFontArguments_VariationPosition_Coordinate, Coordinate);
45
46    #[allow(non_upper_case_globals)]
47    impl Coordinate {
48        pub const wght: FourByteTag = FourByteTag::from_chars('w', 'g', 'h', 't');
49        pub const wdth: FourByteTag = FourByteTag::from_chars('w', 'd', 't', 'h');
50        pub const slnt: FourByteTag = FourByteTag::from_chars('s', 'l', 'n', 't');
51        pub const ital: FourByteTag = FourByteTag::from_chars('i', 't', 'a', 'l');
52        pub const opsz: FourByteTag = FourByteTag::from_chars('o', 'p', 's', 'z');
53    }
54}
55
56/// Specifies a palette to use and overrides for palette entries.
57///
58/// `overrides` is a list of pairs of palette entry index and color.
59/// Overridden palette entries use the associated color.
60///
61/// Override pairs with palette entry indices out of range are not applied.
62/// Later override entries override earlier ones.
63#[derive(Clone, Debug)]
64pub struct Palette<'a> {
65    pub index: i32,
66    pub overrides: &'a [palette::Override],
67}
68
69pub mod palette {
70    //! Palette entry overrides for [`crate::font_arguments::Palette`].
71    use crate::Color;
72    use skia_bindings::SkFontArguments_Palette_Override;
73
74    /// A palette entry override.
75    #[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
76    #[repr(C)]
77    pub struct Override {
78        pub index: u16,
79        pub color: Color,
80    }
81
82    native_transmutable!(SkFontArguments_Palette_Override, Override);
83}
84
85impl Drop for FontArguments<'_, '_> {
86    fn drop(&mut self) {
87        unsafe { sb::C_SkFontArguments_destruct(self.native_mut()) }
88    }
89}
90
91impl Default for FontArguments<'_, '_> {
92    fn default() -> Self {
93        FontArguments::new()
94    }
95}
96
97impl fmt::Debug for FontArguments<'_, '_> {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_struct("FontArguments")
100            .field("collection_index", &self.collection_index())
101            .field(
102                "variation_design_position",
103                &self.variation_design_position(),
104            )
105            .field("palette", &self.palette())
106            .field("synthetic_bold", &self.synthetic_bold())
107            .field("synthetic_oblique", &self.synthetic_oblique())
108            .finish()
109    }
110}
111
112impl FontArguments<'_, '_> {
113    /// Creates default font arguments.
114    pub fn new() -> Self {
115        Self::construct(|fa| unsafe {
116            sb::C_SkFontArguments_construct(fa);
117        })
118    }
119
120    /// Specifies the index of the desired font.
121    ///
122    /// Font formats like ttc, dfont, cff, cid, pfr, t42, t1, and fon may actually be indexed
123    /// collections of fonts.
124    ///
125    /// - `collection_index` index of the font in an indexed collection.
126    pub fn set_collection_index(&mut self, collection_index: usize) -> &mut Self {
127        self.native_mut().fCollectionIndex = collection_index.try_into().unwrap();
128        self
129    }
130
131    // This function consumes self for it to be able to change its lifetime,
132    // because it borrows the coordinates referenced by [`VariationPosition`].
133    //
134    // If we would return `Self`, position's Coordinates would not be borrowed.
135    /// Specifies a position in the variation design space.
136    ///
137    /// Any axis not specified uses the default value.
138    /// Any specified axis not actually present in the font is ignored.
139    ///
140    /// This borrows `position` data; the value must remain valid for the lifetime of
141    /// [`FontArguments`].
142    ///
143    /// - `position` variation coordinates to use.
144    pub fn set_variation_design_position(mut self, position: VariationPosition) -> FontArguments {
145        let position = SkFontArguments_VariationPosition {
146            coordinates: position.coordinates.native().as_ptr(),
147            coordinateCount: position.coordinates.len().try_into().unwrap(),
148        };
149        unsafe {
150            sb::C_SkFontArguments_setVariationDesignPosition(self.native_mut(), position);
151            // note: we are _not_ returning Self here, but VariationPosition with a
152            // changed lifetime.
153            mem::transmute(self)
154        }
155    }
156
157    /// Returns the index of the selected font in an indexed collection.
158    pub fn collection_index(&self) -> usize {
159        self.native().fCollectionIndex.try_into().unwrap()
160    }
161
162    /// Returns the variation design position.
163    pub fn variation_design_position(&self) -> VariationPosition {
164        unsafe {
165            let position = sb::C_SkFontArguments_getVariationDesignPosition(self.native());
166            VariationPosition {
167                coordinates: safer::from_raw_parts(
168                    position.coordinates as *const _,
169                    position.coordinateCount.try_into().unwrap(),
170                ),
171            }
172        }
173    }
174
175    // This function consumes `self` for it to be able to change its lifetime, because it borrows
176    // the coordinates referenced by `[Palette]`.
177    /// Specifies the color palette and optional palette entry overrides.
178    ///
179    /// This borrows `palette` data; the value must remain valid for the lifetime of
180    /// [`FontArguments`].
181    ///
182    /// - `palette` palette index and override entries.
183    pub fn set_palette(mut self, palette: Palette) -> FontArguments {
184        let palette = SkFontArguments_Palette {
185            index: palette.index,
186            overrides: palette.overrides.native().as_ptr(),
187            overrideCount: palette.overrides.len().try_into().unwrap(),
188        };
189        unsafe {
190            sb::C_SkFontArguments_setPalette(self.native_mut(), palette);
191            mem::transmute(self)
192        }
193    }
194
195    /// Returns the palette selection and override entries.
196    pub fn palette(&self) -> Palette {
197        unsafe {
198            let palette = sb::C_SkFontArguments_getPalette(self.native());
199            Palette {
200                index: palette.index,
201                overrides: safer::from_raw_parts(
202                    palette.overrides as *const _,
203                    palette.overrideCount.try_into().unwrap(),
204                ),
205            }
206        }
207    }
208
209    /// Sets whether synthetic bold styling is requested.
210    ///
211    /// - `synthetic_bold` `Some(true)` to force synthetic bold,
212    ///   `Some(false)` to force non-bold, `None` to leave unspecified.
213    pub fn set_synthetic_bold(&mut self, synthetic_bold: impl Into<Option<bool>>) -> &mut Self {
214        unsafe {
215            sb::C_SkFontArguments_setSyntheticBold(
216                self.native_mut(),
217                option_bool_to_ffi(synthetic_bold.into()),
218            );
219        }
220        self
221    }
222
223    /// Returns the synthetic bold preference, if specified.
224    pub fn synthetic_bold(&self) -> Option<bool> {
225        ffi_to_option_bool(unsafe { sb::C_SkFontArguments_getSyntheticBold(self.native()) })
226    }
227
228    /// Sets whether synthetic oblique styling is requested.
229    ///
230    /// - `synthetic_oblique` `Some(true)` to force synthetic oblique,
231    ///   `Some(false)` to force non-oblique, `None` to leave unspecified.
232    pub fn set_synthetic_oblique(
233        &mut self,
234        synthetic_oblique: impl Into<Option<bool>>,
235    ) -> &mut Self {
236        unsafe {
237            sb::C_SkFontArguments_setSyntheticOblique(
238                self.native_mut(),
239                option_bool_to_ffi(synthetic_oblique.into()),
240            );
241        }
242        self
243    }
244
245    /// Returns the synthetic oblique preference, if specified.
246    pub fn synthetic_oblique(&self) -> Option<bool> {
247        ffi_to_option_bool(unsafe { sb::C_SkFontArguments_getSyntheticOblique(self.native()) })
248    }
249}
250
251fn option_bool_to_ffi(value: Option<bool>) -> i32 {
252    match value {
253        Some(true) => 1,
254        Some(false) => 0,
255        None => -1,
256    }
257}
258
259fn ffi_to_option_bool(value: i32) -> Option<bool> {
260    match value {
261        1 => Some(true),
262        0 => Some(false),
263        _ => None,
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn test_font_arguments_with_no_coordinates() {
273        let fa = FontArguments::new();
274        let coordinates = fa.variation_design_position();
275        assert_eq!(coordinates.coordinates, []);
276    }
277
278    #[test]
279    #[allow(clippy::float_cmp)]
280    fn access_coordinates() {
281        let coordinates = Box::new([variation_position::Coordinate {
282            axis: 0.into(),
283            value: 1.0,
284        }]);
285        let args = FontArguments::new();
286        let pos = VariationPosition {
287            coordinates: coordinates.as_ref(),
288        };
289        let args = args.set_variation_design_position(pos);
290        assert_eq!(args.variation_design_position().coordinates[0].value, 1.0);
291        drop(args);
292    }
293
294    #[test]
295    fn synthetic_style_flags_roundtrip() {
296        let mut args = FontArguments::new();
297
298        assert_eq!(args.synthetic_bold(), None);
299        assert_eq!(args.synthetic_oblique(), None);
300
301        args.set_synthetic_bold(Some(true));
302        assert_eq!(args.synthetic_bold(), Some(true));
303
304        args.set_synthetic_bold(Some(false));
305        assert_eq!(args.synthetic_bold(), Some(false));
306
307        args.set_synthetic_bold(None);
308        assert_eq!(args.synthetic_bold(), None);
309
310        args.set_synthetic_oblique(Some(true));
311        assert_eq!(args.synthetic_oblique(), Some(true));
312
313        args.set_synthetic_oblique(Some(false));
314        assert_eq!(args.synthetic_oblique(), Some(false));
315
316        args.set_synthetic_oblique(None);
317        assert_eq!(args.synthetic_oblique(), None);
318    }
319}