skia_safe/modules/paragraph/
text_style.rs

1use super::{FontArguments, FontFamilies, TextBaseline, TextShadow};
2use crate::{
3    interop::{self, AsStr, FromStrs, SetStr},
4    prelude::*,
5    scalar,
6    textlayout::{RangeExtensions, EMPTY_INDEX, EMPTY_RANGE},
7    Color, FontMetrics, FontStyle, Paint, Typeface,
8};
9use skia_bindings as sb;
10use std::{fmt, ops::Range};
11
12bitflags! {
13    /// Multiple decorations can be applied at once. Ex: Underline and overline is
14    /// (0x1 | 0x2)
15    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
16    pub struct TextDecoration: u32 {
17        const NO_DECORATION = sb::skia_textlayout_TextDecoration::kNoDecoration as _;
18        const UNDERLINE = sb::skia_textlayout_TextDecoration::kUnderline as _;
19        const OVERLINE = sb::skia_textlayout_TextDecoration::kOverline as _;
20        const LINE_THROUGH = sb::skia_textlayout_TextDecoration::kLineThrough as _;
21    }
22}
23
24pub const ALL_TEXT_DECORATIONS: TextDecoration = TextDecoration::ALL;
25
26impl Default for TextDecoration {
27    fn default() -> Self {
28        TextDecoration::NO_DECORATION
29    }
30}
31
32impl TextDecoration {
33    pub const ALL: TextDecoration = TextDecoration::all();
34}
35
36pub use sb::skia_textlayout_TextDecorationStyle as TextDecorationStyle;
37#[test]
38fn text_decoration_style_naming() {
39    let _ = TextDecorationStyle::Solid;
40}
41
42pub use sb::skia_textlayout_TextDecorationMode as TextDecorationMode;
43#[test]
44fn text_decoration_mode_naming() {
45    let _ = TextDecorationMode::Gaps;
46}
47
48pub use sb::skia_textlayout_StyleType as StyleType;
49#[test]
50fn style_type_member_naming() {
51    let _ = StyleType::Foreground;
52    let _ = StyleType::LetterSpacing;
53}
54
55#[repr(C)]
56#[derive(Copy, Clone, PartialEq, Debug)]
57pub struct Decoration {
58    pub ty: TextDecoration,
59    pub mode: TextDecorationMode,
60    pub color: Color,
61    pub style: TextDecorationStyle,
62    pub thickness_multiplier: scalar,
63}
64
65impl Default for Decoration {
66    fn default() -> Self {
67        Self {
68            ty: TextDecoration::default(),
69            mode: TextDecorationMode::default(),
70            color: Color::TRANSPARENT,
71            style: TextDecorationStyle::default(),
72            thickness_multiplier: 1.0,
73        }
74    }
75}
76
77native_transmutable!(sb::skia_textlayout_Decoration, Decoration);
78
79/// Where to vertically align the placeholder relative to the surrounding text.
80#[repr(i32)]
81#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Default)]
82pub enum PlaceholderAlignment {
83    /// Match the baseline of the placeholder with the baseline.
84    #[default]
85    Baseline,
86
87    /// Align the bottom edge of the placeholder with the baseline such that the
88    /// placeholder sits on top of the baseline.
89    AboveBaseline,
90
91    /// Align the top edge of the placeholder with the baseline specified in
92    /// such that the placeholder hangs below the baseline.
93    BelowBaseline,
94
95    /// Align the top edge of the placeholder with the top edge of the font.
96    /// When the placeholder is very tall, the extra space will hang from
97    /// the top and extend through the bottom of the line.
98    Top,
99
100    /// Align the bottom edge of the placeholder with the top edge of the font.
101    /// When the placeholder is very tall, the extra space will rise from
102    /// the bottom and extend through the top of the line.
103    Bottom,
104
105    /// Align the middle of the placeholder with the middle of the text. When the
106    /// placeholder is very tall, the extra space will grow equally from
107    /// the top and bottom of the line.
108    Middle,
109}
110native_transmutable!(
111    sb::skia_textlayout_PlaceholderAlignment,
112    PlaceholderAlignment
113);
114
115pub type FontFeature = Handle<sb::skia_textlayout_FontFeature>;
116unsafe_send_sync!(FontFeature);
117
118impl NativeDrop for sb::skia_textlayout_FontFeature {
119    fn drop(&mut self) {
120        unsafe { sb::C_FontFeature_destruct(self) }
121    }
122}
123
124impl NativeClone for sb::skia_textlayout_FontFeature {
125    fn clone(&self) -> Self {
126        construct(|ts| unsafe { sb::C_FontFeature_CopyConstruct(ts, self) })
127    }
128}
129
130impl PartialEq for FontFeature {
131    fn eq(&self, other: &Self) -> bool {
132        self.name() == other.name() && self.value() == other.value()
133    }
134}
135
136impl fmt::Debug for FontFeature {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.debug_tuple("FontFeature")
139            .field(&self.name())
140            .field(&self.value())
141            .finish()
142    }
143}
144
145impl FontFeature {
146    pub fn name(&self) -> &str {
147        self.native().fName.as_str()
148    }
149
150    pub fn value(&self) -> i32 {
151        self.native().fValue
152    }
153}
154
155#[repr(C)]
156#[derive(Clone, Default, Debug)]
157pub struct PlaceholderStyle {
158    pub width: scalar,
159    pub height: scalar,
160    pub alignment: PlaceholderAlignment,
161    pub baseline: TextBaseline,
162    /// Distance from the top edge of the rect to the baseline position. This
163    /// baseline will be aligned against the alphabetic baseline of the surrounding
164    /// text.
165    ///
166    /// Positive values drop the baseline lower (positions the rect higher) and
167    /// small or negative values will cause the rect to be positioned underneath
168    /// the line. When baseline == height, the bottom edge of the rect will rest on
169    /// the alphabetic baseline.
170    pub baseline_offset: scalar,
171}
172
173native_transmutable!(sb::skia_textlayout_PlaceholderStyle, PlaceholderStyle);
174
175impl PartialEq for PlaceholderStyle {
176    fn eq(&self, other: &Self) -> bool {
177        unsafe { self.native().equals(other.native()) }
178    }
179}
180
181impl PlaceholderStyle {
182    pub fn new(
183        width: scalar,
184        height: scalar,
185        alignment: PlaceholderAlignment,
186        baseline: TextBaseline,
187        offset: scalar,
188    ) -> Self {
189        Self {
190            width,
191            height,
192            alignment,
193            baseline,
194            baseline_offset: offset,
195        }
196    }
197}
198
199pub type TextStyle = Handle<sb::skia_textlayout_TextStyle>;
200unsafe_send_sync!(TextStyle);
201
202impl NativeDrop for sb::skia_textlayout_TextStyle {
203    fn drop(&mut self) {
204        unsafe { sb::C_TextStyle_destruct(self) }
205    }
206}
207
208impl NativeClone for sb::skia_textlayout_TextStyle {
209    fn clone(&self) -> Self {
210        construct(|ts| unsafe { sb::C_TextStyle_CopyConstruct(ts, self) })
211    }
212}
213
214impl NativePartialEq for sb::skia_textlayout_TextStyle {
215    fn eq(&self, rhs: &Self) -> bool {
216        unsafe { self.equals(rhs) }
217    }
218}
219
220impl Default for TextStyle {
221    fn default() -> Self {
222        Self::new()
223    }
224}
225
226impl fmt::Debug for TextStyle {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.debug_struct("TextStyle")
229            .field("color", &self.color())
230            .field("has_foreground", &self.has_foreground())
231            .field("foreground", &self.foreground())
232            .field("has_background", &self.has_background())
233            .field("background", &self.background())
234            .field("decoration", &self.decoration())
235            .field("font_style", &self.font_style())
236            .field("shadows", &self.shadows())
237            .field("font_features", &self.font_features())
238            .field("font_size", &self.font_size())
239            .field("font_families", &self.font_families())
240            .field("baseline_shift", &self.baseline_shift())
241            .field("height", &self.height())
242            .field("height_override", &self.height_override())
243            .field("half_leading", &self.half_leading())
244            .field("letter_spacing", &self.letter_spacing())
245            .field("word_spacing", &self.word_spacing())
246            .field("typeface", &self.typeface())
247            .field("locale", &self.locale())
248            .field("text_baseline", &self.text_baseline())
249            .field("is_placeholder", &self.is_placeholder())
250            .finish()
251    }
252}
253
254impl TextStyle {
255    pub fn new() -> Self {
256        TextStyle::construct(|ts| unsafe { sb::C_TextStyle_Construct(ts) })
257    }
258
259    #[deprecated(since = "0.51.0", note = "Use clone_for_placeholder")]
260    #[must_use]
261    pub fn to_placeholder(&self) -> Self {
262        self.clone_for_placeholder()
263    }
264
265    #[must_use]
266    pub fn clone_for_placeholder(&self) -> Self {
267        Self::construct(|ts| unsafe { sb::C_TextStyle_cloneForPlaceholder(self.native(), ts) })
268    }
269
270    pub fn equals(&self, other: &TextStyle) -> bool {
271        *self == *other
272    }
273
274    pub fn equals_by_fonts(&self, that: &TextStyle) -> bool {
275        unsafe { self.native().equalsByFonts(that.native()) }
276    }
277
278    pub fn match_one_attribute(&self, style_type: StyleType, other: &TextStyle) -> bool {
279        unsafe { self.native().matchOneAttribute(style_type, other.native()) }
280    }
281
282    pub fn color(&self) -> Color {
283        Color::from_native_c(self.native().fColor)
284    }
285
286    pub fn set_color(&mut self, color: impl Into<Color>) -> &mut Self {
287        self.native_mut().fColor = color.into().into_native();
288        self
289    }
290
291    pub fn has_foreground(&self) -> bool {
292        self.native().fHasForeground
293    }
294
295    pub fn foreground(&self) -> Paint {
296        Paint::construct(|p| unsafe { sb::C_TextStyle_getForeground(self.native(), p) })
297    }
298
299    pub fn set_foreground_paint(&mut self, paint: &Paint) -> &mut Self {
300        unsafe { sb::C_TextStyle_setForegroundPaint(self.native_mut(), paint.native()) };
301        self
302    }
303
304    #[deprecated(since = "0.64.0", note = "use set_foreground_paint()")]
305    pub fn set_foreground_color(&mut self, paint: &Paint) -> &mut Self {
306        self.set_foreground_paint(paint)
307    }
308
309    pub fn clear_foreground_color(&mut self) -> &mut Self {
310        self.native_mut().fHasForeground = false;
311        self
312    }
313
314    pub fn has_background(&self) -> bool {
315        self.native().fHasBackground
316    }
317
318    pub fn background(&self) -> Paint {
319        Paint::construct(|p| unsafe { sb::C_TextStyle_getBackground(self.native(), p) })
320    }
321
322    pub fn set_background_paint(&mut self, paint: &Paint) -> &mut Self {
323        unsafe { sb::C_TextStyle_setBackgroundPaint(self.native_mut(), paint.native()) };
324        self
325    }
326
327    #[deprecated(since = "0.64.0", note = "use set_background_paint()")]
328    pub fn set_background_color(&mut self, paint: &Paint) -> &mut Self {
329        self.set_background_paint(paint)
330    }
331
332    pub fn clear_background_color(&mut self) -> &mut Self {
333        self.native_mut().fHasBackground = false;
334        self
335    }
336
337    pub fn decoration(&self) -> &Decoration {
338        Decoration::from_native_ref(&self.native().fDecoration)
339    }
340
341    pub fn decoration_type(&self) -> TextDecoration {
342        self.decoration().ty
343    }
344
345    pub fn decoration_mode(&self) -> TextDecorationMode {
346        self.decoration().mode
347    }
348
349    pub fn decoration_color(&self) -> Color {
350        self.decoration().color
351    }
352
353    pub fn decoration_style(&self) -> TextDecorationStyle {
354        self.decoration().style
355    }
356
357    pub fn decoration_thickness_multiplier(&self) -> scalar {
358        self.decoration().thickness_multiplier
359    }
360
361    pub fn set_decoration(&mut self, decoration: &Decoration) {
362        *self.decoration_mut_internal() = *decoration;
363    }
364
365    pub fn set_decoration_type(&mut self, decoration: TextDecoration) {
366        self.decoration_mut_internal().ty = decoration;
367    }
368
369    pub fn set_decoration_mode(&mut self, mode: TextDecorationMode) {
370        self.decoration_mut_internal().mode = mode;
371    }
372
373    pub fn set_decoration_style(&mut self, style: TextDecorationStyle) {
374        self.decoration_mut_internal().style = style;
375    }
376
377    pub fn set_decoration_color(&mut self, color: impl Into<Color>) {
378        self.decoration_mut_internal().color = color.into();
379    }
380
381    pub fn set_decoration_thickness_multiplier(&mut self, multiplier: scalar) {
382        self.decoration_mut_internal().thickness_multiplier = multiplier;
383    }
384
385    #[deprecated(since = "0.63.1", note = "use set_decoration()")]
386    pub fn decoration_mut(&mut self) -> &mut Decoration {
387        self.decoration_mut_internal()
388    }
389
390    fn decoration_mut_internal(&mut self) -> &mut Decoration {
391        Decoration::from_native_ref_mut(&mut self.native_mut().fDecoration)
392    }
393
394    pub fn font_style(&self) -> FontStyle {
395        FontStyle::from_native_c(self.native().fFontStyle)
396    }
397
398    pub fn set_font_style(&mut self, font_style: FontStyle) -> &mut Self {
399        self.native_mut().fFontStyle = font_style.into_native();
400        self
401    }
402
403    pub fn shadows(&self) -> &[TextShadow] {
404        unsafe {
405            let mut count = 0;
406            let ptr = sb::C_TextStyle_getShadows(&self.native().fTextShadows, &mut count);
407            safer::from_raw_parts(TextShadow::from_native_ptr(ptr), count)
408        }
409    }
410
411    pub fn add_shadow(&mut self, shadow: TextShadow) -> &mut Self {
412        unsafe { sb::C_TextStyle_addShadow(self.native_mut(), shadow.native()) }
413        self
414    }
415
416    pub fn reset_shadows(&mut self) -> &mut Self {
417        unsafe { sb::C_TextStyle_resetShadows(self.native_mut()) }
418        self
419    }
420
421    pub fn font_features(&self) -> &[FontFeature] {
422        unsafe {
423            let mut count = 0;
424            let ptr = sb::C_TextStyle_getFontFeatures(&self.native().fFontFeatures, &mut count);
425            safer::from_raw_parts(FontFeature::from_native_ptr(ptr), count)
426        }
427    }
428
429    pub fn add_font_feature(&mut self, font_feature: impl AsRef<str>, value: i32) {
430        let font_feature = interop::String::from_str(font_feature);
431        unsafe { sb::C_TextStyle_addFontFeature(self.native_mut(), font_feature.native(), value) }
432    }
433
434    pub fn reset_font_features(&mut self) {
435        unsafe { sb::C_TextStyle_resetFontFeatures(self.native_mut()) }
436    }
437
438    pub fn font_arguments(&self) -> Option<&FontArguments> {
439        unsafe { sb::C_TextStyle_getFontArguments(self.native()) }
440            .into_non_null()
441            .map(|ptr| FontArguments::from_native_ref(unsafe { ptr.as_ref() }))
442    }
443
444    /// The contents of the [`crate::FontArguments`] will be copied into the [`TextStyle`].
445    pub fn set_font_arguments<'fa>(
446        &mut self,
447        arguments: impl Into<Option<&'fa crate::FontArguments<'fa, 'fa>>>,
448    ) {
449        unsafe {
450            sb::C_TextStyle_setFontArguments(
451                self.native_mut(),
452                arguments.into().native_ptr_or_null(),
453            )
454        }
455    }
456
457    pub fn font_size(&self) -> scalar {
458        self.native().fFontSize
459    }
460
461    pub fn set_font_size(&mut self, size: scalar) -> &mut Self {
462        self.native_mut().fFontSize = size;
463        self
464    }
465
466    pub fn font_families(&self) -> FontFamilies {
467        unsafe {
468            let mut count = 0;
469            let ptr = sb::C_TextStyle_getFontFamilies(self.native(), &mut count);
470            FontFamilies(safer::from_raw_parts(ptr, count))
471        }
472    }
473
474    pub fn set_font_families(&mut self, families: &[impl AsRef<str>]) -> &mut Self {
475        let families: Vec<interop::String> = FromStrs::from_strs(families);
476        let families = families.native();
477        unsafe {
478            sb::C_TextStyle_setFontFamilies(self.native_mut(), families.as_ptr(), families.len())
479        }
480        self
481    }
482
483    pub fn baseline_shift(&self) -> scalar {
484        self.native().fBaselineShift
485    }
486
487    pub fn set_baseline_shift(&mut self, baseline_shift: scalar) -> &mut Self {
488        self.native_mut().fBaselineShift = baseline_shift;
489        self
490    }
491
492    pub fn set_height(&mut self, height: scalar) -> &mut Self {
493        self.native_mut().fHeight = height;
494        self
495    }
496
497    pub fn height(&self) -> scalar {
498        let n = self.native();
499        if n.fHeightOverride {
500            n.fHeight
501        } else {
502            0.0
503        }
504    }
505
506    pub fn set_height_override(&mut self, height_override: bool) -> &mut Self {
507        self.native_mut().fHeightOverride = height_override;
508        self
509    }
510
511    pub fn height_override(&self) -> bool {
512        self.native().fHeightOverride
513    }
514
515    pub fn set_half_leading(&mut self, half_leading: bool) -> &mut Self {
516        self.native_mut().fHalfLeading = half_leading;
517        self
518    }
519
520    pub fn half_leading(&self) -> bool {
521        self.native().fHalfLeading
522    }
523
524    pub fn set_letter_spacing(&mut self, letter_spacing: scalar) -> &mut Self {
525        self.native_mut().fLetterSpacing = letter_spacing;
526        self
527    }
528
529    pub fn letter_spacing(&self) -> scalar {
530        self.native().fLetterSpacing
531    }
532
533    pub fn set_word_spacing(&mut self, word_spacing: scalar) -> &mut Self {
534        self.native_mut().fWordSpacing = word_spacing;
535        self
536    }
537
538    pub fn word_spacing(&self) -> scalar {
539        self.native().fWordSpacing
540    }
541
542    pub fn typeface(&self) -> Option<Typeface> {
543        Typeface::from_unshared_ptr(self.native().fTypeface.fPtr)
544    }
545
546    pub fn set_typeface(&mut self, typeface: impl Into<Option<Typeface>>) -> &mut Self {
547        unsafe {
548            sb::C_TextStyle_setTypeface(self.native_mut(), typeface.into().into_ptr_or_null())
549        }
550        self
551    }
552
553    pub fn locale(&self) -> &str {
554        self.native().fLocale.as_str()
555    }
556
557    pub fn set_locale(&mut self, locale: impl AsRef<str>) -> &mut Self {
558        self.native_mut().fLocale.set_str(locale);
559        self
560    }
561
562    pub fn text_baseline(&self) -> TextBaseline {
563        self.native().fTextBaseline
564    }
565
566    pub fn set_text_baseline(&mut self, baseline: TextBaseline) -> &mut Self {
567        self.native_mut().fTextBaseline = baseline;
568        self
569    }
570
571    pub fn font_metrics(&self) -> FontMetrics {
572        FontMetrics::construct(|fm| unsafe { self.native().getFontMetrics(fm) })
573    }
574
575    pub fn is_placeholder(&self) -> bool {
576        self.native().fIsPlaceholder
577    }
578
579    pub fn set_placeholder(&mut self) -> &mut Self {
580        self.native_mut().fIsPlaceholder = true;
581        self
582    }
583}
584
585pub type TextIndex = usize;
586pub type TextRange = Range<usize>;
587pub const EMPTY_TEXT: TextRange = EMPTY_RANGE;
588
589#[repr(C)]
590#[derive(Clone, PartialEq, Debug)]
591pub struct Block {
592    pub range: TextRange,
593    pub style: TextStyle,
594}
595
596native_transmutable!(sb::skia_textlayout_Block, Block);
597
598impl Default for Block {
599    fn default() -> Self {
600        Self {
601            range: EMPTY_RANGE,
602            style: Default::default(),
603        }
604    }
605}
606
607impl Block {
608    pub fn new(text_range: TextRange, style: TextStyle) -> Self {
609        Self {
610            range: text_range,
611            style,
612        }
613    }
614
615    pub fn add(&mut self, tail: TextRange) -> &mut Self {
616        debug_assert!(self.range.end == tail.start);
617        self.range = self.range.start..self.range.start + self.range.width() + tail.width();
618        self
619    }
620}
621
622pub type BlockIndex = usize;
623pub type BlockRange = Range<usize>;
624
625pub const EMPTY_BLOCK: usize = EMPTY_INDEX;
626pub const EMPTY_BLOCKS: Range<usize> = EMPTY_RANGE;
627
628#[repr(C)]
629#[derive(Clone, PartialEq, Debug)]
630pub struct Placeholder {
631    pub range: TextRange,
632    pub style: PlaceholderStyle,
633    pub text_style: TextStyle,
634    pub blocks_before: BlockRange,
635    pub text_before: TextRange,
636}
637
638native_transmutable!(sb::skia_textlayout_Placeholder, Placeholder);
639
640impl Default for Placeholder {
641    fn default() -> Self {
642        #[allow(clippy::reversed_empty_ranges)]
643        Self {
644            range: EMPTY_RANGE,
645            style: Default::default(),
646            text_style: Default::default(),
647            blocks_before: 0..0,
648            text_before: 0..0,
649        }
650    }
651}
652
653impl Placeholder {
654    pub fn new(
655        range: Range<usize>,
656        style: PlaceholderStyle,
657        text_style: TextStyle,
658        blocks_before: BlockRange,
659        text_before: TextRange,
660    ) -> Self {
661        Self {
662            range,
663            style,
664            text_style,
665            blocks_before,
666            text_before,
667        }
668    }
669}
670
671#[cfg(test)]
672mod tests {
673    use super::*;
674
675    #[test]
676    fn getting_setting_comparing_font_arguments() {
677        let mut ts = TextStyle::new();
678        let mut fa = crate::FontArguments::default();
679        fa.set_collection_index(100);
680        ts.set_font_arguments(&fa);
681        let tl_fa: FontArguments = fa.into();
682        let fa = ts.font_arguments().unwrap();
683        assert_eq!(tl_fa, *fa);
684        let default_fa: FontArguments = crate::FontArguments::default().into();
685        assert_ne!(default_fa, *fa);
686    }
687}