versoview/webview/
context_menu.rs

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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use crate::verso::send_to_constellation;
use crate::window::Window;
use constellation_traits::{EmbedderToConstellationMessage, TraversalDirection};
use embedder_traits::ContextMenuResult;
#[cfg(linux)]
use embedder_traits::ViewportDetails;
use ipc_channel::ipc::IpcSender;

/* macOS, Windows Native Implementation */
#[cfg(any(target_os = "macos", target_os = "windows"))]
use crossbeam_channel::Sender;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use muda::MenuEvent;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use muda::{ContextMenu as MudaContextMenu, Menu as MudaMenu};
#[cfg(any(target_os = "macos", target_os = "windows"))]
use raw_window_handle::{HasWindowHandle, RawWindowHandle};

/* Wayland Implementation */
#[cfg(linux)]
use super::webview_menu::WebViewMenu;
#[cfg(linux)]
use crate::webview::WebView;
#[cfg(linux)]
use base::id::WebViewId;
#[cfg(linux)]
use crossbeam_channel::Sender;
#[cfg(linux)]
use serde::{Deserialize, Serialize};
#[cfg(linux)]
use servo_url::ServoUrl;
#[cfg(linux)]
use url::Url;
#[cfg(linux)]
use webrender_api::units::DeviceRect;
#[cfg(linux)]
use winit::dpi::LogicalPosition;

/// Basic menu type building block
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub struct Menu(pub MudaMenu);
/// Basic menu type building block
#[cfg(linux)]
#[derive(Debug, Clone)]
pub struct Menu(pub Vec<MenuItem>);

/// The Context Menu of the Window. It will be opened when users right click on any window's
/// webview.
///
/// **Platform Specific**
/// - macOS / Windows: This will be native context menu supported by each OS.
/// - Wayland: Winit doesn't support popup surface of Wayland at the moment. So we utilize a custom
///   webview implementation.
#[derive(Clone)]
pub struct ContextMenu {
    /// IpcSender to send the context menu result to the Servo
    servo_result_sender: Option<IpcSender<ContextMenuResult>>, // None if sender already sent
    #[cfg(any(target_os = "macos", target_os = "windows"))]
    menu: MudaMenu,
    #[cfg(linux)]
    menu_items: Vec<MenuItem>,
    /// The webview that the context menu is attached to
    #[cfg(linux)]
    pub(crate) webview: WebView,
    /// Menu position, used for positioning the context menu by CSS
    #[cfg(linux)]
    position: LogicalPosition<f64>,
}

impl ContextMenu {
    /// Create context menu with custom items
    ///
    /// **Platform Specific**
    /// - macOS / Windows: Creates a context menu by muda crate with natvie OS support
    /// - Wayland: Creates a context menu with webview implementation
    pub fn new_with_menu(servo_result_sender: IpcSender<ContextMenuResult>, menu: Menu) -> Self {
        #[cfg(any(target_os = "macos", target_os = "windows"))]
        {
            Self {
                servo_result_sender: Some(servo_result_sender),
                menu: menu.0,
            }
        }
        #[cfg(linux)]
        {
            let webview_id = WebViewId::new();
            let webview = WebView::new(webview_id, ViewportDetails::default());

            Self {
                servo_result_sender: Some(servo_result_sender),
                menu_items: menu.0,
                webview,
                position: LogicalPosition::new(0.0, 0.0),
            }
        }
    }

    /// Send the context menu result back to the Servo. Can only be sent once.
    pub fn send_result_to_servo(&mut self, result: ContextMenuResult) {
        if let Some(sender) = self.servo_result_sender.take() {
            let _ = sender.send(result);
        }
    }
}

impl Drop for ContextMenu {
    fn drop(&mut self) {
        self.send_result_to_servo(ContextMenuResult::Dismissed);
    }
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
impl ContextMenu {
    /// Show the context menu on current cursor position
    ///
    /// This function returns when the context menu is dismissed
    pub fn show(&self, rwh: impl HasWindowHandle) {
        // Show the context menu
        unsafe {
            let wh = rwh.window_handle().unwrap();
            match wh.as_raw() {
                #[cfg(target_os = "macos")]
                RawWindowHandle::AppKit(handle) => {
                    // use objc2
                    assert!(
                        objc2_foundation::is_main_thread(),
                        "can only access AppKit handles on the main thread"
                    );
                    let ns_view = handle.ns_view.as_ptr();
                    self.menu.show_context_menu_for_nsview(ns_view, None);
                }
                #[cfg(target_os = "windows")]
                RawWindowHandle::Win32(handle) => {
                    let hwnd = handle.hwnd;
                    self.menu.show_context_menu_for_hwnd(hwnd.into(), None);
                }
                handle => unreachable!("unknown handle {handle:?} for platform"),
            }
        }
    }
}

#[cfg(linux)]
impl WebViewMenu for ContextMenu {
    /// Get webview of the context menu
    fn webview(&self) -> &WebView {
        &self.webview
    }

    /// Get resource URL of the context menu
    fn resource_url(&self) -> ServoUrl {
        let mut url = Url::parse("verso://resources/components/context_menu.html").unwrap();
        url.query_pairs_mut()
            .append_pair("items", &self.serialize_items());
        url.query_pairs_mut()
            .append_pair("pos_x", &self.position.x.to_string());
        url.query_pairs_mut()
            .append_pair("pos_y", &self.position.y.to_string());
        ServoUrl::from_url(url)
    }

    fn set_webview_rect(&mut self, rect: DeviceRect) {
        self.webview.set_size(rect);
    }

    fn position(&self) -> LogicalPosition<f64> {
        self.position
    }

    fn set_position(&mut self, position: LogicalPosition<f64>) {
        self.position = position;
    }

