waft_widgets/media/
subtitle_view.rs1use 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#[derive(Clone)]
32pub struct SubtitleView {
33 pub key: Option<KeyRef>,
34 pub cues: Vec<Cue>,
36 pub bottom_padding_fraction: f32,
38}
39
40impl SubtitleView {
41 pub const DEFAULT_BOTTOM_PADDING_FRACTION: f32 = 0.08;
44
45 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 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
91struct CanvasSubtitleOutput {
93 cues: Vec<Cue>,
94 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 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
140fn 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 fn text_in(color: Color) -> CaptionStyle {
189 CaptionStyle {
190 foreground_color: Some(CaptionSetting::always(color)),
191 ..CaptionStyle::default()
192 }
193 }
194
195 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 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}