1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::codegen::Bindings::StorageBinding::StorageMethods;
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::storageevent::StorageEvent;
use crate::dom::window::Window;
use crate::task_source::TaskSource;
use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender;
use net_traits::storage_thread::{StorageThreadMsg, StorageType};
use net_traits::IpcSend;
use profile_traits::ipc;
use script_traits::ScriptMsg;
use servo_url::ServoUrl;

#[dom_struct]
pub struct Storage {
    reflector_: Reflector,
    storage_type: StorageType,
}

impl Storage {
    fn new_inherited(storage_type: StorageType) -> Storage {
        Storage {
            reflector_: Reflector::new(),
            storage_type: storage_type,
        }
    }

    pub fn new(global: &Window, storage_type: StorageType) -> DomRoot<Storage> {
        reflect_dom_object(Box::new(Storage::new_inherited(storage_type)), global)
    }

    fn get_url(&self) -> ServoUrl {
        self.global().get_url()
    }

    fn get_storage_thread(&self) -> IpcSender<StorageThreadMsg> {
        self.global().resource_threads().sender()
    }
}

impl StorageMethods for Storage {
    // https://html.spec.whatwg.org/multipage/#dom-storage-length
    fn Length(&self) -> u32 {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();

        self.get_storage_thread()
            .send(StorageThreadMsg::Length(
                sender,
                self.get_url(),
                self.storage_type,
            ))
            .unwrap();
        receiver.recv().unwrap() as u32
    }

    // https://html.spec.whatwg.org/multipage/#dom-storage-key
    fn Key(&self, index: u32) -> Option<DOMString> {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();

        self.get_storage_thread()
            .send(StorageThreadMsg::Key(
                sender,
                self.get_url(),
                self.storage_type,
                index,
            ))
            .unwrap();
        receiver.recv().unwrap().map(DOMString::from)
    }

    // https://html.spec.whatwg.org/multipage/#dom-storage-getitem
    fn GetItem(&self, name: DOMString) -> Option<DOMString> {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
        let name = String::from(name);

        let msg = StorageThreadMsg::GetItem(sender, self.get_url(), self.storage_type, name);
        self.get_storage_thread().send(msg).unwrap();
        receiver.recv().unwrap().map(DOMString::from)
    }

    // https://html.spec.whatwg.org/multipage/#dom-storage-setitem
    fn SetItem(&self, name: DOMString, value: DOMString) -> ErrorResult {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
        let name = String::from(name);
        let value = String::from(value);

        let msg = StorageThreadMsg::SetItem(
            sender,
            self.get_url(),
            self.storage_type,
            name.clone(),
            value.clone(),
        );
        self.get_storage_thread().send(msg).unwrap();
        match receiver.recv().unwrap() {
            Err(_) => Err(Error::QuotaExceeded),
            Ok((changed, old_value)) => {
                if changed {
                    self.broadcast_change_notification(Some(name), old_value, Some(value));
                }
                Ok(())
            },
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-storage-removeitem
    fn RemoveItem(&self, name: DOMString) {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
        let name = String::from(name);

        let msg =
            StorageThreadMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone());
        self.get_storage_thread().send(msg).unwrap();
        if let Some(old_value) = receiver.recv().unwrap() {
            self.broadcast_change_notification(Some(name), Some(old_value), None);
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-storage-clear
    fn Clear(&self) {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();

        self.get_storage_thread()
            .send(StorageThreadMsg::Clear(
                sender,
                self.get_url(),
                self.storage_type,
            ))
            .unwrap();
        if receiver.recv().unwrap() {
            self.broadcast_change_notification(None, None, None);
        }
    }

    // https://html.spec.whatwg.org/multipage/#the-storage-interface:supported-property-names
    fn SupportedPropertyNames(&self) -> Vec<DOMString> {
        let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();

        self.get_storage_thread()
            .send(StorageThreadMsg::Keys(
                sender,
                self.get_url(),
                self.storage_type,
            ))
            .unwrap();
        receiver
            .recv()
            .unwrap()
            .into_iter()
            .map(DOMString::from)
            .collect()
    }

    // check-tidy: no specs after this line
    fn NamedGetter(&self, name: DOMString) -> Option<DOMString> {
        self.GetItem(name)
    }

    fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult {
        self.SetItem(name, value)
    }

    fn NamedDeleter(&self, name: DOMString) {
        self.RemoveItem(name);
    }
}

impl Storage {
    /// <https://html.spec.whatwg.org/multipage/#send-a-storage-notification>
    fn broadcast_change_notification(
        &self,
        key: Option<String>,
        old_value: Option<String>,
        new_value: Option<String>,
    ) {
        let storage = self.storage_type;
        let url = self.get_url();
        let msg = ScriptMsg::BroadcastStorageEvent(storage, url, key, old_value, new_value);
        self.global()
            .script_to_constellation_chan()
            .send(msg)
            .unwrap();
    }

    /// <https://html.spec.whatwg.org/multipage/#send-a-storage-notification>
    pub fn queue_storage_event(
        &self,
        url: ServoUrl,
        key: Option<String>,
        old_value: Option<String>,
        new_value: Option<String>,
    ) {
        let global = self.global();
        let this = Trusted::new(self);
        global
            .as_window()
            .task_manager()
            .dom_manipulation_task_source()
            .queue(
                task!(send_storage_notification: move || {
                    let this = this.root();
                    let global = this.global();
                    let event = StorageEvent::new(
                        global.as_window(),
                        atom!("storage"),
                        EventBubbles::DoesNotBubble,
                        EventCancelable::NotCancelable,
                        key.map(DOMString::from),
                        old_value.map(DOMString::from),
                        new_value.map(DOMString::from),
                        DOMString::from(url.into_string()),
                        Some(&this),
                    );
                    event.upcast::<Event>().fire(global.upcast());
                }),
                global.upcast(),
            )
            .unwrap();
    }
}