Skip to main content

cosmic_applet_avestruz/views/components/
video_box.rs

1// SPDX-License-Identifier: MIT
2
3//! A video a note links to, in the note's row: the room it plays in, and
4//! under that a bar to play it by.
5//!
6//! Until it is played there is a play button, over the picture the note
7//! gave for it if it gave one, or one of YouTube's if it is there, and
8//! nothing of the video has been asked for.
9//! Pressed, it plays where it is (see [`crate::video`]): the bar then has
10//! play and pause, how far in it is and of how long, a slider to go
11//! elsewhere in it, and its sound: a button that turns it off and on and
12//! says how loud it is, and beside it, while the pointer is over either,
13//! a slider that sets that. A click on the picture holds it and lets it
14//! go, as the button does. Beside the sound is how fast it plays, which
15//! opens a menu of speeds. At the end of the bar, either way, the
16//! link it came as opens in the browser.
17//!
18//! The room is the same before, while and after: what the note says the
19//! video's proportions are, or the usual ones, across the whole row (see
20//! [`box_size`]). What plays is fitted inside it, between bars if it is
21//! another shape, so nothing under it moves because it was played.
22
23use std::borrow::Cow;
24
25use cosmic::Element;
26use cosmic::iced::core::widget::{Operation, Tree};
27use cosmic::iced::core::{Clipboard, Layout, Rectangle, Shell, Size, Vector, Widget, layout, overlay, renderer};
28use cosmic::iced::widget::svg;
29use cosmic::iced::widget::text::Wrapping;
30use cosmic::iced::{Alignment, Background, Border, Color, ContentFit, Event, Length, Point, mouse};
31use cosmic::widget::popover::{Position, popover};
32use cosmic::widget::{self, button, container, icon, text};
33
34use crate::fl;
35use crate::helpers::truncate_chars;
36use crate::images::{ImageShape, ImageState};
37use crate::messages::Message;
38use crate::video::{Loudness, Playback, Speed, box_size, clock};
39use crate::views::components::note_row::RowContext;
40use crate::views::components::{CARD_BORDER, CARD_RADIUS, MENU_GAP, card_style, choice_menu};
41
42/// How tall the bar under a video is, and the room at its ends and
43/// between what is on it.
44const VIDEO_BAR_HEIGHT: f32 = 36.0;
45const VIDEO_BAR_PADDING: u16 = 4;
46const VIDEO_BAR_SPACING: u16 = 6;
47
48/// The play button over a video that is not playing: how large its icon
49/// is, the room around it, and how dark the disc it sits on.
50const PLAY_ICON_SIZE: u16 = 32;
51const PLAY_PADDING: u16 = 12;
52const PLAY_DISC: f32 = 0.6;
53
54/// How wide the slider is that sets how loud a video is.
55const VOLUME_WIDTH: f32 = 64.0;
56
57/// The room the speed a video plays at has on the bar, whichever speed it
58/// is, so that nothing beside it moves when another is chosen; and how
59/// wide the menu of speeds is.
60const SPEED_SIZE: (f32, f32) = (44.0, 24.0);
61const SPEED_MENU_WIDTH: f32 = 112.0;
62
63/// How much of why a video can't be played is said in its place.
64const VIDEO_REASON_MAX_CHARS: usize = 160;
65
66/// How tall a video is in a row `width` wide, bar and all, when its note
67/// says it is `size` pixels, or doesn't say.
68pub fn video_height(size: Option<(u32, u32)>, width: f32) -> f32 {
69    box_size(size, (width - 2.0 * CARD_BORDER).max(1.0)).height + VIDEO_BAR_HEIGHT + 2.0 * CARD_BORDER
70}
71
72/// What is in it, in the room a video of `size` pixels is given: as wide
73/// as there is room, and as tall as [`box_size`] makes that.
74struct Screen<'a> {
75    size: Option<(u32, u32)>,
76    content: Element<'a, Message>,
77}
78
79impl Widget<Message, cosmic::Theme, cosmic::Renderer> for Screen<'_> {
80    fn children(&self) -> Vec<Tree> {
81        vec![Tree::new(&self.content)]
82    }
83
84    fn diff(&mut self, tree: &mut Tree) {
85        tree.diff_children(std::slice::from_mut(&mut self.content));
86    }
87
88    fn size(&self) -> Size<Length> {
89        Size::new(Length::Fill, Length::Shrink)
90    }
91
92    fn layout(&mut self, tree: &mut Tree, renderer: &cosmic::Renderer, limits: &layout::Limits) -> layout::Node {
93        let size = box_size(self.size, limits.max().width);
94        let within = layout::Limits::new(Size::ZERO, size);
95        let content = tree.children.first_mut().map(|tree| self.content.as_widget_mut().layout(tree, renderer, &within));
96        layout::Node::with_children(size, content.into_iter().collect())
97    }
98
99    fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &cosmic::Renderer, operation: &mut dyn Operation) {
100        if let (Some(tree), Some(content)) = (tree.children.first_mut(), layout.children().next()) {
101            self.content.as_widget_mut().operate(tree, content, renderer, operation);
102        }
103    }
104
105    fn update(
106        &mut self,
107        tree: &mut Tree,
108        event: &Event,
109        layout: Layout<'_>,
110        cursor: mouse::Cursor,
111        renderer: &cosmic::Renderer,
112        clipboard: &mut dyn Clipboard,
113        shell: &mut Shell<'_, Message>,
114        viewport: &Rectangle,
115    ) {
116        if let (Some(tree), Some(content)) = (tree.children.first_mut(), layout.children().next()) {
117            self.content.as_widget_mut().update(tree, event, content, cursor, renderer, clipboard, shell, viewport);
118        }
119    }
120
121    fn draw(
122        &self,
123        tree: &Tree,
124        renderer: &mut cosmic::Renderer,
125        theme: &cosmic::Theme,
126        style: &renderer::Style,
127        layout: Layout<'_>,
128        cursor: mouse::Cursor,
129        viewport: &Rectangle,
130    ) {
131        if let (Some(tree), Some(content)) = (tree.children.first(), layout.children().next()) {
132            self.content.as_widget().draw(tree, renderer, theme, style, content, cursor, viewport);
133        }
134    }
135
136    fn mouse_interaction(
137        &self,
138        tree: &Tree,
139        layout: Layout<'_>,
140        cursor: mouse::Cursor,
141        viewport: &Rectangle,
142        renderer: &cosmic::Renderer,
143    ) -> mouse::Interaction {
144        match (tree.children.first(), layout.children().next()) {
145            (Some(tree), Some(content)) => self.content.as_widget().mouse_interaction(tree, content, cursor, viewport, renderer),
146            _ => mouse::Interaction::None,
147        }
148    }
149
150    fn overlay<'b>(
151        &'b mut self,
152        tree: &'b mut Tree,
153        layout: Layout<'b>,
154        renderer: &cosmic::Renderer,
155        viewport: &Rectangle,
156        translation: Vector,
157    ) -> Option<overlay::Element<'b, Message, cosmic::Theme, cosmic::Renderer>> {
158        let (tree, content) = (tree.children.first_mut()?, layout.children().next()?);
159        self.content.as_widget_mut().overlay(tree, content, renderer, viewport, translation)
160    }
161}
162
163/// An icon in `color`, `size` across.
164fn tinted<'a>(name: &'static str, size: u16, color: Color) -> Element<'a, Message> {
165    icon::icon(icon::from_name(name).handle())
166        .size(size)
167        .class(cosmic::theme::Svg::custom(move |_theme| svg::Style { color: Some(color) }))
168        .into()
169}
170
171/// The play button over a video: white, on a dark disc, so that it shows
172/// on whatever picture is under it.
173fn play_button<'a>() -> Element<'a, Message> {
174    let disc = f32::from(PLAY_ICON_SIZE + 2 * PLAY_PADDING);
175    on_dark(tinted("media-playback-start-symbolic", PLAY_ICON_SIZE, Color::WHITE), disc)
176}
177
178/// `shown`, in the middle of the room a video has.
179fn centred<'a>(shown: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
180    container(shown).center(Length::Fill).into()
181}
182
183/// A picture fitted into the room a video has, whole.
184fn fitted<'a>(handle: widget::image::Handle) -> Element<'a, Message> {
185    widget::image(handle).width(Length::Fill).height(Length::Fill).content_fit(ContentFit::Contain).into()
186}
187
188/// The picture that stands for a video until it plays: the first of
189/// `posters` that can be had, once it is here. The next is only asked
190/// for when the one before it could not be had.
191fn poster(posters: &[String], context: &RowContext<'_>) -> Option<widget::image::Handle> {
192    let first = posters.iter().find_map(|poster| match context.images.get(poster, ImageShape::Original) {
193        ImageState::Ready(loaded) => Some(Some(loaded.handle.clone())),
194        ImageState::Loading => Some(None),
195        ImageState::Failed => None,
196    });
197    first.flatten()
198}
199
200/// `shown`, on a dark ground that shows on whatever picture is under it,
201/// as the play button's does.
202fn on_dark<'a>(shown: impl Into<Element<'a, Message>>, radius: f32) -> Element<'a, Message> {
203    container(shown)
204        .padding(PLAY_PADDING)
205        .class(cosmic::theme::Container::custom(move |_theme| container::Style {
206            background: Some(Background::Color(Color { a: PLAY_DISC, ..Color::BLACK })),
207            border: Border { radius: radius.into(), ..Border::default() },
208            ..container::Style::default()
209        }))
210        .into()
211}
212
213/// What a video shows where it plays: its latest picture, or before it has
214/// one a picture that stands for it; and over that the play button while
215/// it is held, that it is on its way while it is, or why it can't be
216/// played, which is said on its own.
217fn screen<'a>(playback: Option<&'a Playback>, posters: &'a [String], context: &RowContext<'a>) -> Element<'a, Message> {
218    let failed = playback.is_some_and(|playback| playback.error.is_some());
219    let picture = match playback.and_then(|playback| playback.frame.clone()) {
220        _ if failed => None,
221        Some(frame) => Some(frame),
222        None => poster(posters, context),
223    };
224    let said = |said: String| text(said).size(context.sizes.time()).align_x(Alignment::Center).wrapping(Wrapping::WordOrGlyph);
225    let over: Option<Element<'a, Message>> = match playback {
226        Some(Playback { error: Some(why), .. }) => {
227            let why = truncate_chars(why.lines().next().unwrap_or_default(), VIDEO_REASON_MAX_CHARS);
228            Some(container(said(fl!("video-failed", error = why.as_ref()))).padding(PLAY_PADDING).into())
229        }
230        Some(playback) if playback.loading() => Some(on_dark(said(fl!("video-loading")), CARD_RADIUS)),
231        Some(playback) if playback.playing => None,
232        _ => Some(play_button()),
233    };
234
235    let layers = cosmic::iced::widget::stack(picture.map(fitted).into_iter().chain(over.map(centred)));
236    container(layers)
237        .width(Length::Fill)
238        .height(Length::Fill)
239        .class(cosmic::theme::Container::custom(|_theme| container::Style {
240            background: Some(Background::Color(Color::BLACK)),
241            text_color: Some(Color::WHITE),
242            border: Border {
243                radius: [CARD_RADIUS - CARD_BORDER, CARD_RADIUS - CARD_BORDER, 0.0, 0.0].into(),
244                ..Border::default()
245            },
246            ..container::Style::default()
247        }))
248        .into()
249}
250
251/// A button of the bar: an icon, what it does for whoever points at it,
252/// and what pressing it asks of the app.
253fn bar_button<'a>(name: &'static str, tooltip: String, on_press: Message) -> Element<'a, Message> {
254    button::icon(icon::from_name(name)).extra_small().tooltip(tooltip).on_press(on_press).into()
255}
256
257/// The sound of a video that was played: a button that turns it off and
258/// on, with a picture of how loud it is; and before it, while the pointer
259/// is over either or the slider is being dragged, a slider that sets how
260/// loud. The slider takes its room
261/// from the one beside it, so nothing else on the bar moves.
262fn sound<'a>(playback: &'a Playback) -> Element<'a, Message> {
263    let (picture, tooltip) = match playback.loudness() {
264        Loudness::Off if playback.muted => ("audio-volume-muted-symbolic", fl!("video-unmute")),
265        Loudness::Off => ("audio-volume-muted-symbolic", fl!("video-mute")),
266        Loudness::Low => ("audio-volume-low-symbolic", fl!("video-mute")),
267        Loudness::Medium => ("audio-volume-medium-symbolic", fl!("video-mute")),
268        Loudness::High => ("audio-volume-high-symbolic", fl!("video-mute")),
269    };
270    let slider = playback.sound_shows().then(|| {
271        widget::slider(0.0..=1.0, playback.volume, Message::VideoVolume)
272            .step(0.01)
273            .on_release(Message::VideoVolumeSet)
274            .width(Length::Fixed(VOLUME_WIDTH))
275    });
276    let controls = widget::Row::new()
277        .push_maybe(slider)
278        .push(bar_button(picture, tooltip, Message::VideoMute))
279        .spacing(VIDEO_BAR_SPACING)
280        .align_y(Alignment::Center);
281    // A press between the two is nobody's: it is not the video's to play
282    // or hold.
283    widget::mouse_area(controls)
284        .on_enter(Message::VideoSound(true))
285        .on_exit(Message::VideoSound(false))
286        .on_press(Message::VideoSound(true))
287        .into()
288}
289
290/// How fast videos play, to press: it opens a menu of the speeds there
291/// are, under it, or over it where there is no room under. A speed that
292/// is not the usual one is set in the accent colour: it holds for the
293/// next video too.
294fn speed<'a>(context: &RowContext<'a>) -> Element<'a, Message> {
295    let (chosen, small) = (context.videos.speed(), context.sizes.time());
296    let label = text(chosen.label()).size(small).wrapping(Wrapping::None);
297    let label = if chosen.is_usual() { label } else { label.class(cosmic::theme::Text::Color(context.accent)) };
298    let (across, down) = SPEED_SIZE;
299    let shown = button::custom(container(label).center(Length::Fill))
300        .padding(0)
301        .width(Length::Fixed(across))
302        .height(Length::Fixed(down))
303        .class(cosmic::theme::Button::Text)
304        .on_press(Message::VideoSpeedMenu);
305    let shown = widget::tooltip(shown, text(fl!("video-speed")).size(12), widget::tooltip::Position::Top);
306
307    let under = Point::new(0.0, down + MENU_GAP);
308    let mut shown = popover(shown).position(Position::Point(under)).on_close(Message::CloseVideoSpeedMenu);
309    if context.videos.speed_menu() {
310        let speeds = Speed::ALL.into_iter().map(|speed| (speed.label(), speed == chosen, Message::VideoSpeed(speed)));
311        shown = shown.popup(choice_menu(speeds, SPEED_MENU_WIDTH));
312    }
313    shown.into()
314}
315
316/// The bar under a video: play or pause; then, of a video that was
317/// played, how far in it is, a slider to go elsewhere in it once it is
318/// known how long it is, its sound, and, with the slider, how fast it
319/// plays: a live one has no length, so neither; of one that
320/// wasn't, the link it came as. At the end, opening that link in the browser.
321fn bar<'a>(url: &'a str, label: Cow<'a, str>, playback: Option<&'a Playback>, context: &RowContext<'a>) -> Element<'a, Message> {
322    let playing = playback.is_some_and(|playback| playback.playing);
323    let toggle = if playing {
324        bar_button("media-playback-pause-symbolic", fl!("video-pause"), Message::VideoPress(url.to_string()))
325    } else {
326        bar_button("media-playback-start-symbolic", fl!("video-play"), Message::VideoPress(url.to_string()))
327    };
328    let mut bar = widget::Row::new().push(toggle);
329
330    let small = context.sizes.time();
331    match playback.filter(|playback| playback.error.is_none()) {
332        Some(playback) => {
333            let at = playback.seeking.unwrap_or(playback.position);
334            let time = match playback.duration {
335                Some(all) => format!("{} / {}", clock(at), clock(all)),
336                None => clock(at),
337            };
338            bar = bar.push(text(time).size(small).wrapping(Wrapping::None));
339            bar = match playback.duration {
340                Some(all) => bar.push(
341                    widget::slider(0.0..=all, at.min(all), Message::VideoSeeking)
342                        .step(0.1)
343                        .on_release(Message::VideoSeek)
344                        .width(Length::Fill),
345                ),
346                None => bar.push(widget::Space::new().width(Length::Fill)),
347            };
348            bar = bar.push(sound(playback));
349            // One with no length is live: it plays at the speed it comes.
350            if playback.duration.is_some() {
351                bar = bar.push(speed(context));
352            }
353        }
354        None => bar = bar.push(container(text(label).size(small).wrapping(Wrapping::None)).width(Length::Fill).clip(true)),
355    }
356
357    bar.push(bar_button("window-pop-out-symbolic", fl!("video-open"), Message::OpenUrl(url.to_string())))
358        .spacing(VIDEO_BAR_SPACING)
359        .padding([0, VIDEO_BAR_PADDING])
360        .height(Length::Fixed(VIDEO_BAR_HEIGHT))
361        .align_y(Alignment::Center)
362        .into()
363}
364
365/// The video at `url`, for under the note that links to it: where it
366/// plays, in the proportions of `size`, with the first of `posters` that
367/// can be had standing for it until it does, and the bar it is played by, on which `label` stands for
368/// its address. A click anywhere on it that is not on something of the
369/// bar plays it, or holds it.
370pub fn video_box<'a>(
371    url: &'a str,
372    label: impl Into<Cow<'a, str>>,
373    size: Option<(u32, u32)>,
374    posters: &'a [String],
375    context: &RowContext<'a>,
376) -> Element<'a, Message> {
377    // Being built is being on screen: asking for it here is what keeps it
378    // playing.
379    let playback = context.videos.shown(url);
380    let screen: Element<'a, Message> = Element::new(Screen { size, content: screen(playback, posters, context) });
381    let card = container(widget::Column::new().push(screen).push(bar(url, label.into(), playback, context)))
382        .padding(CARD_BORDER)
383        .width(Length::Fill)
384        .class(card_style());
385    // Not while a menu is open over the list: a click beside the menu is
386    // to put it away, and no more.
387    let area = widget::mouse_area(card);
388    if context.under_a_menu() {
389        area.into()
390    } else {
391        area.on_press(Message::VideoPress(url.to_string())).interaction(mouse::Interaction::Pointer).into()
392    }
393}