servo/
user_content_manager.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::rc::Rc;
6
7use constellation_traits::{EmbedderToConstellationMessage, UserContentManagerAction};
8use embedder_traits::user_contents::{UserContentManagerId, UserScript, UserStyleSheet};
9
10use crate::Servo;
11
12/// The [`UserContentManager`] allows embedders to inject content (scripts, styles) during
13/// into the pages loaded within the `WebView`. The same `UserContentManager` can be
14/// shared among multiple `WebView`s. Any updates to the `UserContentManager` will
15/// take effect only after the page is reloaded.
16#[derive(Clone)]
17pub struct UserContentManager {
18    pub(crate) id: UserContentManagerId,
19    pub(crate) servo: Servo,
20}
21
22impl UserContentManager {
23    pub fn new(servo: &Servo) -> Self {
24        Self {
25            id: UserContentManagerId::next(),
26            servo: servo.clone(),
27        }
28    }
29
30    pub(crate) fn id(&self) -> UserContentManagerId {
31        self.id
32    }
33
34    pub fn add_script(&self, user_script: Rc<UserScript>) {
35        self.servo.constellation_proxy().send(
36            EmbedderToConstellationMessage::UserContentManagerAction(
37                self.id,
38                UserContentManagerAction::AddUserScript((*user_script).clone()),
39            ),
40        );
41    }
42
43    pub fn remove_script(&self, user_script: Rc<UserScript>) {
44        self.servo.constellation_proxy().send(
45            EmbedderToConstellationMessage::UserContentManagerAction(
46                self.id,
47                UserContentManagerAction::RemoveUserScript(user_script.id()),
48            ),
49        );
50    }
51
52    pub fn add_stylesheet(&self, user_stylesheet: Rc<UserStyleSheet>) {
53        self.servo.constellation_proxy().send(
54            EmbedderToConstellationMessage::UserContentManagerAction(
55                self.id,
56                UserContentManagerAction::AddUserStyleSheet((*user_stylesheet).clone()),
57            ),
58        );
59    }
60
61    pub fn remove_stylesheet(&self, user_stylesheet: Rc<UserStyleSheet>) {
62        self.servo.constellation_proxy().send(
63            EmbedderToConstellationMessage::UserContentManagerAction(
64                self.id,
65                UserContentManagerAction::RemoveUserStyleSheet(user_stylesheet.id()),
66            ),
67        );
68    }
69}
70
71impl Drop for UserContentManager {
72    fn drop(&mut self) {
73        self.servo.constellation_proxy().send(
74            EmbedderToConstellationMessage::UserContentManagerAction(
75                self.id,
76                UserContentManagerAction::DestroyUserContentManager,
77            ),
78        );
79    }
80}