1use std::cell::{Cell, RefCell};
6use std::collections::{HashMap, VecDeque};
7use std::rc::Rc;
8
9use embedder_traits::user_contents::UserContentManagerId;
10use embedder_traits::{InputEvent, MouseLeftViewportEvent, Theme, ViewportDetails};
11use euclid::Size2D;
12use log::{debug, warn};
13use paint_api::{PaintMessage, PaintProxy};
14use rustc_hash::{FxHashMap, FxHashSet};
15use script_traits::{ConstellationInputEvent, ScriptThreadMessage, WebViewState};
16use servo_base::Epoch;
17use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
18use servo_constellation_traits::{ScreenshotReadinessResponse, SessionHistoryTraversalRequest};
19
20use crate::browsingcontext::{BrowsingContext, FullyActiveBrowsingContextsIterator};
21use crate::constellation::BrowsingContextGroup;
22use crate::pipeline::Pipeline;
23use crate::screenshot_readiness_request::{ScreenshotReadinessRequest, ScreenshotRequestState};
24use crate::session_history::{JointSessionHistory, SessionHistoryChange};
25
26pub(crate) struct ConstellationWebView {
29 webview_id: WebViewId,
31
32 pub active_top_level_pipeline_id: Option<PipelineId>,
34
35 pub active_top_level_pipeline_epoch: Epoch,
37
38 pub pending_changes: Vec<SessionHistoryChange>,
44
45 browsing_context_group: Rc<RefCell<BrowsingContextGroup>>,
49
50 pub focused_browsing_context_id: BrowsingContextId,
54
55 pub hovered_browsing_context_id: Option<BrowsingContextId>,
58
59 pub session_history: JointSessionHistory,
61
62 pub session_history_traversal_request_queue: VecDeque<SessionHistoryTraversalRequest>,
67
68 pub ongoing_history_traversal_request: Option<OngoingHistoryTraversalRequest>,
71
72 pending_viewport_details: HashMap<BrowsingContextId, ViewportDetails>,
75
76 pub user_content_manager_id: Option<UserContentManagerId>,
80
81 theme: Theme,
84
85 hidden: bool,
88
89 has_system_focus: bool,
93
94 pub accessibility_active: bool,
101
102 screenshot_readiness_requests: Vec<ScreenshotReadinessRequest>,
106}
107
108impl ConstellationWebView {
109 pub(crate) fn new(
110 webview_id: WebViewId,
111 browsing_context_group: Rc<RefCell<BrowsingContextGroup>>,
112 focused_browsing_context_id: BrowsingContextId,
113 user_content_manager_id: Option<UserContentManagerId>,
114 ) -> Self {
115 Self {
116 webview_id,
117 user_content_manager_id,
118 active_top_level_pipeline_id: None,
119 active_top_level_pipeline_epoch: Epoch::default(),
120 pending_changes: Default::default(),
121 browsing_context_group,
122 focused_browsing_context_id,
123 hovered_browsing_context_id: None,
124 session_history: JointSessionHistory::new(),
125 session_history_traversal_request_queue: Default::default(),
126 ongoing_history_traversal_request: None,
127 pending_viewport_details: Default::default(),
128 theme: Theme::Light,
129 hidden: false,
130 has_system_focus: true,
131 accessibility_active: false,
132 screenshot_readiness_requests: Default::default(),
133 }
134 }
135
136 pub(crate) fn browsing_context_group(&self) -> Rc<RefCell<BrowsingContextGroup>> {
137 self.browsing_context_group.clone()
138 }
139
140 pub(crate) fn set_theme(&mut self, new_theme: Theme) -> bool {
142 let old_theme = std::mem::replace(&mut self.theme, new_theme);
143 old_theme != self.theme
144 }
145
146 pub(crate) fn theme(&self) -> Theme {
148 self.theme
149 }
150
151 pub(crate) fn hidden(&self) -> bool {
153 self.hidden
154 }
155
156 pub(crate) fn state(&self) -> WebViewState {
159 WebViewState {
160 id: self.webview_id,
161 theme: Cell::new(self.theme),
162 has_system_focus: Cell::new(self.has_system_focus),
163 }
164 }
165
166 pub(crate) fn set_hidden(&mut self, hidden: bool) -> bool {
169 let old_hidden = std::mem::replace(&mut self.hidden, hidden);
170 old_hidden != self.hidden
171 }
172
173 pub(crate) fn set_has_system_focus(&mut self, has_system_focus: bool) -> bool {
176 let old_has_system_focus = std::mem::replace(&mut self.has_system_focus, has_system_focus);
177 old_has_system_focus != self.has_system_focus
178 }
179
180 fn target_pipeline_id_for_input_event(
181 &self,
182 event: &ConstellationInputEvent,
183 browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
184 ) -> Option<PipelineId> {
185 if let Some(hit_test_result) = &event.hit_test_result {
186 return Some(hit_test_result.pipeline_id);
187 }
188
189 let browsing_context_id = if matches!(event.event.event, InputEvent::MouseLeftViewport(_)) {
192 self.hovered_browsing_context_id
193 .unwrap_or(self.focused_browsing_context_id)
194 } else {
195 self.focused_browsing_context_id
196 };
197
198 Some(browsing_contexts.get(&browsing_context_id)?.pipeline_id)
199 }
200
201 pub(crate) fn forward_input_event(
204 &mut self,
205 event: ConstellationInputEvent,
206 pipelines: &FxHashMap<PipelineId, Pipeline>,
207 browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
208 ) -> bool {
209 let Some(pipeline_id) = self.target_pipeline_id_for_input_event(&event, browsing_contexts)
210 else {
211 warn!("Unknown pipeline for input event. Ignoring.");
212 return false;
213 };
214 let Some(pipeline) = pipelines.get(&pipeline_id) else {
215 warn!("Unknown pipeline id {pipeline_id:?} for input event. Ignoring.");
216 return false;
217 };
218
219 let mut update_hovered_browsing_context =
220 |newly_hovered_browsing_context_id, focus_moving_to_another_iframe: bool| {
221 let old_hovered_context_id = std::mem::replace(
222 &mut self.hovered_browsing_context_id,
223 newly_hovered_browsing_context_id,
224 );
225 if old_hovered_context_id == newly_hovered_browsing_context_id {
226 return;
227 }
228 let Some(old_hovered_context_id) = old_hovered_context_id else {
229 return;
230 };
231 let Some(pipeline) = browsing_contexts
232 .get(&old_hovered_context_id)
233 .and_then(|browsing_context| pipelines.get(&browsing_context.pipeline_id))
234 else {
235 return;
236 };
237
238 let mut synthetic_mouse_leave_event = event.clone();
239 synthetic_mouse_leave_event.event.event =
240 InputEvent::MouseLeftViewport(MouseLeftViewportEvent {
241 focus_moving_to_another_iframe,
242 });
243
244 let _ = pipeline
245 .event_loop
246 .send(ScriptThreadMessage::SendInputEvent(
247 self.webview_id,
248 pipeline.id,
249 synthetic_mouse_leave_event,
250 ));
251 };
252
253 if let InputEvent::MouseLeftViewport(_) = &event.event.event {
254 update_hovered_browsing_context(None, false);
255 return true;
256 }
257
258 if let InputEvent::MouseMove(_) = &event.event.event {
259 update_hovered_browsing_context(Some(pipeline.browsing_context_id), true);
260 }
261
262 let _ = pipeline
263 .event_loop
264 .send(ScriptThreadMessage::SendInputEvent(
265 self.webview_id,
266 pipeline.id,
267 event,
268 ));
269 true
270 }
271
272 pub(crate) fn close_browsing_context(&mut self, browsing_context_id: BrowsingContextId) {
273 self.take_pending_viewport_details(&browsing_context_id);
274 self.session_history
275 .remove_entries_for_browsing_context(browsing_context_id);
276 }
277
278 pub(crate) fn maybe_finish_ongoing_session_history_traversal_request(
282 &mut self,
283 ) -> Option<SessionHistoryTraversalRequest> {
284 let ongoing_history_traversal_request = self.ongoing_history_traversal_request.as_mut()?;
285
286 let pipelines_with_pending_changes = self
287 .pending_changes
288 .iter()
289 .map(|change| change.new_pipeline_id)
290 .collect::<FxHashSet<_>>();
291 ongoing_history_traversal_request
292 .pipelines_awaiting_activation
293 .retain(|pipeline_id| pipelines_with_pending_changes.contains(pipeline_id));
294
295 if !ongoing_history_traversal_request
296 .pipelines_awaiting_activation
297 .is_empty()
298 {
299 return None;
300 }
301 Some(
302 self.ongoing_history_traversal_request
303 .take()
304 .expect("Guaranteed above")
305 .traversal_request,
306 )
307 }
308
309 pub(crate) fn has_pending_change(&self) -> bool {
310 !self.pending_changes.is_empty()
311 }
312
313 pub(crate) fn is_navigating(&self, top_level_pipeline: Option<&Pipeline>) -> bool {
318 let top_level_browsing_context_id = BrowsingContextId::from(self.webview_id);
319 !self.session_history_traversal_request_queue.is_empty() ||
320 self.ongoing_history_traversal_request.is_some() ||
321 top_level_pipeline.is_some_and(|pipeline| !pipeline.load_finished) ||
322 self.pending_changes
323 .iter()
324 .any(|change| change.browsing_context_id == top_level_browsing_context_id)
325 }
326
327 pub(crate) fn pipeline_is_pending(&self, pipeline_id: PipelineId) -> bool {
328 self.pending_changes
329 .iter()
330 .any(|pending_change| pending_change.new_pipeline_id == pipeline_id)
331 }
332
333 pub(crate) fn add_pending_change(&mut self, change: SessionHistoryChange) {
334 debug!(
335 "adding pending session history change with {}",
336 if change.replace.is_some() {
337 "replacement"
338 } else {
339 "no replacement"
340 },
341 );
342 self.pending_changes.push(change);
343 }
344
345 pub(crate) fn remove_pending_change_for_pipeline(
346 &mut self,
347 pipeline_id: PipelineId,
348 ) -> Option<SessionHistoryChange> {
349 let pending_index = self
350 .pending_changes
351 .iter()
352 .rposition(|change| change.new_pipeline_id == pipeline_id)?;
353 Some(self.pending_changes.swap_remove(pending_index))
354 }
355
356 pub(crate) fn remove_pending_changes_for_browsing_context_id(
357 &mut self,
358 browsing_context_id: BrowsingContextId,
359 ) -> Vec<SessionHistoryChange> {
360 self.pending_changes
361 .extract_if(.., |change| {
362 change.browsing_context_id == browsing_context_id
363 })
364 .collect()
365 }
366
367 #[servo_tracing::instrument(skip_all)]
368 pub(crate) fn handle_screenshot_readiness_request(
369 &mut self,
370 browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
371 pipelines: &FxHashMap<PipelineId, Pipeline>,
372 ) {
373 self.screenshot_readiness_requests
374 .push(ScreenshotReadinessRequest {
375 pipeline_states: Default::default(),
376 state: Default::default(),
377 });
378 self.send_screenshot_readiness_requests_to_pipelines(browsing_contexts, pipelines);
379 }
380
381 pub(crate) fn send_screenshot_readiness_requests_to_pipelines(
382 &mut self,
383 browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
384 pipelines: &FxHashMap<PipelineId, Pipeline>,
385 ) {
386 if self.has_pending_change() {
388 return;
389 }
390
391 for screenshot_request in self.screenshot_readiness_requests.iter_mut() {
392 if screenshot_request.state != ScreenshotRequestState::Pending {
394 continue;
395 }
396
397 screenshot_request.pipeline_states = FullyActiveBrowsingContextsIterator::new(
398 self.webview_id.into(),
399 browsing_contexts,
400 pipelines,
401 )
402 .filter_map(|browsing_context| {
403 let pipeline_id = browsing_context.pipeline_id;
404 let Some(pipeline) = pipelines.get(&pipeline_id) else {
405 return None;
407 };
408 if browsing_context.viewport_details.size == Size2D::zero() {
412 return None;
413 }
414 let _ = pipeline
415 .event_loop
416 .send(ScriptThreadMessage::RequestScreenshotReadiness(
417 pipeline.webview_id,
418 pipeline_id,
419 ));
420 Some((pipeline_id, None))
421 })
422 .collect();
423 screenshot_request.state = ScreenshotRequestState::WaitingOnScript;
424 }
425 }
426
427 #[servo_tracing::instrument(skip_all)]
428 pub(crate) fn handle_screenshot_readiness_response(
429 &mut self,
430 updated_pipeline_id: PipelineId,
431 response: ScreenshotReadinessResponse,
432 paint_proxy: &PaintProxy,
433 ) {
434 if self.screenshot_readiness_requests.is_empty() {
435 return;
436 }
437
438 self.screenshot_readiness_requests
439 .retain_mut(|screenshot_request| {
440 if screenshot_request.state != ScreenshotRequestState::WaitingOnScript {
441 return true;
442 }
443
444 let mut has_pending_pipeline = false;
445 screenshot_request
446 .pipeline_states
447 .retain(|pipeline_id, state| {
448 if *pipeline_id != updated_pipeline_id {
449 has_pending_pipeline |= state.is_none();
450 return true;
451 }
452 match response {
453 ScreenshotReadinessResponse::Ready(epoch) => {
454 *state = Some(epoch);
455 true
456 },
457 ScreenshotReadinessResponse::NoLongerActive => false,
458 }
459 });
460
461 if has_pending_pipeline {
462 return true;
463 }
464
465 let pipelines_and_epochs = screenshot_request
466 .pipeline_states
467 .iter()
468 .map(|(pipeline_id, epoch)| {
469 (
470 *pipeline_id,
471 epoch.expect("Should have an epoch when pipeline is ready."),
472 )
473 })
474 .collect();
475 paint_proxy.send(PaintMessage::ScreenshotReadinessReponse(
476 self.webview_id,
477 pipelines_and_epochs,
478 ));
479
480 false
481 });
482 }
483
484 pub(crate) fn add_viewport_details(
485 &mut self,
486 browsing_context_id: BrowsingContextId,
487 viewport_details: ViewportDetails,
488 ) {
489 self.pending_viewport_details
490 .insert(browsing_context_id, viewport_details);
491 }
492
493 pub(crate) fn take_pending_viewport_details(
494 &mut self,
495 browsing_context_id: &BrowsingContextId,
496 ) -> Option<ViewportDetails> {
497 self.pending_viewport_details.remove(browsing_context_id)
498 }
499}
500
501pub(crate) struct OngoingHistoryTraversalRequest {
504 pub traversal_request: SessionHistoryTraversalRequest,
506 pub pipelines_awaiting_activation: FxHashSet<PipelineId>,
511}