Skip to main content

script/dom/filesystem/
filesystementry.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::cell::Cell;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use script_bindings::cell::DomRefCell;
10use script_bindings::reflector::Reflector;
11
12use crate::dom::bindings::callback::{ExceptionHandling, RootedCallback, TracedCallback};
13use crate::dom::bindings::codegen::Bindings::FileSystemEntryBinding::{
14    ErrorCallback, FileSystemEntryCallback, FileSystemEntryMethods,
15};
16use crate::dom::bindings::refcounted::Trusted;
17use crate::dom::bindings::reflector::DomGlobal;
18use crate::dom::bindings::root::{DomRoot, MutNullableDom};
19use crate::dom::bindings::str::USVString;
20use crate::dom::domexception::{DOMErrorName, DOMException};
21use crate::dom::filesystem::FileSystem;
22use crate::dom::filesystem::path::{evaluate_path, resolve_relative_path};
23use crate::dom::filesystemdirectoryentry::FileSystemDirectoryEntry;
24
25#[dom_struct]
26pub(crate) struct FileSystemEntry {
27    reflector_: Reflector,
28    name: USVString,
29    full_path: USVString,
30    is_file: bool,
31    filesystem: MutNullableDom<FileSystem>,
32    pending_callbacks: DomRefCell<Vec<PendingEntryCallback>>,
33    next_callback: Cell<usize>,
34}
35
36#[derive(JSTraceable, MallocSizeOf)]
37#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
38struct PendingEntryCallback {
39    id: usize,
40    callback: Option<TracedCallback<FileSystemEntryCallback>>,
41    error: Option<TracedCallback<ErrorCallback>>,
42}
43
44impl FileSystemEntry {
45    pub(crate) fn new_inherited(
46        name: USVString,
47        full_path: USVString,
48        is_file: bool,
49    ) -> FileSystemEntry {
50        FileSystemEntry {
51            reflector_: Reflector::new(),
52            name,
53            full_path,
54            is_file,
55            filesystem: MutNullableDom::new(None),
56            pending_callbacks: Default::default(),
57            next_callback: Cell::new(0),
58        }
59    }
60
61    pub(crate) fn set_filesystem(&self, fs: &FileSystem) {
62        self.filesystem.set(Some(fs));
63    }
64
65    pub(crate) fn name(&self) -> &str {
66        &self.name
67    }
68
69    pub(crate) fn full_path(&self) -> &str {
70        &self.full_path
71    }
72
73    pub(crate) fn is_file(&self) -> bool {
74        self.is_file
75    }
76
77    pub(crate) fn filesystem(&self) -> DomRoot<FileSystem> {
78        self.filesystem
79            .get()
80            .expect("FileSystemEntry must be associated with a FileSystem")
81    }
82
83    /// Returns this entry's root directory.
84    pub(crate) fn root(&self) -> DomRoot<FileSystemDirectoryEntry> {
85        self.filesystem().root()
86    }
87
88    /// Queue `success_callback` and `error_callback` for the task that will
89    /// invoke one of them, and returns the id used to look them up.
90    pub(crate) fn queue_entry_callback(
91        &self,
92        success_callback: Option<RootedCallback<FileSystemEntryCallback>>,
93        error_callback: Option<RootedCallback<ErrorCallback>>,
94    ) -> usize {
95        let id = self.next_callback.get();
96        self.pending_callbacks
97            .borrow_mut()
98            .push(PendingEntryCallback {
99                id,
100                callback: success_callback.map(|callback| callback.to_traced()),
101                error: error_callback.map(|callback| callback.to_traced()),
102            });
103        self.next_callback.set(id + 1);
104        id
105    }
106
107    /// Invoke the callbacks queued under `id` with `result`, unless the task was cancelled.
108    pub(crate) fn dispatch_entry_callback(
109        &self,
110        cx: &mut JSContext,
111        id: usize,
112        result: Result<DomRoot<FileSystemEntry>, DOMErrorName>,
113    ) {
114        let Some(index) = self
115            .pending_callbacks
116            .borrow()
117            .iter()
118            .position(|val| val.id == id)
119        else {
120            return;
121        };
122
123        let (success_callback, error_callback) = {
124            let pending = self.pending_callbacks.borrow();
125            let pending = pending.get(index).expect("callback must still be queued");
126            (
127                pending.callback.as_ref().map(|callback| callback.root(cx)),
128                pending.error.as_ref().map(|callback| callback.root(cx)),
129            )
130        };
131        self.pending_callbacks
132            .safe_borrow_mut(cx)
133            .swap_remove(index);
134
135        match result {
136            Ok(entry) => {
137                if let Some(callback) = success_callback {
138                    let _ = callback.Call__(cx, &entry, ExceptionHandling::Report);
139                }
140            },
141            Err(name) => {
142                if let Some(error_callback) = error_callback {
143                    let error = DOMException::new(cx, &self.global(), name);
144                    let _ = error_callback.Call__(cx, &error, ExceptionHandling::Report);
145                }
146            },
147        }
148    }
149}
150
151impl FileSystemEntryMethods<crate::DomTypeHolder> for FileSystemEntry {
152    /// <https://wicg.github.io/entries-api/#dom-filesystementry-isfile>
153    fn IsFile(&self) -> bool {
154        self.is_file
155    }
156
157    /// <https://wicg.github.io/entries-api/#dom-filesystementry-isdirectory>
158    fn IsDirectory(&self) -> bool {
159        !self.is_file
160    }
161
162    /// <https://wicg.github.io/entries-api/#dom-filesystementry-name>
163    fn Name(&self) -> USVString {
164        self.name.clone()
165    }
166
167    /// <https://wicg.github.io/entries-api/#dom-filesystementry-fullpath>
168    fn FullPath(&self) -> USVString {
169        self.full_path.clone()
170    }
171
172    /// <https://wicg.github.io/entries-api/#dom-filesystementry-filesystem>
173    fn Filesystem(&self) -> DomRoot<FileSystem> {
174        self.filesystem()
175    }
176
177    /// <https://wicg.github.io/entries-api/#dom-filesystementry-getparent>
178    fn GetParent(
179        &self,
180        success_callback: Option<RootedCallback<FileSystemEntryCallback>>,
181        error_callback: Option<RootedCallback<ErrorCallback>>,
182    ) {
183        // Step 1.1. Let path be the result of resolving a relative path with
184        // this's full path and '..'.
185        let path = resolve_relative_path(self.full_path(), "..");
186
187        // Step 1.2. Let item be the result of evaluating a path with this's
188        // root and path.
189        let item = evaluate_path(&self.root(), &path)
190            .and_then(DomRoot::downcast::<FileSystemDirectoryEntry>)
191            .map(|item| Trusted::new(&*item));
192
193        let id = self.queue_entry_callback(success_callback, error_callback);
194
195        let this = Trusted::new(self);
196        self.global()
197            .task_manager()
198            .dom_manipulation_task_source()
199            .queue(task!(invoke_get_parent: move |cx| {
200                let this = this.root();
201                let result = match item {
202                    // Step 1.3. If item is failure, queue a task to invoke
203                    // errorCallback (if given) with « a newly created
204                    // "NotFoundError" DOMException » and "report", and abort
205                    // these steps.
206                    None => Err(DOMErrorName::NotFoundError),
207                    // Step 1.4. Let entry be a new directory entry with item's
208                    // name as name and path as full path.
209                    //
210                    // Step 1.5. Queue a task to invoke successCallback with « a
211                    // new FileSystemDirectoryEntry object associated with entry »
212                    // and "report".
213                    //
214                    // TODO: Return a new directory entry as the spec requires.
215                    // We can fix this once directory members are resolved by path
216                    // with embedder support.
217                    Some(item) => Ok(DomRoot::upcast::<FileSystemEntry>(item.root())),
218                };
219                this.dispatch_entry_callback(cx, id, result);
220            }));
221    }
222}