Skip to main content

servoshell/desktop/
gui.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::collections::{HashMap, HashSet};
6#[cfg(any(
7    target_os = "windows",
8    target_os = "linux",
9    target_os = "freebsd",
10    target_os = "macos"
11))]
12use std::fs;
13#[cfg(any(
14    target_os = "windows",
15    target_os = "linux",
16    target_os = "freebsd",
17    target_os = "macos"
18))]
19use std::path::Path;
20use std::rc::Rc;
21use std::sync::Arc;
22use std::time::{Duration, Instant};
23
24use dpi::PhysicalSize;
25use egui::text::{CCursor, CCursorRange};
26use egui::text_edit::TextEditState;
27use egui::{
28    Button, FontDefinitions, Id, Key, Label, LayerId, Modifiers, Order, PaintCallback, Panel, Vec2,
29    WidgetInfo, WidgetType,
30};
31#[cfg(any(
32    target_os = "windows",
33    target_os = "linux",
34    target_os = "freebsd",
35    target_os = "macos"
36))]
37use egui::{FontData, FontFamily};
38use egui_glow::{CallbackFn, EguiGlow};
39use egui_winit::EventResponse;
40use euclid::{Length, Point2D, Rect, Scale, Size2D};
41#[cfg(any(
42    target_os = "windows",
43    target_os = "linux",
44    target_os = "freebsd",
45    target_os = "macos"
46))]
47use log::info;
48use log::warn;
49use servo::{
50    DeviceIndependentPixel, DevicePixel, EmbedderControlId, Image, LoadStatus,
51    OffscreenRenderingContext, PixelFormat, RenderingContext, TooltipControl, WebView, WebViewId,
52};
53use url::Url;
54use winit::event::WindowEvent;
55use winit::event_loop::{ActiveEventLoop, EventLoopProxy};
56use winit::window::Window;
57
58use crate::desktop::event_loop::AppEvent;
59use crate::desktop::headed_window::{self, TOOLTIP_DELAY};
60use crate::desktop::webview_widget::WebViewWidget;
61use crate::running_app_state::{RunningAppState, UserInterfaceCommand};
62use crate::window::{ServoShellWindow, TopLevelWebViewCreationRequest};
63
64pub struct ActiveTooltip {
65    id: EmbedderControlId,
66    webview_id: WebViewId,
67    text: String,
68    shown_at: Instant,
69}
70
71/// The user interface of a headed servoshell. Currently this is implemented via
72/// egui.
73pub struct Gui {
74    rendering_context: Rc<OffscreenRenderingContext>,
75    context: EguiGlow,
76    toolbar_height: Length<f32, DeviceIndependentPixel>,
77
78    location: String,
79
80    /// Whether the location has been edited by the user without clicking Go.
81    location_dirty: bool,
82
83    /// The [`LoadStatus`] of the active `WebView`.
84    load_status: LoadStatus,
85
86    /// The text to display in the status bar on the bottom of the window.
87    status_text: Option<String>,
88
89    pub tooltip: Option<ActiveTooltip>,
90
91    /// Whether or not the current `WebView` can navigate backward.
92    can_go_back: bool,
93
94    /// Whether or not the current `WebView` can navigate forward.
95    can_go_forward: bool,
96
97    /// Handle to the GPU texture of the favicon.
98    ///
99    /// These need to be cached across egui draw calls.
100    favicon_textures: HashMap<WebViewId, (egui::TextureHandle, egui::load::SizedTexture)>,
101
102    /// A record of accessibility tree ids that correspond to extant WebViews and have already been
103    /// sent to AccessKit. This is used to avoid focusing a grafted tree before it has been sent.
104    /// Pruned at the end of each GUI update.
105    sent_webview_accesskit_trees: HashSet<accesskit::TreeId>,
106
107    /// AccessKit tree updates pending to be sent during the next call to [`Self::update`].
108    /// This allows us to ensure that graft nodes are sent before the subtrees they graft.
109    pending_accesskit_updates: Vec<accesskit::TreeUpdate>,
110
111    /// Whether the [`WebViewWidget`] corresponding to the currently active [`WebView`] has keyboard
112    /// focus within the egui interface. This remains `true` even if the application loses system
113    /// focus, so that application focus can be re-set to the [`WebViewWidget`] once the application
114    /// regains system focus.
115    webview_widget_focused: bool,
116}
117
118fn truncate_with_ellipsis(input: &str, max_length: usize) -> String {
119    if input.chars().count() > max_length {
120        let truncated: String = input.chars().take(max_length.saturating_sub(1)).collect();
121        format!("{}…", truncated)
122    } else {
123        input.to_string()
124    }
125}
126
127#[cfg(any(
128    target_os = "windows",
129    target_os = "linux",
130    target_os = "freebsd",
131    target_os = "macos"
132))]
133fn load_cjk_fonts(font_candidates: &[(&str, &str)]) -> FontDefinitions {
134    let mut fonts = FontDefinitions::default();
135    let mut loaded_font_names = Vec::new();
136
137    for (path_str, font_name) in font_candidates.iter() {
138        let font_path = Path::new(path_str);
139        if font_path.exists() {
140            match fs::read(font_path) {
141                Ok(bytes) => {
142                    if !fonts.font_data.contains_key(*font_name) {
143                        fonts
144                            .font_data
145                            .insert(font_name.to_string(), Arc::new(FontData::from_owned(bytes)));
146                        loaded_font_names.push(font_name.to_string());
147                        info!("Loaded font: {}", font_name);
148                    }
149                },
150                Err(error) => {
151                    info!("Failed to read font {}: {}", font_name, error);
152                },
153            }
154        }
155    }
156
157    if !loaded_font_names.is_empty() &&
158        let Some(proportional) = fonts.families.get_mut(&FontFamily::Proportional)
159    {
160        proportional.append(&mut loaded_font_names);
161    }
162
163    fonts
164}
165
166#[cfg(target_os = "windows")]
167fn configure_fonts() -> FontDefinitions {
168    load_cjk_fonts(&[
169        (r"C:\Windows\Fonts\malgun.ttf", "Malgun Gothic"), // Korean
170        (r"C:\Windows\Fonts\msyh.ttc", "Microsoft YaHei"), // Chinese + Japanese
171    ])
172}
173
174#[cfg(any(target_os = "linux", target_os = "freebsd"))]
175fn configure_fonts() -> FontDefinitions {
176    load_cjk_fonts(&[
177        (
178            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
179            "Noto Sans CJK",
180        ), // Ubuntu/Debian
181        (
182            "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
183            "Noto Sans CJK",
184        ), // Fedora/Arch
185        // FreeBSD splits the Noto CJK fonts into regional subsets
186        (
187            "/usr/local/share/fonts/noto/NotoSansCJKhk-Regular.otf",
188            "Noto Sans CJK HK",
189        ),
190        (
191            "/usr/local/share/fonts/noto/NotoSansCJKjp-Regular.otf",
192            "Noto Sans CJK JP",
193        ),
194        (
195            "/usr/local/share/fonts/noto/NotoSansCJKkr-Regular.otf",
196            "Noto Sans CJK KR",
197        ),
198        (
199            "/usr/local/share/fonts/noto/NotoSansCJKsc-Regular.otf",
200            "Noto Sans CJK SC",
201        ),
202        (
203            "/usr/local/share/fonts/noto/NotoSansCJKtc-Regular.otf",
204            "Noto Sans CJK TC",
205        ),
206        (
207            "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
208            "WenQuanYi Micro Hei",
209        ), // common fallback
210        (
211            "/usr/local/share/fonts/wqy/wqy-microhei.ttc",
212            "WenQuanYi Micro Hei",
213        ), // FreeBSD
214    ])
215}
216
217#[cfg(target_os = "macos")]
218fn configure_fonts() -> FontDefinitions {
219    load_cjk_fonts(&[
220        (
221            "/System/Library/Fonts/AppleSDGothicNeo.ttc",
222            "Apple SD Gothic Neo",
223        ), // Korean
224        ("/System/Library/Fonts/STHeiti Medium.ttc", "STHeiti Medium"), // Chinese + Japanese
225    ])
226}
227
228impl Drop for Gui {
229    fn drop(&mut self) {
230        self.rendering_context
231            .make_current()
232            .expect("Could not make window RenderingContext current");
233        self.context.destroy();
234    }
235}
236
237impl Gui {
238    pub(crate) fn new(
239        winit_window: &Window,
240        event_loop: &ActiveEventLoop,
241        event_loop_proxy: EventLoopProxy<AppEvent>,
242        rendering_context: Rc<OffscreenRenderingContext>,
243        initial_url: Url,
244        device_pixel_override: Option<f32>,
245    ) -> Self {
246        rendering_context
247            .make_current()
248            .expect("Could not make window RenderingContext current");
249        let mut context = EguiGlow::new(
250            event_loop,
251            rendering_context.glow_gl_api(),
252            None,
253            None,
254            false,
255        );
256
257        let font_definitions = configure_fonts();
258        context.egui_ctx.set_fonts(font_definitions);
259
260        context
261            .egui_winit
262            .init_accesskit(event_loop, winit_window, event_loop_proxy);
263        winit_window.set_visible(true);
264
265        context.egui_ctx.options_mut(|options| {
266            // Disable the builtin egui handlers for the Ctrl+Plus, Ctrl+Minus and Ctrl+0
267            // shortcuts as they don't work well with servoshell's `device-pixel-ratio` CLI argument.
268            options.zoom_with_keyboard = false;
269
270            // On platforms where winit fails to obtain a system theme, fall back to a light theme
271            // since it is the more common default.
272            options.fallback_theme = egui::Theme::Light;
273
274            options.zoom_factor = device_pixel_override.map_or(1.0, |device_pixel_override| {
275                device_pixel_override / winit_window.scale_factor() as f32
276            });
277        });
278
279        Self {
280            rendering_context,
281            context,
282            toolbar_height: Default::default(),
283            location: initial_url.to_string(),
284            location_dirty: false,
285            load_status: LoadStatus::Complete,
286            status_text: None,
287            tooltip: None,
288            can_go_back: false,
289            can_go_forward: false,
290            favicon_textures: Default::default(),
291            sent_webview_accesskit_trees: Default::default(),
292            pending_accesskit_updates: vec![],
293            webview_widget_focused: false,
294        }
295    }
296
297    /// See [`webview_widget_focused`](#structfield.webview_widget_focused)
298    pub(crate) fn webview_widget_focused(&self) -> bool {
299        self.webview_widget_focused
300    }
301
302    /// See [`webview_widget_focused`](#structfield.webview_widget_focused)
303    pub(crate) fn set_webview_widget_focused(&mut self, focused: bool) {
304        self.webview_widget_focused = focused;
305    }
306
307    pub(crate) fn on_window_event(
308        &mut self,
309        winit_window: &Window,
310        event: &WindowEvent,
311    ) -> EventResponse {
312        self.context.on_window_event(winit_window, event)
313    }
314
315    /// The height of the top toolbar of this user inteface ie the distance from the top of the
316    /// window to the position of the `WebView`.
317    pub(crate) fn toolbar_height(&self) -> Length<f32, DeviceIndependentPixel> {
318        self.toolbar_height
319    }
320
321    /// Return true iff the given position is over the egui toolbar.
322    pub(crate) fn is_in_egui_toolbar_rect(
323        &self,
324        position: Point2D<f32, DeviceIndependentPixel>,
325    ) -> bool {
326        position.y < self.toolbar_height.get()
327    }
328
329    /// Create a frameless button with square sizing, as used in the toolbar.
330    fn toolbar_button(text: &str) -> egui::Button<'_> {
331        egui::Button::new(text)
332            .frame(false)
333            .min_size(Vec2 { x: 20.0, y: 20.0 })
334    }
335
336    /// Draws a browser tab, checking for clicks and queues appropriate [`UserInterfaceCommand`]s.
337    /// Using a custom widget here would've been nice, but it doesn't seem as though egui
338    /// supports that, so we arrange multiple Widgets in a way that they look connected.
339    fn browser_tab(
340        ui: &mut egui::Ui,
341        window: &ServoShellWindow,
342        webview: WebView,
343        favicon_texture: Option<egui::load::SizedTexture>,
344    ) {
345        let label = match (webview.page_title(), webview.url()) {
346            (Some(title), _) if !title.is_empty() => title,
347            (_, Some(url)) => url.to_string(),
348            _ => "New Tab".into(),
349        };
350
351        let inactive_bg_color = ui.visuals().window_fill;
352        let active_bg_color = ui.visuals().widgets.active.weak_bg_fill;
353        let active = window.active_webview().map(|webview| webview.id()) == Some(webview.id());
354
355        // Setup a tab frame that will contain the favicon, title and close button
356        let mut tab_frame = egui::Frame::NONE.corner_radius(4).begin(ui);
357        {
358            tab_frame.content_ui.add_space(5.0);
359
360            let visuals = tab_frame.content_ui.visuals_mut();
361            // Remove the stroke so we don't see the border between the close button and the label
362            visuals.widgets.active.bg_stroke.width = 0.0;
363            visuals.widgets.hovered.bg_stroke.width = 0.0;
364            // Now we make sure the fill color is always the same, irrespective of state, that way
365            // we can make sure that both the label and close button have the same background color
366            visuals.widgets.noninteractive.weak_bg_fill = inactive_bg_color;
367            visuals.widgets.inactive.weak_bg_fill = inactive_bg_color;
368            visuals.widgets.hovered.weak_bg_fill = active_bg_color;
369            visuals.widgets.active.weak_bg_fill = active_bg_color;
370            visuals.selection.bg_fill = active_bg_color;
371            visuals.selection.stroke.color = visuals.widgets.active.fg_stroke.color;
372            visuals.widgets.hovered.fg_stroke.color = visuals.widgets.active.fg_stroke.color;
373
374            // Expansion would also show that they are 2 separate widgets
375            visuals.widgets.active.expansion = 0.0;
376            visuals.widgets.hovered.expansion = 0.0;
377
378            if let Some(favicon) = favicon_texture {
379                tab_frame.content_ui.add(
380                    egui::Image::from_texture(favicon)
381                        .fit_to_exact_size(egui::vec2(16.0, 16.0))
382                        .bg_fill(egui::Color32::TRANSPARENT),
383                );
384            }
385
386            let tab = tab_frame
387                .content_ui
388                // No frame: its interact rect is taller than the tab, so only the tab frame is filled.
389                .add(Button::selectable(active, truncate_with_ellipsis(&label, 20)).frame(false))
390                .on_hover_ui(|ui| {
391                    ui.label(&label);
392                });
393
394            let close_button = tab_frame
395                .content_ui
396                .add(egui::Button::new("X").fill(egui::Color32::TRANSPARENT));
397            close_button.widget_info(|| {
398                let mut info = WidgetInfo::new(WidgetType::Button);
399                info.label = Some("Close".into());
400                info
401            });
402            if close_button.clicked() || close_button.middle_clicked() || tab.middle_clicked() {
403                window
404                    .queue_user_interface_command(UserInterfaceCommand::CloseWebView(webview.id()));
405            } else if !active && tab.clicked() {
406                window.activate_webview(webview.id());
407            }
408        }
409
410        let response = tab_frame.allocate_space(ui);
411        let fill_color = if active || response.hovered() {
412            active_bg_color
413        } else {
414            inactive_bg_color
415        };
416        tab_frame.frame.fill = fill_color;
417        tab_frame.end(ui);
418    }
419
420    /// Update the user interface, but do not paint the updated state.
421    pub(crate) fn update(
422        &mut self,
423        state: &RunningAppState,
424        window: &ServoShellWindow,
425        headed_window: &headed_window::HeadedWindow,
426    ) {
427        self.rendering_context
428            .make_current()
429            .expect("Could not make RenderingContext current");
430        let Self {
431            rendering_context,
432            context,
433            toolbar_height,
434            location,
435            location_dirty,
436            favicon_textures,
437            ..
438        } = self;
439
440        let winit_window = headed_window.winit_window();
441        context.run(winit_window, |ctx| {
442            load_pending_favicons(ctx, window, favicon_textures);
443
444            // TODO: While in fullscreen add some way to mitigate the increased phishing risk
445            // when not displaying the URL bar: https://github.com/servo/servo/issues/32443
446            // Show toolbar unless fullscreen is from document (web API)
447            if !headed_window.is_fullscreen_from_document() {
448                let frame = egui::Frame::default()
449                    .fill(ctx.style().visuals.window_fill)
450                    .inner_margin(4.0);
451                Panel::top("toolbar").frame(frame).show_inside(ctx, |ui| {
452                    ui.allocate_ui_with_layout(
453                        ui.available_size(),
454                        egui::Layout::left_to_right(egui::Align::Center),
455                        |ui| {
456                            let back_button =
457                                ui.add_enabled(self.can_go_back, Gui::toolbar_button("⏴"));
458                            back_button.widget_info(|| {
459                                let mut info = WidgetInfo::new(WidgetType::Button);
460                                info.label = Some("Back".into());
461                                info
462                            });
463                            if back_button.clicked() {
464                                *location_dirty = false;
465                                window.queue_user_interface_command(UserInterfaceCommand::Back);
466                            }
467
468                            let forward_button =
469                                ui.add_enabled(self.can_go_forward, Gui::toolbar_button("⏵"));
470                            forward_button.widget_info(|| {
471                                let mut info = WidgetInfo::new(WidgetType::Button);
472                                info.label = Some("Forward".into());
473                                info
474                            });
475                            if forward_button.clicked() {
476                                *location_dirty = false;
477                                window.queue_user_interface_command(UserInterfaceCommand::Forward);
478                            }
479
480                            match self.load_status {
481                                LoadStatus::Started | LoadStatus::HeadParsed => {
482                                    let stop_button = ui.add(Gui::toolbar_button("X"));
483                                    stop_button.widget_info(|| {
484                                        let mut info = WidgetInfo::new(WidgetType::Button);
485                                        info.label = Some("Stop".into());
486                                        info
487                                    });
488                                    if stop_button.clicked() {
489                                        warn!("Do not support stop yet.");
490                                    }
491                                },
492                                LoadStatus::Complete | LoadStatus::Stopped => {
493                                    let reload_button = ui.add(Gui::toolbar_button("↻"));
494                                    reload_button.widget_info(|| {
495                                        let mut info = WidgetInfo::new(WidgetType::Button);
496                                        info.label = Some("Reload".into());
497                                        info
498                                    });
499                                    if reload_button.clicked() {
500                                        *location_dirty = false;
501                                        window.queue_user_interface_command(
502                                            UserInterfaceCommand::Reload,
503                                        );
504                                    }
505                                },
506                            }
507                            ui.add_space(2.0);
508
509                            ui.allocate_ui_with_layout(
510                                ui.available_size(),
511                                egui::Layout::right_to_left(egui::Align::Center),
512                                |ui| {
513                                    let mut experimental_preferences_enabled =
514                                        state.experimental_preferences_enabled();
515                                    let prefs_toggle = ui
516                                        .toggle_value(&mut experimental_preferences_enabled, "☢")
517                                        .on_hover_text("Enable experimental prefs");
518                                    prefs_toggle.widget_info(|| {
519                                        let mut info = WidgetInfo::new(WidgetType::Button);
520                                        info.label = Some("Enable experimental preferences".into());
521                                        info.selected = Some(experimental_preferences_enabled);
522                                        info
523                                    });
524                                    if prefs_toggle.clicked() {
525                                        state.set_experimental_preferences_enabled(
526                                            experimental_preferences_enabled,
527                                        );
528                                        *location_dirty = false;
529                                        window.queue_user_interface_command(
530                                            UserInterfaceCommand::ReloadAll,
531                                        );
532                                    }
533
534                                    let location_id = egui::Id::new("location_input");
535                                    let location_field = ui.add_sized(
536                                        ui.available_size(),
537                                        egui::TextEdit::singleline(location)
538                                            .id(location_id)
539                                            .hint_text("Search or enter address"),
540                                    );
541
542                                    if location_field.changed() {
543                                        *location_dirty = true;
544                                    }
545                                    // Handle adddress bar shortcut.
546                                    if ui.input(|i| {
547                                        if cfg!(target_os = "macos") {
548                                            i.clone().consume_key(Modifiers::COMMAND, Key::L)
549                                        } else {
550                                            i.clone().consume_key(Modifiers::COMMAND, Key::L) ||
551                                                i.clone().consume_key(Modifiers::ALT, Key::D)
552                                        }
553                                    }) {
554                                        // The focus request immediately makes gained_focus return true.
555                                        location_field.request_focus();
556                                    }
557                                    // Select address bar text when it's focused (click or shortcut).
558                                    if location_field.gained_focus() &&
559                                        let Some(mut state) =
560                                            TextEditState::load(ui.ctx(), location_id)
561                                    {
562                                        // Select the whole input.
563                                        state.cursor.set_char_range(Some(CCursorRange::two(
564                                            CCursor::new(0),
565                                            CCursor::new(location.len()),
566                                        )));
567                                        state.store(ui.ctx(), location_id);
568                                    }
569                                    // Navigate to address when enter is pressed in the address bar.
570                                    if location_field.lost_focus() &&
571                                        ui.input(|i| i.clone().key_pressed(Key::Enter))
572                                    {
573                                        window.queue_user_interface_command(
574                                            UserInterfaceCommand::Go(location.clone()),
575                                        );
576                                    }
577                                },
578                            );
579                        },
580                    );
581                });
582
583                // A simple Tab header strip
584                let outer = Panel::top("tabs").show_inside(ctx, |ui| {
585                    // Add scroll for overflowing tabs
586                    egui::ScrollArea::horizontal()
587                        .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
588                        .show(ui, |ui| {
589                            ui.allocate_ui_with_layout(
590                                ui.available_size(),
591                                egui::Layout::left_to_right(egui::Align::Center),
592                                |ui| {
593                                    for (id, webview) in window.webviews().into_iter() {
594                                        let favicon = favicon_textures
595                                            .get(&id)
596                                            .map(|(_, favicon)| favicon)
597                                            .copied();
598                                        Self::browser_tab(ui, window, webview, favicon);
599                                    }
600
601                                    let new_tab_button = ui.add(Gui::toolbar_button("+"));
602                                    new_tab_button.widget_info(|| {
603                                        let mut info = WidgetInfo::new(WidgetType::Button);
604                                        info.label = Some("New tab".into());
605                                        info
606                                    });
607                                    if new_tab_button.clicked() {
608                                        window.queue_user_interface_command(
609                                            UserInterfaceCommand::NewWebView,
610                                        );
611                                    }
612
613                                    let new_window_button = ui.add(Gui::toolbar_button("⊞"));
614                                    new_window_button.widget_info(|| {
615                                        let mut info = WidgetInfo::new(WidgetType::Button);
616                                        info.label = Some("New window".into());
617                                        info
618                                    });
619                                    if new_window_button.clicked() {
620                                        let url = Url::parse("servo:newtab")
621                                            .expect("'servo:newtab' should be valid");
622                                        window.queue_user_interface_command(
623                                            UserInterfaceCommand::NewWindow(
624                                                TopLevelWebViewCreationRequest::WithUrl(url),
625                                            ),
626                                        );
627                                    }
628                                },
629                            );
630                        })
631                });
632
633                *toolbar_height = Length::new(outer.response.rect.max.y);
634            } else {
635                *toolbar_height = Length::default();
636            }
637
638            // If the top parts of the GUI changed size, then update the size of the WebView and also
639            // the size of its RenderingContext.
640            let webview_rect = ctx.available_rect_before_wrap();
641            headed_window.for_each_active_dialog(window, |dialog| dialog.update(ctx, webview_rect));
642
643            // Some other widget may have claimed focus on this tick, so detect if the currently
644            // focused egui widget is still a WebView.
645            let focused_widget = ctx.memory(|memory| memory.focused());
646            if focused_widget.is_some_and(|focused_widget| {
647                !window
648                    .webview_collection()
649                    .values()
650                    .any(|webview| egui::Id::new(webview.id()) == focused_widget)
651            }) {
652                self.webview_widget_focused = false;
653            }
654
655            // Create a WebViewWidget for each webview, not just the active one, so that every
656            // webview gets an AccessKit graft node. This prevents any TreeUpdates from inactive
657            // webviews from causing a panic in AccessKit.
658            let scale_factor =
659                Scale::<_, DeviceIndependentPixel, DevicePixel>::new(ctx.pixels_per_point());
660            let active_webview = window.active_webview();
661            for (_, webview) in window.webviews() {
662                let webview_active = active_webview.as_ref() == Some(&webview);
663                let webview_contains_focus = webview_active && self.webview_widget_focused;
664
665                // AccessKit will panic if we try to focus a graft node whose grafted tree hasn't
666                // been sent yet, so we need to keep track of whether a TreeUpdate containing the
667                // grafted tree has been sent before focusing the WebViewWidget if accessibility is
668                // active.
669                let tree_id_sent = webview
670                    .accesskit_tree_id()
671                    .is_none_or(|tree_id| self.sent_webview_accesskit_trees.contains(&tree_id));
672                let can_take_focus = webview_active && webview.focused() && tree_id_sent;
673                let panel = WebViewWidget::new(
674                    webview.clone(),
675                    scale_factor,
676                    webview_rect,
677                    webview_contains_focus,
678                    can_take_focus,
679                );
680
681                // If focus moves into the WebView via keyboard or assistive technology, then we need
682                // to update the GUI state to reflect that.
683                if ctx.add(panel).gained_focus() {
684                    self.webview_widget_focused = true;
685                }
686            }
687
688            let size = Size2D::new(webview_rect.width(), webview_rect.height()) * scale_factor;
689            if let Some(webview) = window.active_webview() &&
690                size != webview.size()
691            {
692                // `rect` is sized to just the WebView viewport, which is required by
693                // `OffscreenRenderingContext` See:
694                // <https://github.com/servo/servo/issues/38369#issuecomment-3138378527>
695                webview.resize(PhysicalSize::new(size.width as u32, size.height as u32))
696            }
697
698            if let Some(status_text) = &self.status_text {
699                egui::Tooltip::always_open(
700                    ctx.clone(),
701                    LayerId::new(Order::Tooltip, Id::new("tooltip")),
702                    "tooltip layer".into(),
703                    webview_rect.right_bottom(),
704                )
705                .show(|ui| ui.add(Label::new(status_text.clone()).extend()));
706            }
707
708            if let Some(tooltip) = &self.tooltip &&
709                tooltip.shown_at.elapsed() >= TOOLTIP_DELAY
710            {
711                egui::Tooltip::always_open(
712                    ctx.clone(),
713                    LayerId::new(Order::Tooltip, Id::new("embedder_tooltip")),
714                    "embedder tooltip layer".into(),
715                    webview_rect.right_bottom(),
716                )
717                .at_pointer()
718                .show(|ui| ui.add(Label::new(tooltip.text.clone()).extend()));
719            }
720
721            window.repaint_webviews();
722
723            if let Some(render_to_parent) = rendering_context.render_to_parent_callback() {
724                ctx.layer_painter(LayerId::background()).add(PaintCallback {
725                    rect: webview_rect,
726                    callback: Arc::new(CallbackFn::new(move |info, painter| {
727                        let clip = info.viewport_in_pixels();
728                        let rect_in_parent = Rect::new(
729                            Point2D::new(clip.left_px, clip.from_bottom_px),
730                            Size2D::new(clip.width_px, clip.height_px),
731                        );
732                        render_to_parent(painter.gl(), rect_in_parent)
733                    })),
734                });
735            }
736        });
737
738        // If any egui widget requested a repaint, also request a repaint for our
739        // containing window. This allows egui widget to animate on their own.
740        if self.context.egui_ctx.has_requested_repaint() {
741            window.set_needs_repaint();
742        }
743
744        let adapter = self
745            .context
746            .egui_winit
747            .accesskit
748            .as_mut()
749            .expect("guaranteed by Gui::new()");
750        for tree_update in self.pending_accesskit_updates.drain(..) {
751            let tree_id = tree_update.tree_id;
752            adapter.update_if_active(|| tree_update);
753            self.sent_webview_accesskit_trees.insert(tree_id);
754        }
755
756        // Prune any AccessKit tree ids which don't correspond to extant WebViews.
757        self.sent_webview_accesskit_trees.retain(|tree_id| {
758            window
759                .webview_collection()
760                .values()
761                .any(|webview| webview.accesskit_tree_id() == Some(*tree_id))
762        });
763    }
764
765    /// Paint the GUI, as of the last update.
766    pub(crate) fn paint(&mut self, window: &Window) {
767        self.rendering_context
768            .make_current()
769            .expect("Could not make RenderingContext current");
770        self.rendering_context
771            .parent_context()
772            .prepare_for_rendering();
773        self.context.paint(window);
774        self.rendering_context.parent_context().present();
775    }
776
777    /// Updates the location field from the given [`RunningAppState`], unless the user has started
778    /// editing it without clicking Go, returning true iff it has changed (needing an egui update).
779    fn update_location_in_toolbar(&mut self, window: &ServoShellWindow) -> bool {
780        // User edited without clicking Go?
781        if self.location_dirty {
782            return false;
783        }
784
785        let current_url_string = window
786            .active_webview()
787            .and_then(|webview| Some(webview.url()?.to_string()));
788        match current_url_string {
789            Some(location) if location != self.location => {
790                self.location = location;
791                true
792            },
793            _ => false,
794        }
795    }
796
797    fn update_load_status(&mut self, window: &ServoShellWindow) -> bool {
798        let state_status = window
799            .active_webview()
800            .map(|webview| webview.load_status())
801            .unwrap_or(LoadStatus::Complete);
802        let old_status = std::mem::replace(&mut self.load_status, state_status);
803        let status_changed = old_status != self.load_status;
804
805        // When the load status changes, we want the new changes to the URL to start
806        // being reflected in the location bar.
807        if status_changed {
808            self.location_dirty = false;
809        }
810
811        status_changed
812    }
813
814    fn update_status_text(&mut self, window: &ServoShellWindow) -> bool {
815        let state_status = window
816            .active_webview()
817            .and_then(|webview| webview.status_text());
818        let old_status = std::mem::replace(&mut self.status_text, state_status);
819        old_status != self.status_text
820    }
821
822    pub(crate) fn show_tooltip(&mut self, webview_id: WebViewId, control: &TooltipControl) {
823        self.tooltip = Some(ActiveTooltip {
824            id: control.id,
825            webview_id,
826            text: control.text.clone(),
827            shown_at: Instant::now(),
828        });
829    }
830
831    /// Clears the tooltip only if it is still the one identified by `id`, so a late hide
832    /// for an old tooltip doesn't remove a newer one.
833    pub(crate) fn hide_tooltip(&mut self, id: EmbedderControlId) -> bool {
834        if self
835            .tooltip
836            .as_ref()
837            .is_some_and(|tooltip| tooltip.id == id)
838        {
839            self.tooltip = None;
840            return true;
841        }
842        false
843    }
844
845    /// restart the delay if a tooltip is waiting to be shown. Return true if this did.
846    pub(crate) fn restart_pending_tooltip_delay(&mut self) -> bool {
847        match self.tooltip {
848            Some(ref mut tooltip) if tooltip.shown_at.elapsed() != Duration::from_millis(0) => {
849                tooltip.shown_at = Instant::now();
850                true
851            },
852            _ => false,
853        }
854    }
855
856    pub(crate) fn dismiss_tooltips_for_webview(&mut self, webview_id: WebViewId) -> bool {
857        if self
858            .tooltip
859            .as_ref()
860            .is_some_and(|tooltip| tooltip.webview_id == webview_id)
861        {
862            self.tooltip = None;
863            return true;
864        }
865        false
866    }
867
868    fn update_can_go_back_and_forward(&mut self, window: &ServoShellWindow) -> bool {
869        let (can_go_back, can_go_forward) = window
870            .active_webview()
871            .map(|webview| (webview.can_go_back(), webview.can_go_forward()))
872            .unwrap_or((false, false));
873        let old_can_go_back = std::mem::replace(&mut self.can_go_back, can_go_back);
874        let old_can_go_forward = std::mem::replace(&mut self.can_go_forward, can_go_forward);
875        old_can_go_back != self.can_go_back || old_can_go_forward != self.can_go_forward
876    }
877
878    /// Updates all fields taken from the given [`ServoShellWindow`], such as the location field.
879    /// Returns true iff the egui needs an update.
880    pub(crate) fn update_webview_data(&mut self, window: &ServoShellWindow) -> bool {
881        // Note: We must use the "bitwise OR" (|) operator here instead of "logical OR" (||)
882        //       because logical OR would short-circuit if any of the functions return true.
883        //       We want to ensure that all functions are called. The "bitwise OR" operator
884        //       does not short-circuit.
885        self.update_load_status(window) |
886            self.update_location_in_toolbar(window) |
887            self.update_status_text(window) |
888            self.update_can_go_back_and_forward(window)
889    }
890
891    /// Returns true if a redraw is required after handling the provided event.
892    pub(crate) fn handle_accesskit_event(
893        &mut self,
894        event: &egui_winit::accesskit_winit::WindowEvent,
895    ) -> bool {
896        match event {
897            egui_winit::accesskit_winit::WindowEvent::InitialTreeRequested => {
898                self.context.egui_ctx.enable_accesskit();
899                true
900            },
901            egui_winit::accesskit_winit::WindowEvent::ActionRequested(req) => {
902                self.context
903                    .egui_winit
904                    .on_accesskit_action_request(req.clone());
905                true
906            },
907            egui_winit::accesskit_winit::WindowEvent::AccessibilityDeactivated => {
908                self.context.egui_ctx.disable_accesskit();
909                false
910            },
911        }
912    }
913
914    pub(crate) fn set_zoom_factor(&self, factor: f32) {
915        self.context.egui_ctx.set_zoom_factor(factor);
916    }
917
918    pub(crate) fn notify_accessibility_tree_update(&mut self, tree_update: accesskit::TreeUpdate) {
919        self.pending_accesskit_updates.push(tree_update);
920    }
921}
922
923fn embedder_image_to_egui_image(image: &Image) -> egui::ColorImage {
924    let width = image.width as usize;
925    let height = image.height as usize;
926
927    match image.format {
928        PixelFormat::K8 => egui::ColorImage::from_gray([width, height], image.data()),
929        PixelFormat::KA8 => {
930            // Convert to rgba
931            let (chunks, _) = image.data().as_chunks::<2>();
932            let data: Vec<u8> = chunks
933                .iter()
934                .flat_map(|pixel| [pixel[0], pixel[0], pixel[0], pixel[1]])
935                .collect();
936            egui::ColorImage::from_rgba_unmultiplied([width, height], &data)
937        },
938        PixelFormat::RGB8 => egui::ColorImage::from_rgb([width, height], image.data()),
939        PixelFormat::RGBA8 => {
940            egui::ColorImage::from_rgba_unmultiplied([width, height], image.data())
941        },
942        PixelFormat::BGRA8 => {
943            // Convert from BGRA to RGBA
944            let (chunks, _) = image.data().as_chunks::<4>();
945            let data: Vec<u8> = chunks
946                .iter()
947                .flat_map(|chunk| [chunk[2], chunk[1], chunk[0], chunk[3]])
948                .collect();
949            egui::ColorImage::from_rgba_unmultiplied([width, height], &data)
950        },
951    }
952}
953
954/// Uploads all favicons that have not yet been processed to the GPU.
955fn load_pending_favicons(
956    ctx: &egui::Context,
957    window: &ServoShellWindow,
958    texture_cache: &mut HashMap<WebViewId, (egui::TextureHandle, egui::load::SizedTexture)>,
959) {
960    for id in window.take_pending_favicon_loads() {
961        let Some(webview) = window.webview_by_id(id) else {
962            continue;
963        };
964        let Some(favicon) = webview.favicon() else {
965            texture_cache.remove(&id);
966            continue;
967        };
968
969        let egui_image = embedder_image_to_egui_image(&favicon);
970        let handle = ctx.load_texture(format!("favicon-{id:?}"), egui_image, Default::default());
971        let texture = egui::load::SizedTexture::new(
972            handle.id(),
973            egui::vec2(favicon.width as f32, favicon.height as f32),
974        );
975
976        // We don't need the handle anymore but we can't drop it either since that would cause
977        // the texture to be freed.
978        texture_cache.insert(id, (handle, texture));
979    }
980}