Skip to main content

script/dom/file/
file.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::rc::Rc;
6use std::time::SystemTime;
7
8use dom_struct::dom_struct;
9use embedder_traits::SelectedFile;
10use js::context::{JSContext, NoGC};
11use js::rust::HandleObject;
12use script_bindings::domstring::TracedDOMString;
13use script_bindings::reflector::reflect_weak_referenceable_dom_object_with_proto;
14use script_bindings::serializable::Serializable;
15use script_bindings::structuredclone::StructuredData;
16use servo_base::id::{FileId, FileIndex};
17use servo_constellation_traits::{BlobImpl, SerializableFile};
18use time::{Duration, OffsetDateTime};
19
20use crate::dom::bindings::codegen::Bindings::FileBinding;
21use crate::dom::bindings::codegen::Bindings::FileBinding::FileMethods;
22use crate::dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString;
23use crate::dom::bindings::error::{Error, Fallible};
24use crate::dom::bindings::inheritance::Castable;
25use crate::dom::bindings::root::DomRoot;
26use crate::dom::bindings::str::{DOMString, USVString};
27use crate::dom::blob::{Blob, normalize_type_string, process_blob_parts};
28use crate::dom::globalscope::GlobalScope;
29use crate::dom::window::Window;
30
31#[dom_struct]
32pub(crate) struct File {
33    blob: Blob,
34    name: TracedDOMString,
35    modified: SystemTime,
36    // Only set when a directory is selected.
37    // 1. webdriver send keys to <input>.
38    // 2. When dom_testing_html_input_element_select_files_enabled,
39    //    the testing API selectFiles.
40    // 3. with `webkitdirectory` in the file picker.
41    webkit_relative_path: USVString,
42}
43
44impl File {
45    fn new_inherited(
46        blob_impl: &BlobImpl,
47        name: DOMString,
48        modified: Option<SystemTime>,
49        webkit_relative_path: USVString,
50    ) -> File {
51        File {
52            blob: Blob::new_inherited(blob_impl),
53            name: name.traced(),
54            // https://w3c.github.io/FileAPI/#dfn-lastModified
55            modified: modified.unwrap_or_else(SystemTime::now),
56            webkit_relative_path,
57        }
58    }
59
60    pub(crate) fn new(
61        cx: &mut JSContext,
62        global: &GlobalScope,
63        blob_impl: BlobImpl,
64        name: DOMString,
65        modified: Option<SystemTime>,
66    ) -> DomRoot<File> {
67        Self::new_with_proto(
68            cx,
69            global,
70            None,
71            blob_impl,
72            name,
73            modified,
74            USVString::default(),
75        )
76    }
77
78    fn new_with_proto(
79        cx: &mut JSContext,
80        global: &GlobalScope,
81        proto: Option<HandleObject>,
82        blob_impl: BlobImpl,
83        name: DOMString,
84        modified: Option<SystemTime>,
85        webkit_relative_path: USVString,
86    ) -> DomRoot<File> {
87        let file = reflect_weak_referenceable_dom_object_with_proto(
88            cx,
89            Rc::new(File::new_inherited(
90                &blob_impl,
91                name,
92                modified,
93                webkit_relative_path,
94            )),
95            global,
96            proto,
97        );
98        global.track_file(&file, blob_impl);
99        file
100    }
101
102    // Construct from selected file message from file manager thread
103    pub(crate) fn new_from_selected(
104        cx: &mut JSContext,
105        window: &Window,
106        selected: SelectedFile,
107    ) -> DomRoot<File> {
108        let name = DOMString::from(
109            selected
110                .filename
111                .to_str()
112                .expect("File name encoding error"),
113        );
114
115        Self::new_with_proto(
116            cx,
117            window.upcast(),
118            None,
119            BlobImpl::new_from_file(
120                selected.id,
121                selected.filename,
122                selected.size,
123                normalize_type_string(&selected.type_string.to_string()),
124            ),
125            name,
126            Some(selected.modified),
127            USVString::from(selected.relative_path.unwrap_or_default()),
128        )
129    }
130
131    pub(crate) fn file_bytes(&self) -> Result<Vec<u8>, ()> {
132        self.blob.get_bytes()
133    }
134
135    pub(crate) fn name(&self) -> &TracedDOMString {
136        &self.name
137    }
138
139    pub(crate) fn file_type(&self) -> String {
140        self.blob.type_string()
141    }
142
143    pub(crate) fn get_modified(&self) -> SystemTime {
144        self.modified
145    }
146
147    pub(crate) fn serialized_data(&self, no_gc: &NoGC) -> Result<SerializableFile, ()> {
148        let (_, blob_impl) = self.upcast::<Blob>().serialize(no_gc)?;
149        Ok(SerializableFile {
150            blob_impl,
151            name: self.name.to_string(),
152            modified: self.LastModified(),
153            webkit_relative_path: self.webkit_relative_path.to_string(),
154        })
155    }
156}
157
158impl Serializable<crate::DomTypeHolder> for File {
159    type Index = FileIndex;
160    type Data = SerializableFile;
161
162    /// <https://html.spec.whatwg.org/multipage/#serialization-steps>
163    fn serialize(&self, no_gc: &NoGC) -> Result<(FileId, SerializableFile), ()> {
164        Ok((FileId::new(), self.serialized_data(no_gc)?))
165    }
166
167    /// <https://html.spec.whatwg.org/multipage/#deserialization-steps>
168    fn deserialize(
169        cx: &mut JSContext,
170        owner: &GlobalScope,
171        serialized: SerializableFile,
172    ) -> Result<DomRoot<Self>, ()> {
173        let modified = OffsetDateTime::UNIX_EPOCH + Duration::milliseconds(serialized.modified);
174        Ok(File::new_with_proto(
175            cx,
176            owner,
177            None,
178            serialized.blob_impl,
179            serialized.name.into(),
180            Some(modified.into()),
181            USVString::from(serialized.webkit_relative_path),
182        ))
183    }
184
185    fn serialized_storage<'a>(
186        reader: StructuredData<'a, '_>,
187    ) -> &'a mut Option<rustc_hash::FxHashMap<FileId, Self::Data>> {
188        match reader {
189            StructuredData::Reader(r) => &mut r.files,
190            StructuredData::Writer(w) => &mut w.files,
191        }
192    }
193}
194
195impl FileMethods<crate::DomTypeHolder> for File {
196    // https://w3c.github.io/FileAPI/#file-constructor
197    #[expect(non_snake_case)]
198    fn Constructor(
199        cx: &mut JSContext,
200        global: &GlobalScope,
201        proto: Option<HandleObject>,
202        fileBits: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>,
203        filename: DOMString,
204        filePropertyBag: &FileBinding::FilePropertyBag,
205    ) -> Fallible<DomRoot<File>> {
206        let bytes: Vec<u8> =
207            match process_blob_parts(cx.no_gc(), fileBits, filePropertyBag.parent.endings) {
208                Ok(bytes) => bytes,
209                Err(_) => return Err(Error::InvalidCharacter(None)),
210            };
211
212        let blobPropertyBag = &filePropertyBag.parent;
213        let modified = filePropertyBag
214            .lastModified
215            .map(|modified| OffsetDateTime::UNIX_EPOCH + Duration::milliseconds(modified))
216            .map(Into::into);
217
218        let type_string = normalize_type_string(&blobPropertyBag.type_.str());
219        Ok(File::new_with_proto(
220            cx,
221            global,
222            proto,
223            BlobImpl::new_from_bytes(bytes, type_string),
224            filename,
225            modified,
226            USVString::default(),
227        ))
228    }
229
230    /// <https://w3c.github.io/FileAPI/#dfn-name>
231    fn Name(&self) -> DOMString {
232        self.name.clone().root()
233    }
234
235    /// <https://wicg.github.io/entries-api/#dom-file-webkitrelativepath>
236    fn WebkitRelativePath(&self) -> USVString {
237        self.webkit_relative_path.clone()
238    }
239
240    /// <https://w3c.github.io/FileAPI/#dfn-lastModified>
241    fn LastModified(&self) -> i64 {
242        // This is first converted to a `time::OffsetDateTime` because it might be from before the
243        // Unix epoch in which case we will need to return a negative duration to script.
244        (OffsetDateTime::from(self.modified) - OffsetDateTime::UNIX_EPOCH).whole_milliseconds()
245            as i64
246    }
247}