script/
drag_data_store.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::sync::Arc;
6
7use constellation_traits::BlobImpl;
8use indexmap::IndexMap;
9use pixels::RasterImage;
10
11use crate::dom::bindings::error::{Error, Fallible};
12use crate::dom::bindings::root::DomRoot;
13use crate::dom::bindings::str::DOMString;
14use crate::dom::file::File;
15use crate::dom::globalscope::GlobalScope;
16use crate::script_runtime::CanGc;
17
18/// <https://html.spec.whatwg.org/multipage/#the-drag-data-item-kind>
19#[derive(MallocSizeOf)]
20pub(crate) enum Kind {
21    Text {
22        data: DOMString,
23        type_: DOMString,
24    },
25    File {
26        bytes: Vec<u8>,
27        name: DOMString,
28        type_: String,
29    },
30}
31
32impl Kind {
33    pub(crate) fn type_(&self) -> DOMString {
34        match self {
35            Kind::Text { type_, .. } => type_.clone(),
36            Kind::File { type_, .. } => DOMString::from(type_.clone()),
37        }
38    }
39
40    pub(crate) fn as_string(&self) -> Option<String> {
41        match self {
42            Kind::Text { data, .. } => Some(data.to_string()),
43            Kind::File { .. } => None,
44        }
45    }
46
47    // TODO for now we create a new BlobImpl
48    // since File constructor requires moving it.
49    pub(crate) fn as_file(&self, global: &GlobalScope, can_gc: CanGc) -> Option<DomRoot<File>> {
50        match self {
51            Kind::Text { .. } => None,
52            Kind::File { bytes, name, type_ } => Some(File::new(
53                global,
54                BlobImpl::new_from_bytes(bytes.clone(), type_.clone()),
55                name.clone(),
56                None,
57                can_gc,
58            )),
59        }
60    }
61
62    fn text_type_matches(&self, text_type: &DOMString) -> bool {
63        matches!(self, Kind::Text { type_, .. } if type_.eq(text_type))
64    }
65
66    fn is_file(&self) -> bool {
67        matches!(self, Kind::File { .. })
68    }
69}
70
71/// <https://html.spec.whatwg.org/multipage/#drag-data-store-bitmap>
72#[derive(MallocSizeOf)]
73struct Bitmap {
74    #[ignore_malloc_size_of = "RasterImage"]
75    image: Option<Arc<RasterImage>>,
76    x: i32,
77    y: i32,
78}
79
80/// Control the behaviour of the drag data store
81#[derive(Clone, Copy, Eq, MallocSizeOf, PartialEq)]
82pub(crate) enum Mode {
83    /// <https://html.spec.whatwg.org/multipage/#concept-dnd-rw>
84    ReadWrite,
85    /// <https://html.spec.whatwg.org/multipage/#concept-dnd-ro>
86    ReadOnly,
87    /// <https://html.spec.whatwg.org/multipage/#concept-dnd-p>
88    Protected,
89}
90
91#[derive(MallocSizeOf)]
92pub(crate) struct DragDataStore {
93    /// <https://html.spec.whatwg.org/multipage/#drag-data-store-item-list>
94    item_list: IndexMap<u16, Kind>,
95    next_item_id: u16,
96    /// <https://html.spec.whatwg.org/multipage/#drag-data-store-default-feedback>
97    default_feedback: Option<String>,
98    bitmap: Option<Bitmap>,
99    mode: Mode,
100    /// <https://html.spec.whatwg.org/multipage/#drag-data-store-allowed-effects-state>
101    allowed_effects_state: String,
102    pub clear_was_called: bool,
103}
104
105impl DragDataStore {
106    /// <https://html.spec.whatwg.org/multipage/#create-a-drag-data-store>
107    // We don't really need it since it's only instantiated by DataTransfer.
108    #[allow(clippy::new_without_default)]
109    pub(crate) fn new() -> DragDataStore {
110        DragDataStore {
111            item_list: IndexMap::new(),
112            next_item_id: 0,
113            default_feedback: None,
114            bitmap: None,
115            mode: Mode::Protected,
116            allowed_effects_state: String::from("uninitialized"),
117            clear_was_called: false,
118        }
119    }
120
121    /// Get the drag data store mode
122    pub(crate) fn mode(&self) -> Mode {
123        self.mode
124    }
125
126    /// Set the drag data store mode
127    pub(crate) fn set_mode(&mut self, mode: Mode) {
128        self.mode = mode;
129    }
130
131    pub(crate) fn set_bitmap(&mut self, image: Option<Arc<RasterImage>>, x: i32, y: i32) {
132        self.bitmap = Some(Bitmap { image, x, y });
133    }
134
135    /// <https://html.spec.whatwg.org/multipage/#concept-datatransfer-types>
136    pub(crate) fn types(&self) -> Vec<DOMString> {
137        let mut types = Vec::new();
138
139        let has_files = self.item_list.values().fold(false, |has_files, item| {
140            // Step 2.1 For each item in the item list whose kind is text,
141            // add an entry to L consisting of the item's type string.
142            match item {
143                Kind::Text { type_, .. } => types.push(type_.clone()),
144                Kind::File { .. } => return true,
145            }
146
147            has_files
148        });
149
150        // Step 2.2 If there are any items in the item list whose kind is File,
151        // add an entry to L consisting of the string "Files".
152        if has_files {
153            types.push(DOMString::from("Files"));
154        }
155        types
156    }
157
158    pub(crate) fn find_matching_text(&self, type_: &DOMString) -> Option<DOMString> {
159        self.item_list
160            .values()
161            .find(|item| item.text_type_matches(type_))
162            .and_then(|item| item.as_string())
163            .map(DOMString::from)
164    }
165
166    pub(crate) fn add(&mut self, kind: Kind) -> Fallible<u16> {
167        if let Kind::Text { ref type_, .. } = kind {
168            // Step 2.1 If there is already an item in the item list whose kind is text
169            // and whose type string is equal to the method's second argument, throw "NotSupportedError".
170            if self
171                .item_list
172                .values()
173                .any(|item| item.text_type_matches(type_))
174            {
175                return Err(Error::NotSupported);
176            }
177        }
178
179        let item_id = self.next_item_id;
180
181        // Step 2.2
182        self.item_list.insert(item_id, kind);
183
184        self.next_item_id += 1;
185        Ok(item_id)
186    }
187
188    pub(crate) fn set_data(&mut self, format: DOMString, data: DOMString) {
189        // Step 3-4
190        let type_ = normalize_mime(format);
191
192        // Step 5 Remove the item in the drag data store item list whose kind is text
193        // and whose type string is equal to format, if there is one.
194        self.item_list
195            .retain(|_, item| !item.text_type_matches(&type_));
196
197        // Step 6 Add an item whose kind is text, whose type is format, and whose data is the method's second argument.
198        self.item_list
199            .insert(self.next_item_id, Kind::Text { data, type_ });
200        self.next_item_id += 1;
201    }
202
203    pub(crate) fn clear_data(&mut self, format: Option<DOMString>) -> bool {
204        let mut was_modified = false;
205
206        if let Some(format) = format {
207            // Step 4-5
208            let type_ = normalize_mime(format);
209
210            // Step 6 Remove the item in the item list whose kind is text and whose type is format.
211            self.item_list.retain(|_, item| {
212                let matches = item.text_type_matches(&type_);
213
214                if matches {
215                    was_modified = true;
216                }
217                !matches
218            });
219        } else {
220            // Step 3 Remove each item in the item list whose kind is text.
221            self.item_list.retain(|_, item| {
222                let matches = item.is_file();
223
224                if !matches {
225                    was_modified = true;
226                }
227                matches
228            });
229        }
230
231        was_modified
232    }
233
234    pub(crate) fn files(
235        &self,
236        global: &GlobalScope,
237        can_gc: CanGc,
238        file_list: &mut Vec<DomRoot<File>>,
239    ) {
240        // Step 3 If the data store is in the protected mode return the empty list.
241        if self.mode == Mode::Protected {
242            return;
243        }
244
245        // Step 4 For each item in the drag data store item list whose kind is File, add the item's data to the list L.
246        self.item_list
247            .values()
248            .filter_map(|item| item.as_file(global, can_gc))
249            .for_each(|file| file_list.push(file));
250    }
251
252    pub(crate) fn list_len(&self) -> usize {
253        self.item_list.len()
254    }
255
256    pub(crate) fn iter_item_list(&self) -> indexmap::map::Values<'_, u16, Kind> {
257        self.item_list.values()
258    }
259
260    pub(crate) fn get_by_index(&self, index: usize) -> Option<(&u16, &Kind)> {
261        self.item_list.get_index(index)
262    }
263
264    pub(crate) fn get_by_id(&self, id: &u16) -> Option<&Kind> {
265        self.item_list.get(id)
266    }
267
268    pub(crate) fn remove(&mut self, index: usize) {
269        self.item_list.shift_remove_index(index);
270    }
271
272    pub(crate) fn clear_list(&mut self) {
273        self.item_list.clear();
274        self.clear_was_called = true;
275    }
276}
277
278fn normalize_mime(mut format: DOMString) -> DOMString {
279    // Convert format to ASCII lowercase.
280    format.make_ascii_lowercase();
281
282    match &*format.str() {
283        // If format equals "text", change it to "text/plain".
284        "text" => DOMString::from("text/plain"),
285        // If format equals "url", change it to "text/uri-list".
286        "url" => DOMString::from("text/uri-list"),
287        s => DOMString::from(s),
288    }
289}