Skip to main content

script/dom/webvtt/
texttracklist.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::context::{JSContext, NoGC};
7use script_bindings::cell::DomRefCell;
8use script_bindings::reflector::reflect_dom_object_with_cx;
9
10use crate::dom::bindings::codegen::Bindings::TextTrackListBinding::TextTrackListMethods;
11use crate::dom::bindings::codegen::UnionTypes::VideoTrackOrAudioTrackOrTextTrack;
12use crate::dom::bindings::inheritance::Castable;
13use crate::dom::bindings::refcounted::Trusted;
14use crate::dom::bindings::reflector::DomGlobal;
15use crate::dom::bindings::root::{Dom, DomRoot, UnrootedDom};
16use crate::dom::bindings::str::DOMString;
17use crate::dom::event::Event;
18use crate::dom::eventtarget::EventTarget;
19use crate::dom::html::htmlmediaelement::HTMLMediaElement;
20use crate::dom::html::htmltrackelement::HTMLTrackElement;
21use crate::dom::node::node::Node;
22use crate::dom::texttrack::TextTrack;
23use crate::dom::texttrackcue::TextTrackCue;
24use crate::dom::trackevent::TrackEvent;
25use crate::dom::window::Window;
26
27#[dom_struct]
28pub(crate) struct TextTrackList {
29    eventtarget: EventTarget,
30    /// <https://html.spec.whatwg.org/multipage/#list-of-text-tracks>
31    media_element: Dom<HTMLMediaElement>,
32    dom_tracks: DomRefCell<Vec<Dom<TextTrack>>>,
33}
34
35impl TextTrackList {
36    pub(crate) fn new_inherited(
37        media_element: &HTMLMediaElement,
38        tracks: &[&TextTrack],
39    ) -> TextTrackList {
40        TextTrackList {
41            eventtarget: EventTarget::new_inherited(),
42            media_element: Dom::from_ref(media_element),
43            dom_tracks: DomRefCell::new(tracks.iter().map(|g| Dom::from_ref(&**g)).collect()),
44        }
45    }
46
47    pub(crate) fn new(
48        cx: &mut JSContext,
49        media_element: &HTMLMediaElement,
50        window: &Window,
51        tracks: &[&TextTrack],
52    ) -> DomRoot<TextTrackList> {
53        reflect_dom_object_with_cx(
54            Box::new(TextTrackList::new_inherited(media_element, tracks)),
55            window,
56            cx,
57        )
58    }
59
60    pub(crate) fn notify_media_element_for_added_cue(
61        &self,
62        cx: &mut JSContext,
63        cue: &TextTrackCue,
64    ) {
65        self.media_element.add_newly_added_cue(cx, cue);
66    }
67
68    pub(crate) fn add(&self, cx: &mut JSContext, track: &TextTrack) {
69        // We should only store the tracks created by `addTextTrack`
70        // since the iterator already traverses children of a media
71        // element for <track> elements. Otherwise, we would be double
72        // counting.
73        if track.associated_track().is_none() {
74            self.dom_tracks.borrow_mut().push(Dom::from_ref(track));
75        }
76
77        track.add_track_list(self);
78        self.media_element
79            .was_added_to_list_of_text_tracks(cx, track);
80
81        let this = Trusted::new(self);
82        let track = Trusted::new(track);
83        self.global()
84            .task_manager()
85            .media_element_task_source()
86            .queue(task!(track_event_queue: move |cx| {
87                let this = this.root();
88                let track = track.root();
89
90                let event = TrackEvent::new(
91                    cx,
92                    this.global().as_window(),
93                    atom!("addtrack"),
94                    false,
95                    false,
96                    &Some(VideoTrackOrAudioTrackOrTextTrack::TextTrack(
97                        DomRoot::from_ref(&track)
98                    )),
99                );
100
101                event.upcast::<Event>().fire(cx, this.upcast::<EventTarget>());
102            }));
103    }
104
105    pub(crate) fn remove(&self, track: &TextTrack) {
106        if let Some(idx) = self
107            .dom_tracks
108            .borrow()
109            .iter()
110            .position(|dom_track| &**dom_track == track)
111        {
112            self.dom_tracks.borrow_mut().remove(idx);
113        };
114        track.remove_track_list();
115
116        let this = Trusted::new(self);
117        let track = Trusted::new(track);
118        self.global()
119            .task_manager()
120            .media_element_task_source()
121            .queue(task!(track_event_queue: move |cx| {
122                let this = this.root();
123                let track = track.root();
124
125                let event = TrackEvent::new(
126                    cx,
127                    this.global().as_window(),
128                    atom!("removetrack"),
129                    false,
130                    false,
131                    &Some(VideoTrackOrAudioTrackOrTextTrack::TextTrack(
132                        DomRoot::from_ref(&track)
133                    )),
134                );
135
136                event.upcast::<Event>().fire(cx, this.upcast::<EventTarget>());
137            }));
138    }
139
140    pub(crate) fn iter<'a>(&'a self, no_gc: &'a NoGC) -> TextTrackListIterator<'a> {
141        TextTrackListIterator {
142            no_gc,
143            track_elements: Box::new(
144                self.media_element
145                    .upcast::<Node>()
146                    .children_unrooted(no_gc)
147                    .filter_map(UnrootedDom::downcast::<HTMLTrackElement>),
148            ),
149            dom_tracks: Box::new(
150                self.dom_tracks
151                    .borrow()
152                    .clone()
153                    .into_iter()
154                    .map(|track| track.as_unrooted(no_gc)),
155            ),
156        }
157    }
158}
159
160impl TextTrackListMethods<crate::DomTypeHolder> for TextTrackList {
161    /// <https://html.spec.whatwg.org/multipage/#dom-texttracklist-length>
162    fn Length(&self, no_gc: &NoGC) -> u32 {
163        // > The length attribute of a TextTrackList object must return
164        // > the number of text tracks in the list represented by the TextTrackList object.
165        self.iter(no_gc).count() as u32
166    }
167
168    /// <https://html.spec.whatwg.org/multipage/#dom-texttracklist-item>
169    fn IndexedGetter(&self, no_gc: &NoGC, idx: u32) -> Option<DomRoot<TextTrack>> {
170        // > To determine the value of an indexed property of a TextTrackList object
171        // > for a given index index, the user agent must return the indexth
172        // > text track in the list represented by the TextTrackList object.
173        self.iter(no_gc)
174            .nth(idx as usize)
175            .map(|track| track.as_rooted())
176    }
177
178    /// <https://html.spec.whatwg.org/multipage/#dom-texttracklist-gettrackbyid>
179    fn GetTrackById(&self, no_gc: &NoGC, id: DOMString) -> Option<DomRoot<TextTrack>> {
180        // > The getTrackById(id) method must return the first TextTrack in
181        // > the TextTrackList object whose id IDL attribute would return
182        // > a value equal to the value of the id argument.
183        // > When no tracks match the given argument, the method must return null.
184        let id_str = String::from(id);
185        self.iter(no_gc)
186            .find(|track| *track.id() == id_str)
187            .map(|track| track.as_rooted())
188    }
189
190    // https://html.spec.whatwg.org/multipage/#handler-texttracklist-onchange
191    event_handler!(change, GetOnchange, SetOnchange);
192
193    // https://html.spec.whatwg.org/multipage/#handler-texttracklist-onaddtrack
194    event_handler!(addtrack, GetOnaddtrack, SetOnaddtrack);
195
196    // https://html.spec.whatwg.org/multipage/#handler-texttracklist-onremovetrack
197    event_handler!(removetrack, GetOnremovetrack, SetOnremovetrack);
198}
199
200/// <https://html.spec.whatwg.org/multipage/#list-of-text-tracks>
201pub(crate) struct TextTrackListIterator<'a> {
202    no_gc: &'a NoGC,
203    track_elements: Box<dyn Iterator<Item = UnrootedDom<'a, HTMLTrackElement>> + 'a>,
204    dom_tracks: Box<dyn Iterator<Item = UnrootedDom<'a, TextTrack>> + 'a>,
205}
206
207impl<'a> Iterator for TextTrackListIterator<'a> {
208    type Item = UnrootedDom<'a, TextTrack>;
209
210    fn next(&mut self) -> Option<Self::Item> {
211        // > The text tracks are sorted as follows:
212        // Step 1. The text tracks corresponding to track element children of the media element, in tree order.
213        if let Some(track_element) = self.track_elements.next() {
214            return Some(track_element.track(self.no_gc));
215        }
216        // Step 2. Any text tracks added using the addTextTrack() method,
217        // in the order they were added, oldest first.
218        if let Some(dom_track) = self.dom_tracks.next() {
219            return Some(dom_track);
220        }
221        // Step 3. Any media-resource-specific text tracks
222        // (text tracks corresponding to data in the media resource),
223        // in the order defined by the media resource's format specification.
224        // TODO
225        None
226    }
227}