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    pub(crate) fn new() -> DragDataStore {
109        DragDataStore {
110            item_list: IndexMap::new(),
111            next_item_id: 0,
112            default_feedback: None,
113            bitmap: None,
114            mode: Mode::Protected,
115            allowed_effects_state: String::from("uninitialized"),
116            clear_was_called: false,
117        }
118    }
119
120    /// Get the drag data store mode
121    pub(crate) fn mode(&self) -> Mode {
122        self.mode
123    }
124
125    /// Set the drag data store mode
126    pub(crate) fn set_mode(&mut self, mode: Mode) {
127        self.mode = mode;
128    }
129
130    pub(crate) fn set_bitmap(&mut self, image: Option<Arc<RasterImage>>, x: i32, y: i32) {
131        self.bitmap = Some(Bitmap { image, x, y });
132    }
133
134    /// <https://html.spec.whatwg.org/multipage/#concept-datatransfer-types>
135    pub(crate) fn types(&self) -> Vec<DOMString> {
136        let mut types = Vec::new();
137
138        let has_files = self.item_list.values().fold(false, |has_files, item| {
139            // Step 2.1 For each item in the item list whose kind is text,
140            // add an entry to L consisting of the item's type string.
141            match item {
142                Kind::Text { type_, .. } => types.push(type_.clone()),
143                Kind::File { .. } => return true,
144            }
145
146            has_files
147        });
148
149        // Step 2.2 If there are any items in the item list whose kind is File,
150        // add an entry to L consisting of the string "Files".
151        if has_files {
152            types.push(DOMString::from("Files"));
153        }
154        types
155    }
156
157    pub(crate) fn find_matching_text(&self, type_: &DOMString) -> Option<DOMString> {
158        self.item_list
159            .values()
160            .find(|item| item.text_type_matches(type_))
161            .and_then(|item| item.as_string())
162            .map(DOMString::from)
163    }
164
165    pub(crate) fn add(&mut self, kind: Kind) -> Fallible<u16> {
166        if let Kind::Text { ref type_, .. } = kind {
167            // Step 2.1 If there is already an item in the item list whose kind is text
168            // and whose type string is equal to the method's second argument, throw "NotSupportedError".
169            if self
170                .item_list
171                .values()
172                .any(|item| item.text_type_matches(type_))
173            {
174                return Err(Error::NotSupported(None));
175            }
176        }
177
178        let item_id = self.next_item_id;
179
180        // Step 2.2
181        self.item_list.insert(item_id, kind);
182
183        self.next_item_id += 1;
184        Ok(item_id)
185    }
186
187    pub(crate) fn set_data(&mut self, format: DOMString, data: DOMString) {
188        // Step 3-4
189        let type_ = normalize_mime(format);
190
191        // Step 5 Remove the item in the drag data store item list whose kind is text
192        // and whose type string is equal to format, if there is one.
193        self.item_list
194            .retain(|_, item| !item.text_type_matches(&type_));
195
196        // Step 6 Add an item whose kind is text, whose type is format, and whose data is the method's second argument.
197        self.item_list
198            .insert(self.next_item_id, Kind::Text { data, type_ });
199        self.next_item_id += 1;
200    }
201
202    pub(crate) fn clear_data(&mut self, format: Option<DOMString>) -> bool {
203        let mut was_modified = false;
204
205        if let Some(format) = format {
206            // Step 4-5
207            let type_ = normalize_mime(format);
208
209            // Step 6 Remove the item in the item list whose kind is text and whose type is format.
210            self.item_list.retain(|_, item| {
211                let matches = item.text_type_matches(&type_);
212
213                if matches {
214                    was_modified = true;
215                }
216                !matches
217            });
218        } else {
219            // Step 3 Remove each item in the item list whose kind is text.
220            self.item_list.retain(|_, item| {
221                let matches = item.is_file();
222
223                if !matches {
224                    was_modified = true;
225                }
226                matches
227            });
228        }
229
230        was_modified
231    }
232
233    pub(crate) fn files(
234        &self,
235        global: &GlobalScope,
236        can_gc: CanGc,
237        file_list: &mut Vec<DomRoot<File>>,
238    ) {
239        // Step 3 If the data store is in the protected mode return the empty list.
240        if self.mode == Mode::Protected {
241            return;
242        }
243
244        // 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.
245        self.item_list
246            .values()
247            .filter_map(|item| item.as_file(global, can_gc))
248            .for_each(|file| file_list.push(file));
249    }
250
251    pub(crate) fn list_len(&self) -> usize {
252        self.item_list.len()
253    }
254
255    pub(crate) fn iter_item_list(&self) -> indexmap::map::Values<'_, u16, Kind> {
256        self.item_list.values()
257    }
258
259    pub(crate) fn get_by_index(&self, index: usize) -> Option<(&u16, &Kind)> {
260        self.item_list.get_index(index)
261    }
262
263    pub(crate) fn get_by_id(&self, id: &u16) -> Option<&Kind> {
264        self.item_list.get(id)
265    }
266
267    pub(crate) fn remove(&mut self, index: usize) {
268        self.item_list.shift_remove_index(index);
269    }
270
271    pub(crate) fn clear_list(&mut self) {
272        self.item_list.clear();
273        self.clear_was_called = true;
274    }
275}
276
277fn normalize_mime(mut format: DOMString) -> DOMString {
278    // Convert format to ASCII lowercase.
279    format.make_ascii_lowercase();
280
281    match &*format.str() {
282        // If format equals "text", change it to "text/plain".
283        "text" => DOMString::from("text/plain"),
284        // If format equals "url", change it to "text/uri-list".
285        "url" => DOMString::from("text/uri-list"),
286        s => DOMString::from(s),
287    }
288}