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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use arboard::Clipboard;
use base::id::{PipelineNamespace, PipelineNamespaceId, WebViewId};
use compositing_traits::ConstellationMsg;
use crossbeam_channel::Sender;
use embedder_traits::{CompositorEventVariant, EmbedderMsg, PromptDefinition};
use script_traits::TraversalDirection;
use servo_url::ServoUrl;
use url::Url;
use webrender_api::units::DeviceIntRect;

use crate::{compositor::IOCompositor, verso::send_to_constellation, window::Window};

/// A web view is an area to display web browsing context. It's what user will treat as a "web page".
#[derive(Debug, Clone)]
pub struct WebView {
    /// Webview ID
    pub webview_id: WebViewId,
    /// The position and size of the webview.
    pub rect: DeviceIntRect,
}

impl WebView {
    /// Create a web view from Winit window.
    pub fn new(webview_id: WebViewId, rect: DeviceIntRect) -> Self {
        Self { webview_id, rect }
    }

    /// Create a panel view from Winit window. A panel is a special web view that focus on controlling states around window.
    /// It could be treated as the control panel or navigation bar of the window depending on usages.
    ///
    /// At the moment, following Web API is supported:
    /// - Close window: `window.close()`
    /// - Navigate to previous page: `window.prompt('PREV')`
    /// - Navigate to next page: `window.prompt('FORWARD')`
    /// - Refresh the page: `window.prompt('REFRESH')`
    /// - Minimize the window: `window.prompt('MINIMIZE')`
    /// - Maximize the window: `window.prompt('MAXIMIZE')`
    /// - Navigate to a specific URL: `window.prompt('NAVIGATE_TO:${url}')`
    pub fn new_panel(rect: DeviceIntRect) -> Self {
        // Reserving a namespace to create TopLevelBrowsingContextId.
        PipelineNamespace::install(PipelineNamespaceId(0));
        let id = WebViewId::new();
        Self {
            webview_id: id,
            rect,
        }
    }

    /// Set the webview size corresponding to the window size.
    pub fn set_size(&mut self, mut rect: DeviceIntRect) {
        rect.min.y = rect.max.y.min(100);
        rect.min.x += 10;
        rect.max.y -= 10;
        rect.max.x -= 10;
        self.rect = rect;
    }
}

impl Window {
    /// Handle servo messages with corresponding web view ID.
    pub fn handle_servo_messages_with_webview(
        &mut self,
        webview_id: WebViewId,
        message: EmbedderMsg,
        sender: &Sender<ConstellationMsg>,
        clipboard: Option<&mut Clipboard>,
        _compositor: &mut IOCompositor,
    ) {
        log::trace!("Verso WebView {webview_id:?} is handling Embedder message: {message:?}",);
        match message {
            EmbedderMsg::LoadStart
            | EmbedderMsg::HeadParsed
            | EmbedderMsg::WebViewOpened(_)
            | EmbedderMsg::WebViewClosed(_) => {
                // Most WebView messages are ignored because it's done by compositor.
                log::trace!("Verso WebView {webview_id:?} ignores this message: {message:?}")
            }
            EmbedderMsg::WebViewFocused(w) => {
                log::debug!(
                    "Verso Window {:?}'s webview {} has loaded completely.",
                    self.id(),
                    w
                );
            }
            EmbedderMsg::LoadComplete => {
                self.window.request_redraw();
                send_to_constellation(sender, ConstellationMsg::FocusWebView(webview_id));
            }
            EmbedderMsg::AllowNavigationRequest(id, _url) => {
                // TODO should provide a API for users to check url
                send_to_constellation(sender, ConstellationMsg::AllowNavigationResponse(id, true));
            }
            EmbedderMsg::GetClipboardContents(sender) => {
                let contents = clipboard
                    .map(|c| {
                        c.get_text().unwrap_or_else(|e| {
                            log::warn!(
                                "Verso WebView {webview_id:?} failed to get clipboard content: {}",
                                e
                            );
                            String::new()
                        })
                    })
                    .unwrap_or_default();
                if let Err(e) = sender.send(contents) {
                    log::warn!(
                        "Verso WebView {webview_id:?} failed to send clipboard content: {}",
                        e
                    );
                }
            }
            EmbedderMsg::SetClipboardContents(text) => {
                if let Some(c) = clipboard {
                    if let Err(e) = c.set_text(text) {
                        log::warn!(
                            "Verso WebView {webview_id:?} failed to set clipboard contents: {}",
                            e
                        );
                    }
                }
            }
            EmbedderMsg::EventDelivered(event) => {
                if let CompositorEventVariant::MouseButtonEvent = event {
                    send_to_constellation(sender, ConstellationMsg::FocusWebView(webview_id));
                }
            }
            e => {
                log::trace!("Verso WebView isn't supporting this message yet: {e:?}")
            }
        }
    }

