Skip to main content

waft_widgets/media/
subtitle_view.rs

1// Ported from Media3's `SubtitleView.java` and `CanvasSubtitleOutput.java`
2// (https://github.com/androidx/media), Copyright (C) 2016 The Android Open Source Project, licensed
3// under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0). Changed: a
4// widget that takes Waft's cues and always draws them in the user's caption style, which it
5// reads from the ambient `MediaQuery`, so it has no style, text size or embedded-style switches
6// of its own.
7
8//! Media3's `SubtitleView`, drawing on a canvas as its `CanvasSubtitleOutput` does: a player's cues
9//! over the rectangle of its picture, each painted by `subtitle_painter` with the user's caption
10//! style merged in, as Media3's `setUserDefaultStyle` and `setUserDefaultTextSize` have it. It
11//! fills the space it is given, which is the picture's rectangle where a `PlayerView` puts it, so a
12//! cue's fractions are of the picture.
13//!
14//! The style is the ambient `MediaQuery`'s, which follows the platform's caption settings, so
15//! the view is built again when the user changes them; where the platform keeps none, no setting
16//! is merged and the media's own style shows.
17
18use std::any::Any;
19use std::fmt;
20
21use waft_embedder::{Canvas, CaptionStyle, Cue, CueAnchor, CueLine, Rect, Size};
22use waft_foundation::App;
23use waft_rendering::CustomPainter;
24
25use super::subtitle_painter;
26use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
27use crate::widgets::basic::CustomPaint;
28use crate::widgets::media_query::MediaQuery;
29
30/// A view for displaying subtitle cues, laid out as large as it is let be.
31#[derive(Clone)]
32pub struct SubtitleView {
33    pub key: Option<KeyRef>,
34    /// The cues to display.
35    pub cues: Vec<Cue>,
36    /// The bottom padding to apply when a cue has no `line`, as a fraction of the view's height.
37    pub bottom_padding_fraction: f32,
38}
39
40impl SubtitleView {
41    /// The default bottom padding to apply when a cue has no `line`, as a fraction of the
42    /// viewport height.
43    pub const DEFAULT_BOTTOM_PADDING_FRACTION: f32 = 0.08;
44
45    /// A view displaying `cues`: Media3's `setCues`.
46    pub fn new(cues: Vec<Cue>) -> SubtitleView {
47        SubtitleView {
48            key: None,
49            cues,
50            bottom_padding_fraction: SubtitleView::DEFAULT_BOTTOM_PADDING_FRACTION,
51        }
52    }
53
54    pub fn key(mut self, key: KeyRef) -> SubtitleView {
55        self.key = Some(key);
56        self
57    }
58
59    /// Media3's `setBottomPaddingFraction`.
60    pub fn bottom_padding_fraction(mut self, bottom_padding_fraction: f32) -> SubtitleView {
61        self.bottom_padding_fraction = bottom_padding_fraction;
62        self
63    }
64}
65
66impl fmt::Debug for SubtitleView {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.debug_struct("SubtitleView")
69            .field("cues", &self.cues)
70            .finish_non_exhaustive()
71    }
72}
73
74impl StatelessWidget for SubtitleView {
75    fn key(&self) -> Option<&KeyRef> {
76        self.key.as_ref()
77    }
78
79    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
80        CustomPaint::new()
81            .painter(CanvasSubtitleOutput {
82                cues: self.cues.clone(),
83                style: MediaQuery::maybe_caption_style_of(app, context).unwrap_or_default(),
84                bottom_padding_fraction: self.bottom_padding_fraction,
85            })
86            .size(Size::INFINITE)
87            .into_widget()
88    }
89}
90
91/// Media3's `CanvasSubtitleOutput`: paints each cue with `subtitle_painter`.
92struct CanvasSubtitleOutput {
93    cues: Vec<Cue>,
94    /// The user's caption style, with no setting where the platform keeps none.
95    style: CaptionStyle,
96    bottom_padding_fraction: f32,
97}
98
99impl CustomPainter for CanvasSubtitleOutput {
100    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
101        if self.cues.is_empty() {
102            return;
103        }
104        let cue_box = Rect::from_ltwh(0.0, 0.0, size.width(), size.height());
105        if cue_box.is_empty() {
106            // No space to draw subtitles.
107            return;
108        }
109        for cue in &self.cues {
110            let cue = match cue.vertical {
111                Some(_) => reposition_vertical_cue(cue),
112                None => cue.clone(),
113            };
114            subtitle_painter::draw(
115                app,
116                canvas,
117                &cue,
118                &self.style,
119                f64::from(self.bottom_padding_fraction),
120                cue_box,
121            );
122        }
123    }
124
125    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
126        let Some(old_delegate) = old_delegate.as_any().downcast_ref::<CanvasSubtitleOutput>()
127        else {
128            return true;
129        };
130        self.cues != old_delegate.cues
131            || self.style != old_delegate.style
132            || self.bottom_padding_fraction != old_delegate.bottom_padding_fraction
133    }
134
135    fn as_any(&self) -> &dyn Any {
136        self
137    }
138}
139
140/// Reposition a vertical cue for horizontal display.
141///
142/// This view doesn't support rendering vertical text, but if we naively interpret a vertical
143/// cue's `position` and `line` for horizontal display then the cues will often be displayed in
144/// unexpected positions. For example, the 'default' position for right-to-left vertical subtitles
145/// is the right-hand edge of the viewport, so cues that would appear vertically in this position
146/// should appear horizontally at the bottom of the viewport (generally the default position).
147/// Similarly left-edge right-to-left vertical cues should be shown at the top of a horizontal
148/// viewport.
149///
150/// There isn't a meaningful way to transform `position` and related values (e.g. alignment), so
151/// we clear these and allow `subtitle_painter` to do the default behaviour of centering the cue.
152fn reposition_vertical_cue(cue: &Cue) -> Cue {
153    let line = cue.line.map(|line| match line {
154        CueLine::Fraction(line) => CueLine::Fraction(1.0 - line),
155        CueLine::Number(line) => CueLine::Number(-line - 1),
156    });
157    let line_anchor = match cue.line_anchor {
158        CueAnchor::End => CueAnchor::Start,
159        CueAnchor::Start => CueAnchor::End,
160        CueAnchor::Middle => CueAnchor::Middle,
161    };
162    Cue {
163        position: None,
164        position_anchor: CueAnchor::Start,
165        text_alignment: waft_embedder::CueTextAlignment::Center,
166        line,
167        line_anchor,
168        ..cue.clone()
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use std::rc::Rc;
175
176    use waft_embedder::valo::Op;
177    use waft_embedder::{CaptionSetting, Color, CueContent, CueTextRun, CueVertical};
178    use waft_test::{MockCaptionSettings, TestPlatform};
179
180    use super::*;
181    use crate::testing::{WidgetTester, test_widgets};
182
183    const RED: Color = Color::new(0xFFFF_0000);
184    const GREEN: Color = Color::new(0xFF00_FF00);
185    const BLUE: Color = Color::new(0xFF00_00FF);
186
187    /// A style whose text is `color` over whatever the media says.
188    fn text_in(color: Color) -> CaptionStyle {
189        CaptionStyle {
190            foreground_color: Some(CaptionSetting::always(color)),
191            ..CaptionStyle::default()
192        }
193    }
194
195    /// The colours of the glyph runs the tester's view last drew.
196    fn glyph_colors(tester: &WidgetTester) -> Vec<waft_embedder::valo::Color> {
197        let scene = tester.view().last_scene().expect("a frame was presented");
198        waft_embedder::flattened_ops(&waft_embedder::slices(&scene, |_| None).picture_with_room())
199            .into_iter()
200            .filter_map(|op| match op {
201                Op::GlyphRun { paint, .. } => Some(paint.color),
202                _ => None,
203            })
204            .collect()
205    }
206
207    /// Pumps a subtitle view showing a cue whose text the media colours blue.
208    fn pump_a_blue_cue(tester: &mut WidgetTester) {
209        let mut said = CueTextRun::new("Hello");
210        said.color = Some(BLUE);
211        let cue = Cue::new(CueContent::Text(vec![said]));
212        tester.pump_widget(SubtitleView::new(vec![cue]));
213    }
214
215    #[test]
216    fn a_subtitle_view_draws_in_the_users_caption_style_and_follows_its_changes() {
217        let settings = MockCaptionSettings::new(text_in(RED));
218        let tester = &mut WidgetTester::with_platform(
219            TestPlatform::new().with_caption_settings(Rc::new(settings.clone())),
220        );
221        pump_a_blue_cue(tester);
222        assert!(glyph_colors(tester).contains(&RED.into()), "the user's red");
223
224        settings.set_style(text_in(GREEN));
225        tester.cell.checkpoint();
226        tester.pump();
227        let colors = glyph_colors(tester);
228        assert!(colors.contains(&GREEN.into()), "the new style: {colors:?}");
229        assert!(!colors.contains(&RED.into()));
230    }
231
232    #[test]
233    fn a_subtitle_view_draws_the_medias_own_style_where_the_platform_has_no_caption_settings() {
234        test_widgets(|tester| {
235            pump_a_blue_cue(tester);
236            let colors = glyph_colors(tester);
237            assert!(
238                colors.contains(&BLUE.into()),
239                "the media's blue: {colors:?}"
240            );
241        });
242    }
243
244    #[test]
245    fn a_vertical_cue_is_shown_across_on_the_opposite_side_centred() {
246        let mut cue = Cue::new(CueContent::Text(vec![CueTextRun::new("縦")]));
247        cue.vertical = Some(CueVertical::RightToLeft);
248        cue.line = Some(CueLine::Fraction(0.9));
249        cue.line_anchor = CueAnchor::End;
250        cue.position = Some(0.2);
251        let shown = reposition_vertical_cue(&cue);
252        assert_eq!(shown.line, Some(CueLine::Fraction(1.0 - 0.9)));
253        assert_eq!(shown.line_anchor, CueAnchor::Start);
254        assert_eq!(shown.position, None);
255
256        cue.line = Some(CueLine::Number(0));
257        assert_eq!(
258            reposition_vertical_cue(&cue).line,
259            Some(CueLine::Number(-1))
260        );
261    }
262}