    fn close(&mut self, sender: &Sender<EmbedderToConstellationMessage>) {
        self.send_result_to_servo(ContextMenuResult::Dismissed);
        send_to_constellation(
            sender,
            EmbedderToConstellationMessage::CloseWebView(self.webview().webview_id),
        );
    }
}

#[cfg(linux)]
impl ContextMenu {
    /// Convert the context menu items to JSON string
    fn serialize_items(&self) -> String {
        serde_json::to_string(&self.menu_items).unwrap()
    }
}

/// Menu Item
#[cfg(linux)]
#[derive(Debug, Clone, Serialize)]
pub struct MenuItem {
    id: String,
    /// label of the menu item
    pub label: String,
    /// Whether the menu item is enabled
    pub enabled: bool,
}

#[cfg(linux)]
impl MenuItem {
    /// Create a new menu item
    pub fn new(id: Option<&str>, label: &str, enabled: bool) -> Self {
        let id = id.unwrap_or(label);
        Self {
            id: id.to_string(),
            label: label.to_string(),
            enabled,
        }
    }
    /// Get the id of the menu item
    pub fn id(&self) -> &str {
        &self.id
    }
}

/// Context Menu Click Result
#[cfg(linux)]
#[derive(Debug, Clone, Serialize, Deserialize)]

pub struct ContextMenuUIResponse {
    /// The id of the menu item
    pub id: Option<String>,
    /// Close the context menu
    pub close: bool,
}

// Context Menu methods
impl Window {
    #[cfg(any(target_os = "macos", target_os = "windows"))]
    pub(crate) fn show_context_menu(
        &self,
        servo_sender: IpcSender<ContextMenuResult>,
    ) -> ContextMenu {
        use muda::MenuItem;

        let tab = self.tab_manager.current_tab().unwrap();
        let history = tab.history();
        let history_len = history.list.len();

        // items
        let back = MenuItem::with_id("back", "Back", history.current_idx > 0, None);
        let forward = MenuItem::with_id(
            "forward",
            "Forward",
            history.current_idx + 1 < history_len,
            None,
        );
        let reload = MenuItem::with_id("reload", "Reload", true, None);

        let menu = MudaMenu::new();
        let _ = menu.append_items(&[&back, &forward, &reload]);

        let context_menu = ContextMenu::new_with_menu(servo_sender, Menu(menu));
        context_menu.show(self.window.window_handle().unwrap());

        context_menu
    }

    #[cfg(linux)]
    pub(crate) fn show_context_menu(
        &mut self,
        sender: &Sender<EmbedderToConstellationMessage>,
        servo_sender: IpcSender<ContextMenuResult>,
    ) -> ContextMenu {
        let tab = self.tab_manager.current_tab().unwrap();
        let history = tab.history();
        let history_len = history.list.len();

        // items
        let back = MenuItem::new(Some("back"), "Back", history.current_idx > 0);
        let forward = MenuItem::new(
            Some("forward"),
            "Forward",
            history.current_idx + 1 < history_len,
        );
        let reload = MenuItem::new(Some("reload"), "Reload", true);

        let mut context_menu =
            ContextMenu::new_with_menu(servo_sender, Menu(vec![back, forward, reload]));

        let position = self.mouse_position.get().unwrap();
        context_menu.show(sender, self, position);

        context_menu
    }

    #[cfg(any(target_os = "macos", target_os = "windows"))]
    pub(crate) fn handle_context_menu_event(
        &self,
        mut context_menu: ContextMenu,
        sender: &Sender<EmbedderToConstellationMessage>,
        event: MenuEvent,
    ) {
        context_menu.send_result_to_servo(ContextMenuResult::Dismissed);
        // TODO: should be more flexible to handle different menu items
        let active_tab = self.tab_manager.current_tab().unwrap();
        match event.id().0.as_str() {
            "back" => {
                send_to_constellation(
                    sender,
                    EmbedderToConstellationMessage::TraverseHistory(
                        active_tab.id(),
                        TraversalDirection::Back(1),
                    ),
                );
            }
            "forward" => {
                send_to_constellation(
                    sender,
                    EmbedderToConstellationMessage::TraverseHistory(
                        active_tab.id(),
                        TraversalDirection::Forward(1),
                    ),
                );
            }
            "reload" => {
                send_to_constellation(
                    sender,
                    EmbedderToConstellationMessage::Reload(active_tab.id()),
                );
            }
            _ => {}
        }
    }

    /// Handle linux context menu event
    // TODO(context-menu): should make the call in synchronous way after calling show_context_menu, otherwise
    // we'll have to deal with constellation sender and other parameter's lifetime, also we lose the context that why this context menu popup
    #[cfg(linux)]
    pub(crate) fn handle_context_menu_event(
        &mut self,
        sender: &Sender<EmbedderToConstellationMessage>,
        event: crate::webview::context_menu::ContextMenuUIResponse,
    ) {
        self.close_webview_menu(sender);
        if let Some(id) = event.id {
            if let Some(tab_id) = self.tab_manager.current_tab_id() {
                match id.as_str() {
                    "back" => {
                        send_to_constellation(
                            sender,
                            EmbedderToConstellationMessage::TraverseHistory(
                                tab_id,
                                TraversalDirection::Back(1),
                            ),
                        );
                    }
                    "forward" => {
                        send_to_constellation(
                            sender,
                            EmbedderToConstellationMessage::TraverseHistory(
                                tab_id,
                                TraversalDirection::Forward(1),
                            ),
                        );
                    }
                    "reload" => {
                        send_to_constellation(
                            sender,
                            EmbedderToConstellationMessage::Reload(tab_id),
                        );
                    }
                    _ => {}
                }
            } else {
                log::error!("No active webview to handle context menu event");
            }
        };
    }
}