script/dom/
filelist.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 std::slice::Iter;
6
7use dom_struct::dom_struct;
8
9use super::bindings::root::{LayoutDom, ToLayout};
10use crate::dom::bindings::codegen::Bindings::FileListBinding::FileListMethods;
11use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
12use crate::dom::bindings::root::{Dom, DomRoot};
13use crate::dom::file::File;
14use crate::dom::window::Window;
15use crate::script_runtime::CanGc;
16
17// https://w3c.github.io/FileAPI/#dfn-filelist
18#[dom_struct]
19pub(crate) struct FileList {
20    reflector_: Reflector,
21    list: Vec<Dom<File>>,
22}
23
24impl FileList {
25    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
26    fn new_inherited(files: Vec<Dom<File>>) -> FileList {
27        FileList {
28            reflector_: Reflector::new(),
29            list: files,
30        }
31    }
32
33    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
34    pub(crate) fn new(
35        window: &Window,
36        files: Vec<DomRoot<File>>,
37        can_gc: CanGc,
38    ) -> DomRoot<FileList> {
39        reflect_dom_object(
40            Box::new(FileList::new_inherited(
41                files.iter().map(|r| Dom::from_ref(&**r)).collect(),
42            )),
43            window,
44            can_gc,
45        )
46    }
47
48    pub(crate) fn iter_files(&self) -> Iter<'_, Dom<File>> {
49        self.list.iter()
50    }
51}
52
53impl FileListMethods<crate::DomTypeHolder> for FileList {
54    // https://w3c.github.io/FileAPI/#dfn-length
55    fn Length(&self) -> u32 {
56        self.list.len() as u32
57    }
58
59    // https://w3c.github.io/FileAPI/#dfn-item
60    fn Item(&self, index: u32) -> Option<DomRoot<File>> {
61        if (index as usize) < self.list.len() {
62            Some(DomRoot::from_ref(&*(self.list[index as usize])))
63        } else {
64            None
65        }
66    }
67
68    // check-tidy: no specs after this line
69    fn IndexedGetter(&self, index: u32) -> Option<DomRoot<File>> {
70        self.Item(index)
71    }
72}
73
74pub(crate) trait LayoutFileListHelpers<'dom> {
75    fn file_for_layout(&self, index: u32) -> Option<&File>;
76    fn len(&self) -> usize;
77}
78
79#[allow(unsafe_code)]
80impl<'dom> LayoutFileListHelpers<'dom> for LayoutDom<'dom, FileList> {
81    fn len(&self) -> usize {
82        self.unsafe_get().list.len()
83    }
84    fn file_for_layout(&self, index: u32) -> Option<&File> {
85        let list = &self.unsafe_get().list;
86        if (index as usize) < list.len() {
87            Some(unsafe { list[index as usize].to_layout().unsafe_get() })
88        } else {
89            None
90        }
91    }
92}