    /// Handle servo messages with main panel. Return true it requests a new window.
    pub fn handle_servo_messages_with_panel(
        &mut self,
        panel_id: WebViewId,
        message: EmbedderMsg,
        sender: &Sender<ConstellationMsg>,
        clipboard: Option<&mut Clipboard>,
        _compositor: &mut IOCompositor,
    ) -> bool {
        log::trace!("Verso Panel {panel_id:?} is handling Embedder message: {message:?}",);
        match message {
            EmbedderMsg::LoadStart
            | EmbedderMsg::HeadParsed
            | EmbedderMsg::WebViewOpened(_)
            | EmbedderMsg::WebViewClosed(_) => {
                // Most WebView messages are ignored because it's done by compositor.
                log::trace!("Verso Panel ignores this message: {message:?}")
            }
            EmbedderMsg::WebViewFocused(w) => {
                log::debug!(
                    "Verso Window {:?}'s panel {} has loaded completely.",
                    self.id(),
                    w
                );
            }
            EmbedderMsg::LoadComplete => {
                self.window.request_redraw();
                send_to_constellation(sender, ConstellationMsg::FocusWebView(panel_id));

                let demo_url = ServoUrl::parse("https://example.com").unwrap();
                let demo_id = WebViewId::new();
                let size = self.size();
                let rect = DeviceIntRect::from_size(size);
                let mut webview = WebView::new(demo_id, rect);
                webview.set_size(rect);
                self.webview = Some(webview);
                send_to_constellation(sender, ConstellationMsg::NewWebView(demo_url, demo_id));
                log::debug!("Verso Window {:?} adds webview {}", self.id(), demo_id);
            }
            EmbedderMsg::AllowNavigationRequest(id, _url) => {
                // The panel shouldn't navigate to other pages.
                send_to_constellation(sender, ConstellationMsg::AllowNavigationResponse(id, false));
            }
            EmbedderMsg::HistoryChanged(..) | EmbedderMsg::ChangePageTitle(..) => {
                log::trace!("Verso Panel ignores this message: {message:?}")
            }
            EmbedderMsg::Prompt(definition, _origin) => {
                match definition {
                    PromptDefinition::Input(msg, _, prompt_sender) => {
                        let _ = prompt_sender.send(None);
                        if let Some(webview) = &self.webview {
                            let id = webview.webview_id;

                            if msg.starts_with("NAVIGATE_TO:") {
                                let unparsed_url = msg.strip_prefix("NAVIGATE_TO:").unwrap();
                                let url = match Url::parse(unparsed_url) {
                                    Ok(url_parsed) => url_parsed,
                                    Err(e) => {
                                        if e == url::ParseError::RelativeUrlWithoutBase {
                                            Url::parse(&format!("https://{}", unparsed_url))
                                                .unwrap()
                                        } else {
                                            panic!("Verso Panel failed to parse URL: {}", e);
                                        }
                                    }
                                };

                                send_to_constellation(
                                    sender,
                                    ConstellationMsg::LoadUrl(id, ServoUrl::from_url(url)),
                                );
                            } else {
                                match msg.as_str() {
                                    "PREV" => {
                                        send_to_constellation(
                                            sender,
                                            ConstellationMsg::TraverseHistory(
                                                id,
                                                TraversalDirection::Back(1),
                                            ),
                                        );
                                        // TODO Set EmbedderMsg::Status to None
                                    }
                                    "FORWARD" => {
                                        send_to_constellation(
                                            sender,
                                            ConstellationMsg::TraverseHistory(
                                                id,
                                                TraversalDirection::Forward(1),
                                            ),
                                        );
                                        // TODO Set EmbedderMsg::Status to None
                                    }
                                    "REFRESH" => {
                                        // send_to_constellation(sender, ConstellationMsg::Reload(id));
                                        return true;
                                    }
                                    "MINIMIZE" => {
                                        self.window.set_minimized(true);
                                    }
                                    "MAXIMIZE" => {
                                        let is_maximized = self.window.is_maximized();
                                        self.window.set_maximized(!is_maximized);
                                    }
                                    e => log::trace!(
                                        "Verso Panel isn't supporting this prompt message yet: {e}"
                                    ),
                                }
                            }
                        }
                    }
                    _ => log::trace!("Verso Panel isn't supporting this prompt yet"),
                }
            }
            EmbedderMsg::GetClipboardContents(sender) => {
                let contents = clipboard
                    .map(|c| {
                        c.get_text().unwrap_or_else(|e| {
                            log::warn!("Verso Panel failed to get clipboard content: {}", e);
                            String::new()
                        })
                    })
                    .unwrap_or_default();
                if let Err(e) = sender.send(contents) {
                    log::warn!("Verso Panel failed to send clipboard content: {}", e);
                }
            }
            EmbedderMsg::SetClipboardContents(text) => {
                if let Some(c) = clipboard {
                    if let Err(e) = c.set_text(text) {
                        log::warn!("Verso Panel failed to set clipboard contents: {}", e);
                    }
                }
            }
            EmbedderMsg::EventDelivered(event) => {
                if let CompositorEventVariant::MouseButtonEvent = event {
                    send_to_constellation(sender, ConstellationMsg::FocusWebView(panel_id));
                }
            }
            e => {
                log::trace!("Verso Panel isn't supporting this message yet: {e:?}")
            }
        }
        false
    }
}