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