Skip to main content

script/dom/filesystem/
filesystemdirectoryentry.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;
7use script_bindings::cell::DomRefCell;
8use script_bindings::reflector::reflect_dom_object;
9
10use crate::dom::bindings::callback::RootedCallback;
11use crate::dom::bindings::codegen::Bindings::FileSystemDirectoryEntryBinding::{
12    FileSystemDirectoryEntryMethods, FileSystemFlags,
13};
14use crate::dom::bindings::codegen::Bindings::FileSystemEntryBinding::{
15    ErrorCallback, FileSystemEntryCallback,
16};
17use crate::dom::bindings::refcounted::Trusted;
18use crate::dom::bindings::reflector::DomGlobal;
19use crate::dom::bindings::root::{Dom, DomRoot};
20use crate::dom::bindings::str::USVString;
21use crate::dom::domexception::DOMErrorName;
22use crate::dom::filesystem::FileSystem;
23use crate::dom::filesystem::path::{evaluate_path, is_valid_path, resolve_relative_path};
24use crate::dom::filesystemdirectoryreader::FileSystemDirectoryReader;
25use crate::dom::filesystementry::FileSystemEntry;
26use crate::dom::filesystemfileentry::FileSystemFileEntry;
27use crate::dom::globalscope::GlobalScope;
28
29#[dom_struct]
30pub(crate) struct FileSystemDirectoryEntry {
31    filesystementry: FileSystemEntry,
32    children: DomRefCell<Vec<Dom<FileSystemEntry>>>,
33}
34
35impl FileSystemDirectoryEntry {
36    fn new_inherited(name: USVString, full_path: USVString) -> FileSystemDirectoryEntry {
37        FileSystemDirectoryEntry {
38            filesystementry: FileSystemEntry::new_inherited(name, full_path, false),
39            children: DomRefCell::new(Vec::new()),
40        }
41    }
42
43    pub(crate) fn new(
44        cx: &mut JSContext,
45        global: &GlobalScope,
46        name: USVString,
47        full_path: USVString,
48    ) -> DomRoot<FileSystemDirectoryEntry> {
49        reflect_dom_object(
50            cx,
51            Box::new(FileSystemDirectoryEntry::new_inherited(name, full_path)),
52            global,
53        )
54    }
55
56    pub(crate) fn set_filesystem(&self, fs: &FileSystem) {
57        self.filesystementry.set_filesystem(fs);
58    }
59
60    pub(crate) fn push_child(&self, child: &FileSystemEntry) {
61        self.children.borrow_mut().push(Dom::from_ref(child));
62    }
63
64    /// Returns the member of this directory named `name`, if any.
65    pub(crate) fn child(&self, name: &str) -> Option<DomRoot<FileSystemEntry>> {
66        self.children
67            .borrow()
68            .iter()
69            .find(|child| child.name() == name)
70            .map(|child| DomRoot::from_ref(&**child))
71    }
72
73    /// Returns up to `max` children starting at index `start`.
74    pub(crate) fn children_batch(&self, start: usize, max: usize) -> Vec<DomRoot<FileSystemEntry>> {
75        self.children
76            .borrow()
77            .iter()
78            .skip(start)
79            .take(max)
80            .map(|child| DomRoot::from_ref(&**child))
81            .collect()
82    }
83
84    /// Shared helper for getFile() and getDirectory().
85    /// Only 1.8 and 1.9 is different, based on whether this is file or dir.
86    fn get_entry(
87        &self,
88        path: Option<Option<USVString>>,
89        options: &FileSystemFlags,
90        is_file: bool,
91        success_callback: Option<RootedCallback<FileSystemEntryCallback>>,
92        error_callback: Option<RootedCallback<ErrorCallback>>,
93    ) {
94        // Step 1.1. If path is undefined or null let path be the empty string.
95        let path = path.flatten().unwrap_or_default();
96
97        // Step 1.2. If path is not a valid path, queue a task to invoke
98        // errorCallback (if given) with « a newly created "TypeMismatchError"
99        // DOMException » and "report", and abort these steps.
100        //
101        // Step 1.3. If options's create member is true, queue a task to invoke
102        // errorCallback (if given) with « a newly created "SecurityError"
103        // DOMException » and "report", and abort these steps.
104        //
105        // Step 1.4. Let path be the result of resolving a relative path with
106        // this's full path and path.
107        //
108        // Step 1.5. Let item be the result of evaluating a path with this's
109        // root and path.
110        //
111        // Step 1.6. If item is failure, queue a task to invoke errorCallback
112        // (if given) with « a newly created "NotFoundError" DOMException » and
113        // "report", and abort these steps.
114        //
115        // Step 1.7. If item is not a file (getFile) or directory
116        // (getDirectory), queue a task to invoke errorCallback (if given) with
117        // « a newly created "TypeMismatchError" DOMException » and "report",
118        // and abort these steps.
119        let result = if !is_valid_path(&path) {
120            Err(DOMErrorName::TypeMismatchError)
121        } else if options.create {
122            Err(DOMErrorName::SecurityError)
123        } else {
124            let path = USVString::from(resolve_relative_path(
125                self.filesystementry.full_path(),
126                &path,
127            ));
128            evaluate_path(&self.filesystementry.root(), &path)
129                .ok_or(DOMErrorName::NotFoundError)
130                .and_then(|item| {
131                    if item.is_file() == is_file {
132                        // Step 1.8. Let entry be a new file or directory entry
133                        // with item's name as name and path as full path.
134                        // We pin down the value synchronously now to pass
135                        // to the queued task.
136                        Ok((item.name().to_owned(), path, Trusted::new(&*item)))
137                    } else {
138                        Err(DOMErrorName::TypeMismatchError)
139                    }
140                })
141        };
142
143        let id = self
144            .filesystementry
145            .queue_entry_callback(success_callback, error_callback);
146        let this = Trusted::new(&self.filesystementry);
147        self.global()
148            .task_manager()
149            .dom_manipulation_task_source()
150            .queue(task!(invoke_get_entry: move |cx| {
151                let this = this.root();
152                let result = match result {
153                    Ok((name, path, item)) => {
154                        let item = item.root();
155                        if is_file {
156                            // Step 1.9. Queue a task to invoke successCallback
157                            // with « a new FileSystemFileEntry object associated
158                            // with entry » and "report".
159                            let file = DomRoot::downcast::<FileSystemFileEntry>(item)
160                                .expect("getFile() checked that item is a file")
161                                .file();
162                            let entry = FileSystemFileEntry::new(
163                                cx,
164                                &this.global(),
165                                USVString::from(name),
166                                path,
167                                &file,
168                            );
169                            entry.set_filesystem(&this.filesystem());
170                            Ok(DomRoot::upcast::<FileSystemEntry>(entry))
171                        } else {
172                            // Step 1.9. Queue a task to invoke successCallback
173                            // with « a new FileSystemDirectoryEntry associated
174                            // with entry » and "report".
175                            //
176                            // TODO: Return a new directory entry as the spec
177                            // requires. Need embedder directory support.
178                            Ok(item)
179                        }
180                    },
181                    Err(name) => Err(name),
182                };
183                this.dispatch_entry_callback(cx, id, result);
184            }));
185    }
186}
187
188impl FileSystemDirectoryEntryMethods<crate::DomTypeHolder> for FileSystemDirectoryEntry {
189    /// <https://wicg.github.io/entries-api/#dom-filesystemdirectoryentry-createreader>
190    fn CreateReader(&self, cx: &mut JSContext) -> DomRoot<FileSystemDirectoryReader> {
191        FileSystemDirectoryReader::new(cx, &self.global(), self)
192    }
193
194    /// <https://wicg.github.io/entries-api/#dom-filesystemdirectoryentry-getfile>
195    fn GetFile(
196        &self,
197        path: Option<Option<USVString>>,
198        options: &FileSystemFlags,
199        success_callback: Option<RootedCallback<FileSystemEntryCallback>>,
200        error_callback: Option<RootedCallback<ErrorCallback>>,
201    ) {
202        self.get_entry(
203            path,
204            options,
205            true, /*is_file*/
206            success_callback,
207            error_callback,
208        );
209    }
210
211    /// <https://wicg.github.io/entries-api/#dom-filesystemdirectoryentry-getdirectory>
212    fn GetDirectory(
213        &self,
214        path: Option<Option<USVString>>,
215        options: &FileSystemFlags,
216        success_callback: Option<RootedCallback<FileSystemEntryCallback>>,
217        error_callback: Option<RootedCallback<ErrorCallback>>,
218    ) {
219        self.get_entry(
220            path,
221            options,
222            false, /*is_file*/
223            success_callback,
224            error_callback,
225        );
226    }
227}