[NFC] winit: document event handling and improve naming (#30016)

* compositing: rename WindowEvent to EmbedderEvent

* winit: rename winit_event_to_{servo → embedder}_event

* winit: rename ServoEvent::Awakened to WakerEvent

* winit: document App::handle_events and rename locals

* servo: rename Servo.embedder_events to messages_for_embedder

* winit: rustdoc link to EmbedderEvent

* winit: use new name queue_embedder_events_for_winit_event
This commit is contained in:
Delan Azabani 2023-07-24 13:30:18 +08:00 committed by GitHub
parent 605bf52334
commit dfeced5a8e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 228 additions and 202 deletions

View file

@ -35,9 +35,9 @@ pub enum WebRenderDebugOption {
RenderTargetDebug, RenderTargetDebug,
} }
/// Events that the windowing system sends to Servo. /// Events that the embedder sends to Servo, including events from the windowing system.
#[derive(Clone)] #[derive(Clone)]
pub enum WindowEvent { pub enum EmbedderEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps /// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem). /// by another Servo subsystem).
/// ///
@ -107,38 +107,38 @@ pub enum WindowEvent {
IMEDismissed, IMEDismissed,
} }
impl Debug for WindowEvent { impl Debug for EmbedderEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self { match *self {
WindowEvent::Idle => write!(f, "Idle"), EmbedderEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"), EmbedderEvent::Refresh => write!(f, "Refresh"),
WindowEvent::Resize => write!(f, "Resize"), EmbedderEvent::Resize => write!(f, "Resize"),
WindowEvent::Keyboard(..) => write!(f, "Keyboard"), EmbedderEvent::Keyboard(..) => write!(f, "Keyboard"),
WindowEvent::AllowNavigationResponse(..) => write!(f, "AllowNavigationResponse"), EmbedderEvent::AllowNavigationResponse(..) => write!(f, "AllowNavigationResponse"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"), EmbedderEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"), EmbedderEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"), EmbedderEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"), EmbedderEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Wheel(..) => write!(f, "Wheel"), EmbedderEvent::Wheel(..) => write!(f, "Wheel"),
WindowEvent::Scroll(..) => write!(f, "Scroll"), EmbedderEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"), EmbedderEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"), EmbedderEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"), EmbedderEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"), EmbedderEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"), EmbedderEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload(..) => write!(f, "Reload"), EmbedderEvent::Reload(..) => write!(f, "Reload"),
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"), EmbedderEvent::NewBrowser(..) => write!(f, "NewBrowser"),
WindowEvent::SendError(..) => write!(f, "SendError"), EmbedderEvent::SendError(..) => write!(f, "SendError"),
WindowEvent::CloseBrowser(..) => write!(f, "CloseBrowser"), EmbedderEvent::CloseBrowser(..) => write!(f, "CloseBrowser"),
WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"), EmbedderEvent::SelectBrowser(..) => write!(f, "SelectBrowser"),
WindowEvent::ToggleWebRenderDebug(..) => write!(f, "ToggleWebRenderDebug"), EmbedderEvent::ToggleWebRenderDebug(..) => write!(f, "ToggleWebRenderDebug"),
WindowEvent::CaptureWebRender => write!(f, "CaptureWebRender"), EmbedderEvent::CaptureWebRender => write!(f, "CaptureWebRender"),
WindowEvent::ToggleSamplingProfiler(..) => write!(f, "ToggleSamplingProfiler"), EmbedderEvent::ToggleSamplingProfiler(..) => write!(f, "ToggleSamplingProfiler"),
WindowEvent::ExitFullScreen(..) => write!(f, "ExitFullScreen"), EmbedderEvent::ExitFullScreen(..) => write!(f, "ExitFullScreen"),
WindowEvent::MediaSessionAction(..) => write!(f, "MediaSessionAction"), EmbedderEvent::MediaSessionAction(..) => write!(f, "MediaSessionAction"),
WindowEvent::ChangeBrowserVisibility(..) => write!(f, "ChangeBrowserVisibility"), EmbedderEvent::ChangeBrowserVisibility(..) => write!(f, "ChangeBrowserVisibility"),
WindowEvent::IMEDismissed => write!(f, "IMEDismissed"), EmbedderEvent::IMEDismissed => write!(f, "IMEDismissed"),
WindowEvent::ClearCache => write!(f, "ClearCache"), EmbedderEvent::ClearCache => write!(f, "ClearCache"),
} }
} }
} }

View file

@ -72,7 +72,7 @@ use compositing::compositor_thread::{
CompositorProxy, CompositorReceiver, InitialCompositorState, Msg, WebrenderCanvasMsg, CompositorProxy, CompositorReceiver, InitialCompositorState, Msg, WebrenderCanvasMsg,
WebrenderFontMsg, WebrenderMsg, WebrenderFontMsg, WebrenderMsg,
}; };
use compositing::windowing::{EmbedderMethods, WindowEvent, WindowMethods}; use compositing::windowing::{EmbedderEvent, EmbedderMethods, WindowMethods};
use compositing::{CompositingReason, ConstellationMsg, IOCompositor, ShutdownState}; use compositing::{CompositingReason, ConstellationMsg, IOCompositor, ShutdownState};
#[cfg(all( #[cfg(all(
not(target_os = "windows"), not(target_os = "windows"),
@ -194,7 +194,7 @@ pub struct Servo<Window: WindowMethods + 'static + ?Sized> {
compositor: IOCompositor<Window>, compositor: IOCompositor<Window>,
constellation_chan: Sender<ConstellationMsg>, constellation_chan: Sender<ConstellationMsg>,
embedder_receiver: EmbedderReceiver, embedder_receiver: EmbedderReceiver,
embedder_events: Vec<(Option<BrowserId>, EmbedderMsg)>, messages_for_embedder: Vec<(Option<BrowserId>, EmbedderMsg)>,
profiler_enabled: bool, profiler_enabled: bool,
/// For single-process Servo instances, this field controls the initialization /// For single-process Servo instances, this field controls the initialization
/// and deinitialization of the JS Engine. Multiprocess Servo instances have their /// and deinitialization of the JS Engine. Multiprocess Servo instances have their
@ -515,26 +515,26 @@ where
compositor: compositor, compositor: compositor,
constellation_chan: constellation_chan, constellation_chan: constellation_chan,
embedder_receiver: embedder_receiver, embedder_receiver: embedder_receiver,
embedder_events: Vec::new(), messages_for_embedder: Vec::new(),
profiler_enabled: false, profiler_enabled: false,
_js_engine_setup: js_engine_setup, _js_engine_setup: js_engine_setup,
}; };
InitializedServo { servo, browser_id } InitializedServo { servo, browser_id }
} }
fn handle_window_event(&mut self, event: WindowEvent) -> bool { fn handle_window_event(&mut self, event: EmbedderEvent) -> bool {
match event { match event {
WindowEvent::Idle => {}, EmbedderEvent::Idle => {},
WindowEvent::Refresh => { EmbedderEvent::Refresh => {
self.compositor.composite(); self.compositor.composite();
}, },
WindowEvent::Resize => { EmbedderEvent::Resize => {
return self.compositor.on_resize_window_event(); return self.compositor.on_resize_window_event();
}, },
WindowEvent::AllowNavigationResponse(pipeline_id, allowed) => { EmbedderEvent::AllowNavigationResponse(pipeline_id, allowed) => {
let msg = ConstellationMsg::AllowNavigationResponse(pipeline_id, allowed); let msg = ConstellationMsg::AllowNavigationResponse(pipeline_id, allowed);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -544,55 +544,55 @@ where
} }
}, },
WindowEvent::LoadUrl(top_level_browsing_context_id, url) => { EmbedderEvent::LoadUrl(top_level_browsing_context_id, url) => {
let msg = ConstellationMsg::LoadUrl(top_level_browsing_context_id, url); let msg = ConstellationMsg::LoadUrl(top_level_browsing_context_id, url);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending load url to constellation failed ({:?}).", e); warn!("Sending load url to constellation failed ({:?}).", e);
} }
}, },
WindowEvent::ClearCache => { EmbedderEvent::ClearCache => {
let msg = ConstellationMsg::ClearCache; let msg = ConstellationMsg::ClearCache;
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending clear cache to constellation failed ({:?}).", e); warn!("Sending clear cache to constellation failed ({:?}).", e);
} }
}, },
WindowEvent::MouseWindowEventClass(mouse_window_event) => { EmbedderEvent::MouseWindowEventClass(mouse_window_event) => {
self.compositor self.compositor
.on_mouse_window_event_class(mouse_window_event); .on_mouse_window_event_class(mouse_window_event);
}, },
WindowEvent::MouseWindowMoveEventClass(cursor) => { EmbedderEvent::MouseWindowMoveEventClass(cursor) => {
self.compositor.on_mouse_window_move_event_class(cursor); self.compositor.on_mouse_window_move_event_class(cursor);
}, },
WindowEvent::Touch(event_type, identifier, location) => { EmbedderEvent::Touch(event_type, identifier, location) => {
self.compositor self.compositor
.on_touch_event(event_type, identifier, location); .on_touch_event(event_type, identifier, location);
}, },
WindowEvent::Wheel(delta, location) => { EmbedderEvent::Wheel(delta, location) => {
self.compositor.on_wheel_event(delta, location); self.compositor.on_wheel_event(delta, location);
}, },
WindowEvent::Scroll(delta, cursor, phase) => { EmbedderEvent::Scroll(delta, cursor, phase) => {
self.compositor.on_scroll_event(delta, cursor, phase); self.compositor.on_scroll_event(delta, cursor, phase);
}, },
WindowEvent::Zoom(magnification) => { EmbedderEvent::Zoom(magnification) => {
self.compositor.on_zoom_window_event(magnification); self.compositor.on_zoom_window_event(magnification);
}, },
WindowEvent::ResetZoom => { EmbedderEvent::ResetZoom => {
self.compositor.on_zoom_reset_window_event(); self.compositor.on_zoom_reset_window_event();
}, },
WindowEvent::PinchZoom(magnification) => { EmbedderEvent::PinchZoom(magnification) => {
self.compositor.on_pinch_zoom_window_event(magnification); self.compositor.on_pinch_zoom_window_event(magnification);
}, },
WindowEvent::Navigation(top_level_browsing_context_id, direction) => { EmbedderEvent::Navigation(top_level_browsing_context_id, direction) => {
let msg = let msg =
ConstellationMsg::TraverseHistory(top_level_browsing_context_id, direction); ConstellationMsg::TraverseHistory(top_level_browsing_context_id, direction);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
@ -600,14 +600,14 @@ where
} }
}, },
WindowEvent::Keyboard(key_event) => { EmbedderEvent::Keyboard(key_event) => {
let msg = ConstellationMsg::Keyboard(key_event); let msg = ConstellationMsg::Keyboard(key_event);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending keyboard event to constellation failed ({:?}).", e); warn!("Sending keyboard event to constellation failed ({:?}).", e);
} }
}, },
WindowEvent::IMEDismissed => { EmbedderEvent::IMEDismissed => {
let msg = ConstellationMsg::IMEDismissed; let msg = ConstellationMsg::IMEDismissed;
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -617,25 +617,25 @@ where
} }
}, },
WindowEvent::Quit => { EmbedderEvent::Quit => {
self.compositor.maybe_start_shutting_down(); self.compositor.maybe_start_shutting_down();
}, },
WindowEvent::ExitFullScreen(top_level_browsing_context_id) => { EmbedderEvent::ExitFullScreen(top_level_browsing_context_id) => {
let msg = ConstellationMsg::ExitFullScreen(top_level_browsing_context_id); let msg = ConstellationMsg::ExitFullScreen(top_level_browsing_context_id);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending exit fullscreen to constellation failed ({:?}).", e); warn!("Sending exit fullscreen to constellation failed ({:?}).", e);
} }
}, },
WindowEvent::Reload(top_level_browsing_context_id) => { EmbedderEvent::Reload(top_level_browsing_context_id) => {
let msg = ConstellationMsg::Reload(top_level_browsing_context_id); let msg = ConstellationMsg::Reload(top_level_browsing_context_id);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!("Sending reload to constellation failed ({:?}).", e); warn!("Sending reload to constellation failed ({:?}).", e);
} }
}, },
WindowEvent::ToggleSamplingProfiler(rate, max_duration) => { EmbedderEvent::ToggleSamplingProfiler(rate, max_duration) => {
self.profiler_enabled = !self.profiler_enabled; self.profiler_enabled = !self.profiler_enabled;
let msg = if self.profiler_enabled { let msg = if self.profiler_enabled {
ConstellationMsg::EnableProfiler(rate, max_duration) ConstellationMsg::EnableProfiler(rate, max_duration)
@ -647,15 +647,15 @@ where
} }
}, },
WindowEvent::ToggleWebRenderDebug(option) => { EmbedderEvent::ToggleWebRenderDebug(option) => {
self.compositor.toggle_webrender_debug(option); self.compositor.toggle_webrender_debug(option);
}, },
WindowEvent::CaptureWebRender => { EmbedderEvent::CaptureWebRender => {
self.compositor.capture_webrender(); self.compositor.capture_webrender();
}, },
WindowEvent::NewBrowser(url, browser_id) => { EmbedderEvent::NewBrowser(url, browser_id) => {
let msg = ConstellationMsg::NewBrowser(url, browser_id); let msg = ConstellationMsg::NewBrowser(url, browser_id);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -665,7 +665,7 @@ where
} }
}, },
WindowEvent::SelectBrowser(ctx) => { EmbedderEvent::SelectBrowser(ctx) => {
let msg = ConstellationMsg::SelectBrowser(ctx); let msg = ConstellationMsg::SelectBrowser(ctx);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -675,7 +675,7 @@ where
} }
}, },
WindowEvent::CloseBrowser(ctx) => { EmbedderEvent::CloseBrowser(ctx) => {
let msg = ConstellationMsg::CloseBrowser(ctx); let msg = ConstellationMsg::CloseBrowser(ctx);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -685,7 +685,7 @@ where
} }
}, },
WindowEvent::SendError(ctx, e) => { EmbedderEvent::SendError(ctx, e) => {
let msg = ConstellationMsg::SendError(ctx, e); let msg = ConstellationMsg::SendError(ctx, e);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -695,7 +695,7 @@ where
} }
}, },
WindowEvent::MediaSessionAction(a) => { EmbedderEvent::MediaSessionAction(a) => {
let msg = ConstellationMsg::MediaSessionAction(a); let msg = ConstellationMsg::MediaSessionAction(a);
if let Err(e) = self.constellation_chan.send(msg) { if let Err(e) = self.constellation_chan.send(msg) {
warn!( warn!(
@ -705,7 +705,7 @@ where
} }
}, },
WindowEvent::ChangeBrowserVisibility(top_level_browsing_context_id, visible) => { EmbedderEvent::ChangeBrowserVisibility(top_level_browsing_context_id, visible) => {
let msg = ConstellationMsg::ChangeBrowserVisibility( let msg = ConstellationMsg::ChangeBrowserVisibility(
top_level_browsing_context_id, top_level_browsing_context_id,
visible, visible,
@ -736,21 +736,22 @@ where
(EmbedderMsg::Keyboard(key_event), ShutdownState::NotShuttingDown) => { (EmbedderMsg::Keyboard(key_event), ShutdownState::NotShuttingDown) => {
let event = (top_level_browsing_context, EmbedderMsg::Keyboard(key_event)); let event = (top_level_browsing_context, EmbedderMsg::Keyboard(key_event));
self.embedder_events.push(event); self.messages_for_embedder.push(event);
}, },
(msg, ShutdownState::NotShuttingDown) => { (msg, ShutdownState::NotShuttingDown) => {
self.embedder_events.push((top_level_browsing_context, msg)); self.messages_for_embedder
.push((top_level_browsing_context, msg));
}, },
} }
} }
} }
pub fn get_events(&mut self) -> Vec<(Option<BrowserId>, EmbedderMsg)> { pub fn get_events(&mut self) -> Vec<(Option<BrowserId>, EmbedderMsg)> {
::std::mem::replace(&mut self.embedder_events, Vec::new()) ::std::mem::replace(&mut self.messages_for_embedder, Vec::new())
} }
pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool { pub fn handle_events(&mut self, events: Vec<EmbedderEvent>) -> bool {
if self.compositor.receive_messages() { if self.compositor.receive_messages() {
self.receive_messages(); self.receive_messages();
} }
@ -761,7 +762,8 @@ where
if self.compositor.shutdown_state != ShutdownState::FinishedShuttingDown { if self.compositor.shutdown_state != ShutdownState::FinishedShuttingDown {
self.compositor.perform_updates(); self.compositor.perform_updates();
} else { } else {
self.embedder_events.push((None, EmbedderMsg::Shutdown)); self.messages_for_embedder
.push((None, EmbedderMsg::Shutdown));
} }
need_resize need_resize
} }

View file

@ -69,8 +69,8 @@ use log::warn;
use servo::compositing::windowing::AnimationState; use servo::compositing::windowing::AnimationState;
use servo::compositing::windowing::EmbedderCoordinates; use servo::compositing::windowing::EmbedderCoordinates;
use servo::compositing::windowing::EmbedderEvent;
use servo::compositing::windowing::EmbedderMethods; use servo::compositing::windowing::EmbedderMethods;
use servo::compositing::windowing::WindowEvent;
use servo::compositing::windowing::WindowMethods; use servo::compositing::windowing::WindowMethods;
use servo::embedder_traits::EmbedderProxy; use servo::embedder_traits::EmbedderProxy;
use servo::embedder_traits::EventLoopWaker; use servo::embedder_traits::EventLoopWaker;
@ -221,14 +221,14 @@ impl ServoThread {
let id = servo.top_level_browsing_context_id; let id = servo.top_level_browsing_context_id;
let mut servo = servo.servo; let mut servo = servo.servo;
servo.handle_events(vec![WindowEvent::NewBrowser(url, id)]); servo.handle_events(vec![EmbedderEvent::NewBrowser(url, id)]);
let swap_chain = match webxr_mode { let swap_chain = match webxr_mode {
None => Some(webrender_swap_chain), None => Some(webrender_swap_chain),
Some(..) => { Some(..) => {
set_pref!(dom.webxr.sessionavailable, true); set_pref!(dom.webxr.sessionavailable, true);
set_pref!(dom.webxr.unsafe_assume_user_intent, true); set_pref!(dom.webxr.unsafe_assume_user_intent, true);
servo.handle_events(vec![WindowEvent::ChangeBrowserVisibility(id, false)]); servo.handle_events(vec![EmbedderEvent::ChangeBrowserVisibility(id, false)]);
None None
}, },
}; };
@ -256,7 +256,7 @@ impl ServoThread {
ServoWebSrcMsg::Stop => break, ServoWebSrcMsg::Stop => break,
} }
} }
self.servo.handle_events(vec![WindowEvent::Quit]); self.servo.handle_events(vec![EmbedderEvent::Quit]);
} }
fn send_swap_chain(&mut self, sender: Sender<SwapChain<Device>>) { fn send_swap_chain(&mut self, sender: Sender<SwapChain<Device>>) {
@ -273,7 +273,7 @@ impl ServoThread {
.window() .window()
.webrender_surfman .webrender_surfman
.resize(size.to_untyped()); .resize(size.to_untyped());
self.servo.handle_events(vec![WindowEvent::Resize]); self.servo.handle_events(vec![EmbedderEvent::Resize]);
} }
} }

View file

@ -18,7 +18,7 @@ pub use servo::webrender_api::units::DeviceIntRect;
use getopts::Options; use getopts::Options;
use ipc_channel::ipc::IpcSender; use ipc_channel::ipc::IpcSender;
use servo::compositing::windowing::{ use servo::compositing::windowing::{
AnimationState, EmbedderCoordinates, EmbedderMethods, MouseWindowEvent, WindowEvent, AnimationState, EmbedderCoordinates, EmbedderEvent, EmbedderMethods, MouseWindowEvent,
WindowMethods, WindowMethods,
}; };
use servo::config::prefs::pref_map; use servo::config::prefs::pref_map;
@ -179,7 +179,7 @@ pub struct ServoGlue {
// EmbedderMsg::CloseBrowser will pop from it, // EmbedderMsg::CloseBrowser will pop from it,
// and exit if it is empty afterwards. // and exit if it is empty afterwards.
browsers: Vec<BrowserId>, browsers: Vec<BrowserId>,
events: Vec<WindowEvent>, events: Vec<EmbedderEvent>,
context_menu_sender: Option<IpcSender<ContextMenuResult>>, context_menu_sender: Option<IpcSender<ContextMenuResult>>,
} }
@ -316,7 +316,7 @@ pub fn init(
events: vec![], events: vec![],
context_menu_sender: None, context_menu_sender: None,
}; };
let _ = servo_glue.process_event(WindowEvent::NewBrowser(url, servo.browser_id)); let _ = servo_glue.process_event(EmbedderEvent::NewBrowser(url, servo.browser_id));
*s.borrow_mut() = Some(servo_glue); *s.borrow_mut() = Some(servo_glue);
}); });
@ -338,7 +338,7 @@ impl ServoGlue {
/// Request shutdown. Will call on_shutdown_complete. /// Request shutdown. Will call on_shutdown_complete.
pub fn request_shutdown(&mut self) -> Result<(), &'static str> { pub fn request_shutdown(&mut self) -> Result<(), &'static str> {
self.process_event(WindowEvent::Quit) self.process_event(EmbedderEvent::Quit)
} }
/// Call after on_shutdown_complete /// Call after on_shutdown_complete
@ -382,7 +382,7 @@ impl ServoGlue {
.map_err(|_| "Can't parse URL") .map_err(|_| "Can't parse URL")
.and_then(|url| { .and_then(|url| {
let browser_id = self.get_browser_id()?; let browser_id = self.get_browser_id()?;
let event = WindowEvent::LoadUrl(browser_id, url); let event = EmbedderEvent::LoadUrl(browser_id, url);
self.process_event(event) self.process_event(event)
}) })
} }
@ -390,7 +390,7 @@ impl ServoGlue {
/// Reload the page. /// Reload the page.
pub fn clear_cache(&mut self) -> Result<(), &'static str> { pub fn clear_cache(&mut self) -> Result<(), &'static str> {
info!("clear_cache"); info!("clear_cache");
let event = WindowEvent::ClearCache; let event = EmbedderEvent::ClearCache;
self.process_event(event) self.process_event(event)
} }
@ -398,14 +398,14 @@ impl ServoGlue {
pub fn reload(&mut self) -> Result<(), &'static str> { pub fn reload(&mut self) -> Result<(), &'static str> {
info!("reload"); info!("reload");
let browser_id = self.get_browser_id()?; let browser_id = self.get_browser_id()?;
let event = WindowEvent::Reload(browser_id); let event = EmbedderEvent::Reload(browser_id);
self.process_event(event) self.process_event(event)
} }
/// Redraw the page. /// Redraw the page.
pub fn refresh(&mut self) -> Result<(), &'static str> { pub fn refresh(&mut self) -> Result<(), &'static str> {
info!("refresh"); info!("refresh");
self.process_event(WindowEvent::Refresh) self.process_event(EmbedderEvent::Refresh)
} }
/// Stop loading the page. /// Stop loading the page.
@ -418,7 +418,7 @@ impl ServoGlue {
pub fn go_back(&mut self) -> Result<(), &'static str> { pub fn go_back(&mut self) -> Result<(), &'static str> {
info!("go_back"); info!("go_back");
let browser_id = self.get_browser_id()?; let browser_id = self.get_browser_id()?;
let event = WindowEvent::Navigation(browser_id, TraversalDirection::Back(1)); let event = EmbedderEvent::Navigation(browser_id, TraversalDirection::Back(1));
self.process_event(event) self.process_event(event)
} }
@ -426,7 +426,7 @@ impl ServoGlue {
pub fn go_forward(&mut self) -> Result<(), &'static str> { pub fn go_forward(&mut self) -> Result<(), &'static str> {
info!("go_forward"); info!("go_forward");
let browser_id = self.get_browser_id()?; let browser_id = self.get_browser_id()?;
let event = WindowEvent::Navigation(browser_id, TraversalDirection::Forward(1)); let event = EmbedderEvent::Navigation(browser_id, TraversalDirection::Forward(1));
self.process_event(event) self.process_event(event)
} }
@ -434,7 +434,7 @@ impl ServoGlue {
pub fn resize(&mut self, coordinates: Coordinates) -> Result<(), &'static str> { pub fn resize(&mut self, coordinates: Coordinates) -> Result<(), &'static str> {
info!("resize"); info!("resize");
*self.callbacks.coordinates.borrow_mut() = coordinates; *self.callbacks.coordinates.borrow_mut() = coordinates;
self.process_event(WindowEvent::Resize) self.process_event(EmbedderEvent::Resize)
} }
/// Start scrolling. /// Start scrolling.
@ -443,7 +443,8 @@ impl ServoGlue {
pub fn scroll_start(&mut self, dx: f32, dy: f32, x: i32, y: i32) -> Result<(), &'static str> { pub fn scroll_start(&mut self, dx: f32, dy: f32, x: i32, y: i32) -> Result<(), &'static str> {
let delta = Vector2D::new(dx, dy); let delta = Vector2D::new(dx, dy);
let scroll_location = ScrollLocation::Delta(delta); let scroll_location = ScrollLocation::Delta(delta);
let event = WindowEvent::Scroll(scroll_location, Point2D::new(x, y), TouchEventType::Down); let event =
EmbedderEvent::Scroll(scroll_location, Point2D::new(x, y), TouchEventType::Down);
self.process_event(event) self.process_event(event)
} }
@ -453,7 +454,8 @@ impl ServoGlue {
pub fn scroll(&mut self, dx: f32, dy: f32, x: i32, y: i32) -> Result<(), &'static str> { pub fn scroll(&mut self, dx: f32, dy: f32, x: i32, y: i32) -> Result<(), &'static str> {
let delta = Vector2D::new(dx, dy); let delta = Vector2D::new(dx, dy);
let scroll_location = ScrollLocation::Delta(delta); let scroll_location = ScrollLocation::Delta(delta);
let event = WindowEvent::Scroll(scroll_location, Point2D::new(x, y), TouchEventType::Move); let event =
EmbedderEvent::Scroll(scroll_location, Point2D::new(x, y), TouchEventType::Move);
self.process_event(event) self.process_event(event)
} }
@ -463,13 +465,13 @@ impl ServoGlue {
pub fn scroll_end(&mut self, dx: f32, dy: f32, x: i32, y: i32) -> Result<(), &'static str> { pub fn scroll_end(&mut self, dx: f32, dy: f32, x: i32, y: i32) -> Result<(), &'static str> {
let delta = Vector2D::new(dx, dy); let delta = Vector2D::new(dx, dy);
let scroll_location = ScrollLocation::Delta(delta); let scroll_location = ScrollLocation::Delta(delta);
let event = WindowEvent::Scroll(scroll_location, Point2D::new(x, y), TouchEventType::Up); let event = EmbedderEvent::Scroll(scroll_location, Point2D::new(x, y), TouchEventType::Up);
self.process_event(event) self.process_event(event)
} }
/// Touch event: press down /// Touch event: press down
pub fn touch_down(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> { pub fn touch_down(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> {
let event = WindowEvent::Touch( let event = EmbedderEvent::Touch(
TouchEventType::Down, TouchEventType::Down,
TouchId(pointer_id), TouchId(pointer_id),
Point2D::new(x as f32, y as f32), Point2D::new(x as f32, y as f32),
@ -479,7 +481,7 @@ impl ServoGlue {
/// Touch event: move touching finger /// Touch event: move touching finger
pub fn touch_move(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> { pub fn touch_move(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> {
let event = WindowEvent::Touch( let event = EmbedderEvent::Touch(
TouchEventType::Move, TouchEventType::Move,
TouchId(pointer_id), TouchId(pointer_id),
Point2D::new(x as f32, y as f32), Point2D::new(x as f32, y as f32),
@ -489,7 +491,7 @@ impl ServoGlue {
/// Touch event: Lift touching finger /// Touch event: Lift touching finger
pub fn touch_up(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> { pub fn touch_up(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> {
let event = WindowEvent::Touch( let event = EmbedderEvent::Touch(
TouchEventType::Up, TouchEventType::Up,
TouchId(pointer_id), TouchId(pointer_id),
Point2D::new(x as f32, y as f32), Point2D::new(x as f32, y as f32),
@ -499,7 +501,7 @@ impl ServoGlue {
/// Cancel touch event /// Cancel touch event
pub fn touch_cancel(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> { pub fn touch_cancel(&mut self, x: f32, y: f32, pointer_id: i32) -> Result<(), &'static str> {
let event = WindowEvent::Touch( let event = EmbedderEvent::Touch(
TouchEventType::Cancel, TouchEventType::Cancel,
TouchId(pointer_id), TouchId(pointer_id),
Point2D::new(x as f32, y as f32), Point2D::new(x as f32, y as f32),
@ -510,46 +512,47 @@ impl ServoGlue {
/// Register a mouse movement. /// Register a mouse movement.
pub fn mouse_move(&mut self, x: f32, y: f32) -> Result<(), &'static str> { pub fn mouse_move(&mut self, x: f32, y: f32) -> Result<(), &'static str> {
let point = Point2D::new(x, y); let point = Point2D::new(x, y);
let event = WindowEvent::MouseWindowMoveEventClass(point); let event = EmbedderEvent::MouseWindowMoveEventClass(point);
self.process_event(event) self.process_event(event)
} }
/// Register a mouse button press. /// Register a mouse button press.
pub fn mouse_down(&mut self, x: f32, y: f32, button: MouseButton) -> Result<(), &'static str> { pub fn mouse_down(&mut self, x: f32, y: f32, button: MouseButton) -> Result<(), &'static str> {
let point = Point2D::new(x, y); let point = Point2D::new(x, y);
let event = WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseDown(button, point)); let event =
EmbedderEvent::MouseWindowEventClass(MouseWindowEvent::MouseDown(button, point));
self.process_event(event) self.process_event(event)
} }
/// Register a mouse button release. /// Register a mouse button release.
pub fn mouse_up(&mut self, x: f32, y: f32, button: MouseButton) -> Result<(), &'static str> { pub fn mouse_up(&mut self, x: f32, y: f32, button: MouseButton) -> Result<(), &'static str> {
let point = Point2D::new(x, y); let point = Point2D::new(x, y);
let event = WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(button, point)); let event = EmbedderEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(button, point));
self.process_event(event) self.process_event(event)
} }
/// Start pinchzoom. /// Start pinchzoom.
/// x/y are pinch origin coordinates. /// x/y are pinch origin coordinates.
pub fn pinchzoom_start(&mut self, factor: f32, _x: u32, _y: u32) -> Result<(), &'static str> { pub fn pinchzoom_start(&mut self, factor: f32, _x: u32, _y: u32) -> Result<(), &'static str> {
self.process_event(WindowEvent::PinchZoom(factor)) self.process_event(EmbedderEvent::PinchZoom(factor))
} }
/// Pinchzoom. /// Pinchzoom.
/// x/y are pinch origin coordinates. /// x/y are pinch origin coordinates.
pub fn pinchzoom(&mut self, factor: f32, _x: u32, _y: u32) -> Result<(), &'static str> { pub fn pinchzoom(&mut self, factor: f32, _x: u32, _y: u32) -> Result<(), &'static str> {
self.process_event(WindowEvent::PinchZoom(factor)) self.process_event(EmbedderEvent::PinchZoom(factor))
} }
/// End pinchzoom. /// End pinchzoom.
/// x/y are pinch origin coordinates. /// x/y are pinch origin coordinates.
pub fn pinchzoom_end(&mut self, factor: f32, _x: u32, _y: u32) -> Result<(), &'static str> { pub fn pinchzoom_end(&mut self, factor: f32, _x: u32, _y: u32) -> Result<(), &'static str> {
self.process_event(WindowEvent::PinchZoom(factor)) self.process_event(EmbedderEvent::PinchZoom(factor))
} }
/// Perform a click. /// Perform a click.
pub fn click(&mut self, x: f32, y: f32) -> Result<(), &'static str> { pub fn click(&mut self, x: f32, y: f32) -> Result<(), &'static str> {
let mouse_event = MouseWindowEvent::Click(MouseButton::Left, Point2D::new(x, y)); let mouse_event = MouseWindowEvent::Click(MouseButton::Left, Point2D::new(x, y));
let event = WindowEvent::MouseWindowEventClass(mouse_event); let event = EmbedderEvent::MouseWindowEventClass(mouse_event);
self.process_event(event) self.process_event(event)
} }
@ -559,7 +562,7 @@ impl ServoGlue {
key, key,
..KeyboardEvent::default() ..KeyboardEvent::default()
}; };
self.process_event(WindowEvent::Keyboard(key_event)) self.process_event(EmbedderEvent::Keyboard(key_event))
} }
pub fn key_up(&mut self, key: Key) -> Result<(), &'static str> { pub fn key_up(&mut self, key: Key) -> Result<(), &'static str> {
@ -568,7 +571,7 @@ impl ServoGlue {
key, key,
..KeyboardEvent::default() ..KeyboardEvent::default()
}; };
self.process_event(WindowEvent::Keyboard(key_event)) self.process_event(EmbedderEvent::Keyboard(key_event))
} }
pub fn media_session_action( pub fn media_session_action(
@ -576,13 +579,13 @@ impl ServoGlue {
action: MediaSessionActionType, action: MediaSessionActionType,
) -> Result<(), &'static str> { ) -> Result<(), &'static str> {
info!("Media session action {:?}", action); info!("Media session action {:?}", action);
self.process_event(WindowEvent::MediaSessionAction(action)) self.process_event(EmbedderEvent::MediaSessionAction(action))
} }
pub fn change_visibility(&mut self, visible: bool) -> Result<(), &'static str> { pub fn change_visibility(&mut self, visible: bool) -> Result<(), &'static str> {
info!("change_visibility"); info!("change_visibility");
if let Ok(id) = self.get_browser_id() { if let Ok(id) = self.get_browser_id() {
let event = WindowEvent::ChangeBrowserVisibility(id, visible); let event = EmbedderEvent::ChangeBrowserVisibility(id, visible);
self.process_event(event) self.process_event(event)
} else { } else {
// Ignore visibility change if no browser has been created yet. // Ignore visibility change if no browser has been created yet.
@ -592,7 +595,7 @@ impl ServoGlue {
pub fn ime_dismissed(&mut self) -> Result<(), &'static str> { pub fn ime_dismissed(&mut self) -> Result<(), &'static str> {
info!("ime_dismissed"); info!("ime_dismissed");
self.process_event(WindowEvent::IMEDismissed) self.process_event(EmbedderEvent::IMEDismissed)
} }
pub fn on_context_menu_closed( pub fn on_context_menu_closed(
@ -607,7 +610,7 @@ impl ServoGlue {
Ok(()) Ok(())
} }
fn process_event(&mut self, event: WindowEvent) -> Result<(), &'static str> { fn process_event(&mut self, event: EmbedderEvent) -> Result<(), &'static str> {
self.events.push(event); self.events.push(event);
if !self.batch_mode { if !self.batch_mode {
self.perform_updates() self.perform_updates()
@ -628,7 +631,8 @@ impl ServoGlue {
.callbacks .callbacks
.host_callbacks .host_callbacks
.on_allow_navigation(url.to_string()); .on_allow_navigation(url.to_string());
let window_event = WindowEvent::AllowNavigationResponse(pipeline_id, data); let window_event =
EmbedderEvent::AllowNavigationResponse(pipeline_id, data);
self.events.push(window_event); self.events.push(window_event);
let _ = self.perform_updates(); let _ = self.perform_updates();
} }
@ -687,7 +691,8 @@ impl ServoGlue {
}; };
if let Err(e) = res { if let Err(e) = res {
let reason = format!("Failed to send Prompt response: {}", e); let reason = format!("Failed to send Prompt response: {}", e);
self.events.push(WindowEvent::SendError(browser_id, reason)); self.events
.push(EmbedderEvent::SendError(browser_id, reason));
} }
}, },
EmbedderMsg::AllowOpeningBrowser(response_chan) => { EmbedderMsg::AllowOpeningBrowser(response_chan) => {
@ -703,7 +708,8 @@ impl ServoGlue {
if self.browser_id.is_none() { if self.browser_id.is_none() {
self.browser_id = Some(new_browser_id); self.browser_id = Some(new_browser_id);
} }
self.events.push(WindowEvent::SelectBrowser(new_browser_id)); self.events
.push(EmbedderEvent::SelectBrowser(new_browser_id));
}, },
EmbedderMsg::GetClipboardContents(sender) => { EmbedderMsg::GetClipboardContents(sender) => {
let contents = self.callbacks.host_callbacks.get_clipboard_contents(); let contents = self.callbacks.host_callbacks.get_clipboard_contents();
@ -718,9 +724,9 @@ impl ServoGlue {
if let Some(prev_browser_id) = self.browsers.last() { if let Some(prev_browser_id) = self.browsers.last() {
self.browser_id = Some(*prev_browser_id); self.browser_id = Some(*prev_browser_id);
self.events self.events
.push(WindowEvent::SelectBrowser(*prev_browser_id)); .push(EmbedderEvent::SelectBrowser(*prev_browser_id));
} else { } else {
self.events.push(WindowEvent::Quit); self.events.push(EmbedderEvent::Quit);
} }
}, },
EmbedderMsg::Shutdown => { EmbedderMsg::Shutdown => {

View file

@ -6,12 +6,12 @@
use crate::browser::Browser; use crate::browser::Browser;
use crate::embedder::EmbedderCallbacks; use crate::embedder::EmbedderCallbacks;
use crate::events_loop::{EventsLoop, ServoEvent}; use crate::events_loop::{EventsLoop, WakerEvent};
use crate::window_trait::WindowPortsMethods; use crate::window_trait::WindowPortsMethods;
use crate::{headed_window, headless_window}; use crate::{headed_window, headless_window};
use winit::window::WindowId; use winit::window::WindowId;
use winit::event_loop::EventLoopWindowTarget; use winit::event_loop::EventLoopWindowTarget;
use servo::compositing::windowing::WindowEvent; use servo::compositing::windowing::EmbedderEvent;
use servo::config::opts::{self, parse_url_or_filename}; use servo::config::opts::{self, parse_url_or_filename};
use servo::servo_config::pref; use servo::servo_config::pref;
use servo::servo_url::ServoUrl; use servo::servo_url::ServoUrl;
@ -26,7 +26,7 @@ use webxr::glwindow::GlWindowDiscovery;
pub struct App { pub struct App {
servo: Option<Servo<dyn WindowPortsMethods>>, servo: Option<Servo<dyn WindowPortsMethods>>,
browser: RefCell<Browser<dyn WindowPortsMethods>>, browser: RefCell<Browser<dyn WindowPortsMethods>>,
event_queue: RefCell<Vec<WindowEvent>>, event_queue: RefCell<Vec<EmbedderEvent>>,
suspended: Cell<bool>, suspended: Cell<bool>,
windows: HashMap<WindowId, Rc<dyn WindowPortsMethods>>, windows: HashMap<WindowId, Rc<dyn WindowPortsMethods>>,
} }
@ -76,8 +76,8 @@ impl App {
// it stops being valid. // it stops being valid.
let w = unsafe { let w = unsafe {
std::mem::transmute::< std::mem::transmute::<
&EventLoopWindowTarget<ServoEvent>, &EventLoopWindowTarget<WakerEvent>,
&'static EventLoopWindowTarget<ServoEvent> &'static EventLoopWindowTarget<WakerEvent>
>(w.unwrap()) >(w.unwrap())
}; };
let factory = Box::new(move || Ok(window.new_glwindow(w))); let factory = Box::new(move || Ok(window.new_glwindow(w)));
@ -100,7 +100,7 @@ impl App {
let servo_data = Servo::new(embedder, window.clone(), user_agent.clone()); let servo_data = Servo::new(embedder, window.clone(), user_agent.clone());
let mut servo = servo_data.servo; let mut servo = servo_data.servo;
servo.handle_events(vec![WindowEvent::NewBrowser(get_default_url(), servo_data.browser_id)]); servo.handle_events(vec![EmbedderEvent::NewBrowser(get_default_url(), servo_data.browser_id)]);
servo.setup_logging(); servo.setup_logging();
app.windows.insert(window.id(), window.clone()); app.windows.insert(window.id(), window.clone());
@ -114,7 +114,7 @@ impl App {
} }
// Handle the event // Handle the event
app.winit_event_to_servo_event(e); app.queue_embedder_events_for_winit_event(e);
let animating = app.is_animating(); let animating = app.is_animating();
@ -137,12 +137,13 @@ impl App {
self.windows.iter().any(|(_, window)| window.is_animating()) self.windows.iter().any(|(_, window)| window.is_animating())
} }
fn get_events(&self) -> Vec<WindowEvent> { fn get_events(&self) -> Vec<EmbedderEvent> {
std::mem::take(&mut *self.event_queue.borrow_mut()) std::mem::take(&mut *self.event_queue.borrow_mut())
} }
// This function decides whether the event should be handled during `run_forever`. /// Processes the given winit Event, possibly converting it to an [EmbedderEvent] and
fn winit_event_to_servo_event(&self, event: winit::event::Event<'_, ServoEvent>) { /// routing that to the App or relevant Window event queues.
fn queue_embedder_events_for_winit_event(&self, event: winit::event::Event<'_, WakerEvent>) {
match event { match event {
// App level events // App level events
winit::event::Event::Suspended => { winit::event::Event::Suspended => {
@ -150,15 +151,15 @@ impl App {
}, },
winit::event::Event::Resumed => { winit::event::Event::Resumed => {
self.suspended.set(false); self.suspended.set(false);
self.event_queue.borrow_mut().push(WindowEvent::Idle); self.event_queue.borrow_mut().push(EmbedderEvent::Idle);
}, },
winit::event::Event::UserEvent(_) => { winit::event::Event::UserEvent(_) => {
self.event_queue.borrow_mut().push(WindowEvent::Idle); self.event_queue.borrow_mut().push(EmbedderEvent::Idle);
}, },
winit::event::Event::DeviceEvent { .. } => {}, winit::event::Event::DeviceEvent { .. } => {},
winit::event::Event::RedrawRequested(_) => { winit::event::Event::RedrawRequested(_) => {
self.event_queue.borrow_mut().push(WindowEvent::Idle); self.event_queue.borrow_mut().push(EmbedderEvent::Idle);
}, },
// Window level events // Window level events
@ -170,7 +171,7 @@ impl App {
warn!("Got an event from unknown window"); warn!("Got an event from unknown window");
}, },
Some(window) => { Some(window) => {
window.winit_event_to_servo_event(event); window.queue_embedder_events_for_winit_event(event);
}, },
} }
}, },
@ -182,6 +183,13 @@ impl App {
} }
} }
/// Pumps events and messages between the embedder and Servo, where embedder events flow
/// towards Servo and embedder messages flow away from Servo, and also runs the compositor.
///
/// As the embedder, we push embedder events through our event queues, from the App queue and
/// Window queues to the Browser queue, and from the Browser queue to Servo. We receive and
/// collect embedder messages from the various Servo components, then take them out of the
/// Servo interface so that the Browser can handle them.
fn handle_events(&mut self) -> bool { fn handle_events(&mut self) -> bool {
let mut browser = self.browser.borrow_mut(); let mut browser = self.browser.borrow_mut();
@ -192,23 +200,33 @@ impl App {
// browser instance. Pressing the "a" key on the glwindow // browser instance. Pressing the "a" key on the glwindow
// will send a key event to the servo window. // will send a key event to the servo window.
let mut app_events = self.get_events(); // Take any outstanding embedder events from the App and its Windows.
let mut embedder_events = self.get_events();
for (_win_id, window) in &self.windows { for (_win_id, window) in &self.windows {
app_events.extend(window.get_events()); embedder_events.extend(window.get_events());
} }
browser.handle_window_events(app_events); // Catch some keyboard events, and push the rest onto the Browser event queue.
browser.handle_window_events(embedder_events);
let mut servo_events = self.servo.as_mut().unwrap().get_events(); // Take any new embedder messages from Servo itself.
let mut embedder_messages = self.servo.as_mut().unwrap().get_events();
let mut need_resize = false; let mut need_resize = false;
loop { loop {
browser.handle_servo_events(servo_events); // Consume and handle those embedder messages.
browser.handle_servo_events(embedder_messages);
// Route embedder events from the Browser to the relevant Servo components,
// receives and collects embedder messages from various Servo components,
// and runs the compositor.
need_resize |= self.servo.as_mut().unwrap().handle_events(browser.get_events()); need_resize |= self.servo.as_mut().unwrap().handle_events(browser.get_events());
if browser.shutdown_requested() { if browser.shutdown_requested() {
return true; return true;
} }
servo_events = self.servo.as_mut().unwrap().get_events();
if servo_events.is_empty() { // Take any new embedder messages from Servo itself.
embedder_messages = self.servo.as_mut().unwrap().get_events();
if embedder_messages.is_empty() {
break; break;
} }
} }

View file

@ -7,7 +7,7 @@ use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT};
use clipboard::{ClipboardContext, ClipboardProvider}; use clipboard::{ClipboardContext, ClipboardProvider};
use euclid::{Point2D, Vector2D}; use euclid::{Point2D, Vector2D};
use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher}; use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher};
use servo::compositing::windowing::{WebRenderDebugOption, WindowEvent}; use servo::compositing::windowing::{WebRenderDebugOption, EmbedderEvent};
use servo::embedder_traits::{ use servo::embedder_traits::{
ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest, ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest,
PromptDefinition, PromptOrigin, PromptResult, PromptDefinition, PromptOrigin, PromptResult,
@ -44,7 +44,7 @@ pub struct Browser<Window: WindowPortsMethods + ?Sized> {
title: Option<String>, title: Option<String>,
window: Rc<Window>, window: Rc<Window>,
event_queue: Vec<WindowEvent>, event_queue: Vec<EmbedderEvent>,
clipboard_ctx: Option<ClipboardContext>, clipboard_ctx: Option<ClipboardContext>,
shutdown_requested: bool, shutdown_requested: bool,
} }
@ -72,14 +72,14 @@ where
} }
} }
pub fn get_events(&mut self) -> Vec<WindowEvent> { pub fn get_events(&mut self) -> Vec<EmbedderEvent> {
std::mem::take(&mut self.event_queue) std::mem::take(&mut self.event_queue)
} }
pub fn handle_window_events(&mut self, events: Vec<WindowEvent>) { pub fn handle_window_events(&mut self, events: Vec<EmbedderEvent>) {
for event in events { for event in events {
match event { match event {
WindowEvent::Keyboard(key_event) => { EmbedderEvent::Keyboard(key_event) => {
self.handle_key_from_window(key_event); self.handle_key_from_window(key_event);
}, },
event => { event => {
@ -98,7 +98,7 @@ where
ShortcutMatcher::from_event(key_event.clone()) ShortcutMatcher::from_event(key_event.clone())
.shortcut(CMD_OR_CONTROL, 'R', || { .shortcut(CMD_OR_CONTROL, 'R', || {
if let Some(id) = self.browser_id { if let Some(id) = self.browser_id {
self.event_queue.push(WindowEvent::Reload(id)); self.event_queue.push(EmbedderEvent::Reload(id));
} }
}) })
.shortcut(CMD_OR_CONTROL, 'L', || { .shortcut(CMD_OR_CONTROL, 'L', || {
@ -112,13 +112,13 @@ where
if let Some(input) = input { if let Some(input) = input {
if let Some(url) = sanitize_url(&input) { if let Some(url) = sanitize_url(&input) {
if let Some(id) = self.browser_id { if let Some(id) = self.browser_id {
self.event_queue.push(WindowEvent::LoadUrl(id, url)); self.event_queue.push(EmbedderEvent::LoadUrl(id, url));
} }
} }
} }
}) })
.shortcut(CMD_OR_CONTROL, 'Q', || { .shortcut(CMD_OR_CONTROL, 'Q', || {
self.event_queue.push(WindowEvent::Quit); self.event_queue.push(EmbedderEvent::Quit);
}) })
.shortcut(CMD_OR_CONTROL, 'P', || { .shortcut(CMD_OR_CONTROL, 'P', || {
let rate = env::var("SAMPLING_RATE") let rate = env::var("SAMPLING_RATE")
@ -129,38 +129,38 @@ where
.ok() .ok()
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.unwrap_or(10); .unwrap_or(10);
self.event_queue.push(WindowEvent::ToggleSamplingProfiler( self.event_queue.push(EmbedderEvent::ToggleSamplingProfiler(
Duration::from_millis(rate), Duration::from_millis(rate),
Duration::from_secs(duration), Duration::from_secs(duration),
)); ));
}) })
.shortcut(Modifiers::CONTROL, Key::F9, || { .shortcut(Modifiers::CONTROL, Key::F9, || {
self.event_queue.push(WindowEvent::CaptureWebRender) self.event_queue.push(EmbedderEvent::CaptureWebRender)
}) })
.shortcut(Modifiers::CONTROL, Key::F10, || { .shortcut(Modifiers::CONTROL, Key::F10, || {
self.event_queue.push(WindowEvent::ToggleWebRenderDebug( self.event_queue.push(EmbedderEvent::ToggleWebRenderDebug(
WebRenderDebugOption::RenderTargetDebug, WebRenderDebugOption::RenderTargetDebug,
)); ));
}) })
.shortcut(Modifiers::CONTROL, Key::F11, || { .shortcut(Modifiers::CONTROL, Key::F11, || {
self.event_queue.push(WindowEvent::ToggleWebRenderDebug( self.event_queue.push(EmbedderEvent::ToggleWebRenderDebug(
WebRenderDebugOption::TextureCacheDebug, WebRenderDebugOption::TextureCacheDebug,
)); ));
}) })
.shortcut(Modifiers::CONTROL, Key::F12, || { .shortcut(Modifiers::CONTROL, Key::F12, || {
self.event_queue.push(WindowEvent::ToggleWebRenderDebug( self.event_queue.push(EmbedderEvent::ToggleWebRenderDebug(
WebRenderDebugOption::Profiler, WebRenderDebugOption::Profiler,
)); ));
}) })
.shortcut(CMD_OR_ALT, Key::ArrowRight, || { .shortcut(CMD_OR_ALT, Key::ArrowRight, || {
if let Some(id) = self.browser_id { if let Some(id) = self.browser_id {
let event = WindowEvent::Navigation(id, TraversalDirection::Forward(1)); let event = EmbedderEvent::Navigation(id, TraversalDirection::Forward(1));
self.event_queue.push(event); self.event_queue.push(event);
} }
}) })
.shortcut(CMD_OR_ALT, Key::ArrowLeft, || { .shortcut(CMD_OR_ALT, Key::ArrowLeft, || {
if let Some(id) = self.browser_id { if let Some(id) = self.browser_id {
let event = WindowEvent::Navigation(id, TraversalDirection::Back(1)); let event = EmbedderEvent::Navigation(id, TraversalDirection::Back(1));
self.event_queue.push(event); self.event_queue.push(event);
} }
}) })
@ -168,11 +168,11 @@ where
let state = self.window.get_fullscreen(); let state = self.window.get_fullscreen();
if state { if state {
if let Some(id) = self.browser_id { if let Some(id) = self.browser_id {
let event = WindowEvent::ExitFullScreen(id); let event = EmbedderEvent::ExitFullScreen(id);
self.event_queue.push(event); self.event_queue.push(event);
} }
} else { } else {
self.event_queue.push(WindowEvent::Quit); self.event_queue.push(EmbedderEvent::Quit);
} }
}) })
.otherwise(|| self.platform_handle_key(key_event)); .otherwise(|| self.platform_handle_key(key_event));
@ -183,12 +183,12 @@ where
if let Some(id) = self.browser_id { if let Some(id) = self.browser_id {
if let Some(event) = ShortcutMatcher::from_event(key_event.clone()) if let Some(event) = ShortcutMatcher::from_event(key_event.clone())
.shortcut(CMD_OR_CONTROL, '[', || { .shortcut(CMD_OR_CONTROL, '[', || {
WindowEvent::Navigation(id, TraversalDirection::Back(1)) EmbedderEvent::Navigation(id, TraversalDirection::Back(1))
}) })
.shortcut(CMD_OR_CONTROL, ']', || { .shortcut(CMD_OR_CONTROL, ']', || {
WindowEvent::Navigation(id, TraversalDirection::Forward(1)) EmbedderEvent::Navigation(id, TraversalDirection::Forward(1))
}) })
.otherwise(|| WindowEvent::Keyboard(key_event)) .otherwise(|| EmbedderEvent::Keyboard(key_event))
{ {
self.event_queue.push(event) self.event_queue.push(event)
} }
@ -202,16 +202,16 @@ where
fn handle_key_from_servo(&mut self, _: Option<BrowserId>, event: KeyboardEvent) { fn handle_key_from_servo(&mut self, _: Option<BrowserId>, event: KeyboardEvent) {
ShortcutMatcher::from_event(event) ShortcutMatcher::from_event(event)
.shortcut(CMD_OR_CONTROL, '=', || { .shortcut(CMD_OR_CONTROL, '=', || {
self.event_queue.push(WindowEvent::Zoom(1.1)) self.event_queue.push(EmbedderEvent::Zoom(1.1))
}) })
.shortcut(CMD_OR_CONTROL, '+', || { .shortcut(CMD_OR_CONTROL, '+', || {
self.event_queue.push(WindowEvent::Zoom(1.1)) self.event_queue.push(EmbedderEvent::Zoom(1.1))
}) })
.shortcut(CMD_OR_CONTROL, '-', || { .shortcut(CMD_OR_CONTROL, '-', || {
self.event_queue.push(WindowEvent::Zoom(1.0 / 1.1)) self.event_queue.push(EmbedderEvent::Zoom(1.0 / 1.1))
}) })
.shortcut(CMD_OR_CONTROL, '0', || { .shortcut(CMD_OR_CONTROL, '0', || {
self.event_queue.push(WindowEvent::ResetZoom) self.event_queue.push(EmbedderEvent::ResetZoom)
}) })
.shortcut(Modifiers::empty(), Key::PageDown, || { .shortcut(Modifiers::empty(), Key::PageDown, || {
let scroll_location = ScrollLocation::Delta(Vector2D::new( let scroll_location = ScrollLocation::Delta(Vector2D::new(
@ -260,7 +260,7 @@ where
} }
fn scroll_window_from_key(&mut self, scroll_location: ScrollLocation, phase: TouchEventType) { fn scroll_window_from_key(&mut self, scroll_location: ScrollLocation, phase: TouchEventType) {
let event = WindowEvent::Scroll(scroll_location, Point2D::zero(), phase); let event = EmbedderEvent::Scroll(scroll_location, Point2D::zero(), phase);
self.event_queue.push(event); self.event_queue.push(event);
} }
@ -366,7 +366,7 @@ where
if let Err(e) = res { if let Err(e) = res {
let reason = format!("Failed to send Prompt response: {}", e); let reason = format!("Failed to send Prompt response: {}", e);
self.event_queue self.event_queue
.push(WindowEvent::SendError(browser_id, reason)); .push(EmbedderEvent::SendError(browser_id, reason));
} }
}, },
EmbedderMsg::AllowUnload(sender) => { EmbedderMsg::AllowUnload(sender) => {
@ -374,13 +374,13 @@ where
if let Err(e) = sender.send(true) { if let Err(e) = sender.send(true) {
let reason = format!("Failed to send AllowUnload response: {}", e); let reason = format!("Failed to send AllowUnload response: {}", e);
self.event_queue self.event_queue
.push(WindowEvent::SendError(browser_id, reason)); .push(EmbedderEvent::SendError(browser_id, reason));
} }
}, },
EmbedderMsg::AllowNavigationRequest(pipeline_id, _url) => { EmbedderMsg::AllowNavigationRequest(pipeline_id, _url) => {
if let Some(_browser_id) = browser_id { if let Some(_browser_id) = browser_id {
self.event_queue self.event_queue
.push(WindowEvent::AllowNavigationResponse(pipeline_id, true)); .push(EmbedderEvent::AllowNavigationResponse(pipeline_id, true));
} }
}, },
EmbedderMsg::AllowOpeningBrowser(response_chan) => { EmbedderMsg::AllowOpeningBrowser(response_chan) => {
@ -399,7 +399,7 @@ where
error!("Multiple top level browsing contexts not supported yet."); error!("Multiple top level browsing contexts not supported yet.");
} }
self.event_queue self.event_queue
.push(WindowEvent::SelectBrowser(new_browser_id)); .push(EmbedderEvent::SelectBrowser(new_browser_id));
}, },
EmbedderMsg::Keyboard(key_event) => { EmbedderMsg::Keyboard(key_event) => {
self.handle_key_from_servo(browser_id, key_event); self.handle_key_from_servo(browser_id, key_event);
@ -453,9 +453,9 @@ where
if let Some(prev_browser_id) = self.browsers.last() { if let Some(prev_browser_id) = self.browsers.last() {
self.browser_id = Some(*prev_browser_id); self.browser_id = Some(*prev_browser_id);
self.event_queue self.event_queue
.push(WindowEvent::SelectBrowser(*prev_browser_id)); .push(EmbedderEvent::SelectBrowser(*prev_browser_id));
} else { } else {
self.event_queue.push(WindowEvent::Quit); self.event_queue.push(EmbedderEvent::Quit);
} }
}, },
EmbedderMsg::Shutdown => { EmbedderMsg::Shutdown => {
@ -467,7 +467,7 @@ where
if let Err(e) = sender.send(selected) { if let Err(e) = sender.send(selected) {
let reason = let reason =
format!("Failed to send GetSelectedBluetoothDevice response: {}", e); format!("Failed to send GetSelectedBluetoothDevice response: {}", e);
self.event_queue.push(WindowEvent::SendError(None, reason)); self.event_queue.push(EmbedderEvent::SendError(None, reason));
}; };
}, },
EmbedderMsg::SelectFiles(patterns, multiple_files, sender) => { EmbedderMsg::SelectFiles(patterns, multiple_files, sender) => {
@ -480,7 +480,7 @@ where
}; };
if let Err(e) = res { if let Err(e) = res {
let reason = format!("Failed to send SelectFiles response: {}", e); let reason = format!("Failed to send SelectFiles response: {}", e);
self.event_queue.push(WindowEvent::SendError(None, reason)); self.event_queue.push(EmbedderEvent::SendError(None, reason));
}; };
}, },
EmbedderMsg::PromptPermission(prompt, sender) => { EmbedderMsg::PromptPermission(prompt, sender) => {

View file

@ -11,15 +11,15 @@ use std::time;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
/// Another process or thread has kicked the OS event loop with EventLoopWaker.
#[derive(Debug)] #[derive(Debug)]
pub enum ServoEvent { pub struct WakerEvent;
Awakened,
}
/// The real or fake OS event loop.
#[allow(dead_code)] #[allow(dead_code)]
enum EventLoop { enum EventLoop {
/// A real Winit windowing event loop. /// A real Winit windowing event loop.
Winit(Option<winit::event_loop::EventLoop<ServoEvent>>), Winit(Option<winit::event_loop::EventLoop<WakerEvent>>),
/// A fake event loop which contains a signalling flag used to ensure /// A fake event loop which contains a signalling flag used to ensure
/// that pending events get processed in a timely fashion, and a condition /// that pending events get processed in a timely fashion, and a condition
/// variable to allow waiting on that flag changing state. /// variable to allow waiting on that flag changing state.
@ -71,7 +71,7 @@ impl EventsLoop {
EventLoop::Headless(ref data) => Box::new(HeadlessEventLoopWaker(data.clone())), EventLoop::Headless(ref data) => Box::new(HeadlessEventLoopWaker(data.clone())),
} }
} }
pub fn as_winit(&self) -> &winit::event_loop::EventLoop<ServoEvent> { pub fn as_winit(&self) -> &winit::event_loop::EventLoop<WakerEvent> {
match self.0 { match self.0 {
EventLoop::Winit(Some(ref event_loop)) => event_loop, EventLoop::Winit(Some(ref event_loop)) => event_loop,
EventLoop::Winit(None) | EventLoop::Headless(..) => { EventLoop::Winit(None) | EventLoop::Headless(..) => {
@ -82,8 +82,8 @@ impl EventsLoop {
pub fn run_forever<F: 'static>(self, mut callback: F) pub fn run_forever<F: 'static>(self, mut callback: F)
where F: FnMut( where F: FnMut(
winit::event::Event<'_, ServoEvent>, winit::event::Event<'_, WakerEvent>,
Option<&winit::event_loop::EventLoopWindowTarget<ServoEvent>>, Option<&winit::event_loop::EventLoopWindowTarget<WakerEvent>>,
&mut winit::event_loop::ControlFlow &mut winit::event_loop::ControlFlow
) { ) {
match self.0 { match self.0 {
@ -105,7 +105,7 @@ impl EventsLoop {
None, None,
&mut control_flow &mut control_flow
); );
event = winit::event::Event::<ServoEvent>::UserEvent(ServoEvent::Awakened); event = winit::event::Event::<WakerEvent>::UserEvent(WakerEvent);
if control_flow != winit::event_loop::ControlFlow::Poll { if control_flow != winit::event_loop::ControlFlow::Poll {
*flag.lock().unwrap() = false; *flag.lock().unwrap() = false;
@ -135,10 +135,10 @@ impl EventsLoop {
} }
struct HeadedEventLoopWaker { struct HeadedEventLoopWaker {
proxy: Arc<Mutex<winit::event_loop::EventLoopProxy<ServoEvent>>>, proxy: Arc<Mutex<winit::event_loop::EventLoopProxy<WakerEvent>>>,
} }
impl HeadedEventLoopWaker { impl HeadedEventLoopWaker {
fn new(events_loop: &winit::event_loop::EventLoop<ServoEvent>) -> HeadedEventLoopWaker { fn new(events_loop: &winit::event_loop::EventLoop<WakerEvent>) -> HeadedEventLoopWaker {
let proxy = Arc::new(Mutex::new(events_loop.create_proxy())); let proxy = Arc::new(Mutex::new(events_loop.create_proxy()));
HeadedEventLoopWaker { proxy } HeadedEventLoopWaker { proxy }
} }
@ -146,7 +146,7 @@ impl HeadedEventLoopWaker {
impl EventLoopWaker for HeadedEventLoopWaker { impl EventLoopWaker for HeadedEventLoopWaker {
fn wake(&self) { fn wake(&self) {
// Kick the OS event loop awake. // Kick the OS event loop awake.
if let Err(err) = self.proxy.lock().unwrap().send_event(ServoEvent::Awakened) { if let Err(err) = self.proxy.lock().unwrap().send_event(WakerEvent) {
warn!("Failed to wake up event loop ({}).", err); warn!("Failed to wake up event loop ({}).", err);
} }
} }

View file

@ -4,7 +4,7 @@
//! A winit window implementation. //! A winit window implementation.
use crate::events_loop::{EventsLoop, ServoEvent}; use crate::events_loop::{EventsLoop, WakerEvent};
use crate::keyutils::keyboard_event_from_winit; use crate::keyutils::keyboard_event_from_winit;
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT};
use euclid::{ use euclid::{
@ -16,7 +16,7 @@ use winit::window::Icon;
use winit::event::{ElementState, KeyboardInput, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode}; use winit::event::{ElementState, KeyboardInput, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode};
use servo::keyboard_types::{Key, KeyState, KeyboardEvent}; use servo::keyboard_types::{Key, KeyState, KeyboardEvent};
use servo::compositing::windowing::{AnimationState, MouseWindowEvent, WindowEvent}; use servo::compositing::windowing::{AnimationState, MouseWindowEvent, EmbedderEvent};
use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods};
use servo::embedder_traits::Cursor; use servo::embedder_traits::Cursor;
use servo::script_traits::{TouchEventType, WheelDelta, WheelMode}; use servo::script_traits::{TouchEventType, WheelDelta, WheelMode};
@ -55,7 +55,7 @@ pub struct Window {
mouse_down_button: Cell<Option<winit::event::MouseButton>>, mouse_down_button: Cell<Option<winit::event::MouseButton>>,
mouse_down_point: Cell<Point2D<i32, DevicePixel>>, mouse_down_point: Cell<Point2D<i32, DevicePixel>>,
primary_monitor: winit::monitor::MonitorHandle, primary_monitor: winit::monitor::MonitorHandle,
event_queue: RefCell<Vec<WindowEvent>>, event_queue: RefCell<Vec<EmbedderEvent>>,
mouse_pos: Cell<Point2D<i32, DevicePixel>>, mouse_pos: Cell<Point2D<i32, DevicePixel>>,
last_pressed: Cell<Option<(KeyboardEvent, Option<VirtualKeyCode>)>>, last_pressed: Cell<Option<(KeyboardEvent, Option<VirtualKeyCode>)>>,
/// A map of winit's key codes to key values that are interpreted from /// A map of winit's key codes to key values that are interpreted from
@ -199,7 +199,7 @@ impl Window {
} }
self.event_queue self.event_queue
.borrow_mut() .borrow_mut()
.push(WindowEvent::Keyboard(event)); .push(EmbedderEvent::Keyboard(event));
} }
fn handle_keyboard_input(&self, input: KeyboardInput) { fn handle_keyboard_input(&self, input: KeyboardInput) {
@ -227,7 +227,7 @@ impl Window {
} }
self.event_queue self.event_queue
.borrow_mut() .borrow_mut()
.push(WindowEvent::Keyboard(event)); .push(EmbedderEvent::Keyboard(event));
} }
} }
@ -265,7 +265,7 @@ impl Window {
if pixel_dist < max_pixel_dist { if pixel_dist < max_pixel_dist {
self.event_queue self.event_queue
.borrow_mut() .borrow_mut()
.push(WindowEvent::MouseWindowEventClass(mouse_up_event)); .push(EmbedderEvent::MouseWindowEventClass(mouse_up_event));
MouseWindowEvent::Click(mouse_button, coords.to_f32()) MouseWindowEvent::Click(mouse_button, coords.to_f32())
} else { } else {
mouse_up_event mouse_up_event
@ -277,7 +277,7 @@ impl Window {
}; };
self.event_queue self.event_queue
.borrow_mut() .borrow_mut()
.push(WindowEvent::MouseWindowEventClass(event)); .push(EmbedderEvent::MouseWindowEventClass(event));
} }
fn device_hidpi_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel> { fn device_hidpi_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel> {
@ -296,7 +296,7 @@ impl Window {
} }
impl WindowPortsMethods for Window { impl WindowPortsMethods for Window {
fn get_events(&self) -> Vec<WindowEvent> { fn get_events(&self) -> Vec<EmbedderEvent> {
std::mem::take(&mut *self.event_queue.borrow_mut()) std::mem::take(&mut *self.event_queue.borrow_mut())
} }
@ -393,7 +393,7 @@ impl WindowPortsMethods for Window {
self.winit_window.id() self.winit_window.id()
} }
fn winit_event_to_servo_event(&self, event: winit::event::WindowEvent<'_>) { fn queue_embedder_events_for_winit_event(&self, event: winit::event::WindowEvent<'_>) {
match event { match event {
winit::event::WindowEvent::ReceivedCharacter(ch) => self.handle_received_character(ch), winit::event::WindowEvent::ReceivedCharacter(ch) => self.handle_received_character(ch),
winit::event::WindowEvent::KeyboardInput { input, .. } => self.handle_keyboard_input(input), winit::event::WindowEvent::KeyboardInput { input, .. } => self.handle_keyboard_input(input),
@ -408,7 +408,7 @@ impl WindowPortsMethods for Window {
self.mouse_pos.set(Point2D::new(x, y)); self.mouse_pos.set(Point2D::new(x, y));
self.event_queue self.event_queue
.borrow_mut() .borrow_mut()
.push(WindowEvent::MouseWindowMoveEventClass(Point2D::new( .push(EmbedderEvent::MouseWindowMoveEventClass(Point2D::new(
x as f32, y as f32, x as f32, y as f32,
))); )));
}, },
@ -433,7 +433,7 @@ impl WindowPortsMethods for Window {
}; };
let pos = self.mouse_pos.get(); let pos = self.mouse_pos.get();
let position = Point2D::new(pos.x as f32, pos.y as f32); let position = Point2D::new(pos.x as f32, pos.y as f32);
let wheel_event = WindowEvent::Wheel(wheel_delta, position); let wheel_event = EmbedderEvent::Wheel(wheel_delta, position);
// Scroll events snap to the major axis of movement, with vertical // Scroll events snap to the major axis of movement, with vertical
// preferred over horizontal. // preferred over horizontal.
@ -446,7 +446,7 @@ impl WindowPortsMethods for Window {
let scroll_location = ScrollLocation::Delta(Vector2D::new(dx as f32, dy as f32)); let scroll_location = ScrollLocation::Delta(Vector2D::new(dx as f32, dy as f32));
let phase = winit_phase_to_touch_event_type(phase); let phase = winit_phase_to_touch_event_type(phase);
let scroll_event = let scroll_event =
WindowEvent::Scroll(scroll_location, self.mouse_pos.get(), phase); EmbedderEvent::Scroll(scroll_location, self.mouse_pos.get(), phase);
// Send events // Send events
self.event_queue.borrow_mut().push(wheel_event); self.event_queue.borrow_mut().push(wheel_event);
@ -461,10 +461,10 @@ impl WindowPortsMethods for Window {
let point = Point2D::new(position.x as f32, position.y as f32); let point = Point2D::new(position.x as f32, position.y as f32);
self.event_queue self.event_queue
.borrow_mut() .borrow_mut()
.push(WindowEvent::Touch(phase, id, point)); .push(EmbedderEvent::Touch(phase, id, point));
}, },
winit::event::WindowEvent::CloseRequested => { winit::event::WindowEvent::CloseRequested => {
self.event_queue.borrow_mut().push(WindowEvent::Quit); self.event_queue.borrow_mut().push(EmbedderEvent::Quit);
}, },
winit::event::WindowEvent::Resized(physical_size) => { winit::event::WindowEvent::Resized(physical_size) => {
let (width, height) = physical_size.into(); let (width, height) = physical_size.into();
@ -475,7 +475,7 @@ impl WindowPortsMethods for Window {
.resize(physical_size.to_i32()) .resize(physical_size.to_i32())
.expect("Failed to resize"); .expect("Failed to resize");
self.inner_size.set(new_size); self.inner_size.set(new_size);
self.event_queue.borrow_mut().push(WindowEvent::Resize); self.event_queue.borrow_mut().push(EmbedderEvent::Resize);
} }
}, },
_ => {}, _ => {},
@ -484,7 +484,7 @@ impl WindowPortsMethods for Window {
fn new_glwindow( fn new_glwindow(
&self, &self,
event_loop: &winit::event_loop::EventLoopWindowTarget<ServoEvent> event_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent>
) -> Box<dyn webxr::glwindow::GlWindow> { ) -> Box<dyn webxr::glwindow::GlWindow> {
let size = self.winit_window.outer_size(); let size = self.winit_window.outer_size();

View file

@ -4,10 +4,10 @@
//! A headless window implementation. //! A headless window implementation.
use crate::events_loop::ServoEvent; use crate::events_loop::WakerEvent;
use crate::window_trait::WindowPortsMethods; use crate::window_trait::WindowPortsMethods;
use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D}; use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D};
use servo::compositing::windowing::{AnimationState, WindowEvent}; use servo::compositing::windowing::{AnimationState, EmbedderEvent};
use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods};
use servo::servo_geometry::DeviceIndependentPixel; use servo::servo_geometry::DeviceIndependentPixel;
use servo::style_traits::DevicePixel; use servo::style_traits::DevicePixel;
@ -63,7 +63,7 @@ impl Window {
} }
impl WindowPortsMethods for Window { impl WindowPortsMethods for Window {
fn get_events(&self) -> Vec<WindowEvent> { fn get_events(&self) -> Vec<EmbedderEvent> {
vec![] vec![]
} }
@ -98,13 +98,13 @@ impl WindowPortsMethods for Window {
self.animation_state.get() == AnimationState::Animating self.animation_state.get() == AnimationState::Animating
} }
fn winit_event_to_servo_event(&self, _event: winit::event::WindowEvent<'_>) { fn queue_embedder_events_for_winit_event(&self, _event: winit::event::WindowEvent<'_>) {
// Not expecting any winit events. // Not expecting any winit events.
} }
fn new_glwindow( fn new_glwindow(
&self, &self,
_events_loop: &winit::event_loop::EventLoopWindowTarget<ServoEvent> _events_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent>
) -> Box<dyn webxr::glwindow::GlWindow> { ) -> Box<dyn webxr::glwindow::GlWindow> {
unimplemented!() unimplemented!()
} }

View file

@ -5,8 +5,8 @@
//! Definition of Window. //! Definition of Window.
//! Implemented by headless and headed windows. //! Implemented by headless and headed windows.
use crate::events_loop::ServoEvent; use crate::events_loop::WakerEvent;
use servo::compositing::windowing::{WindowEvent, WindowMethods}; use servo::compositing::windowing::{EmbedderEvent, WindowMethods};
use servo::embedder_traits::Cursor; use servo::embedder_traits::Cursor;
use servo::webrender_api::units::{DeviceIntPoint, DeviceIntSize}; use servo::webrender_api::units::{DeviceIntPoint, DeviceIntSize};
@ -15,12 +15,12 @@ use servo::webrender_api::units::{DeviceIntPoint, DeviceIntSize};
pub const LINE_HEIGHT: f32 = 38.0; pub const LINE_HEIGHT: f32 = 38.0;
pub trait WindowPortsMethods: WindowMethods { pub trait WindowPortsMethods: WindowMethods {
fn get_events(&self) -> Vec<WindowEvent>; fn get_events(&self) -> Vec<EmbedderEvent>;
fn id(&self) -> winit::window::WindowId; fn id(&self) -> winit::window::WindowId;
fn has_events(&self) -> bool; fn has_events(&self) -> bool;
fn page_height(&self) -> f32; fn page_height(&self) -> f32;
fn get_fullscreen(&self) -> bool; fn get_fullscreen(&self) -> bool;
fn winit_event_to_servo_event(&self, event: winit::event::WindowEvent<'_>); fn queue_embedder_events_for_winit_event(&self, event: winit::event::WindowEvent<'_>);
fn is_animating(&self) -> bool; fn is_animating(&self) -> bool;
fn set_title(&self, _title: &str) {} fn set_title(&self, _title: &str) {}
fn set_inner_size(&self, _size: DeviceIntSize) {} fn set_inner_size(&self, _size: DeviceIntSize) {}
@ -29,6 +29,6 @@ pub trait WindowPortsMethods: WindowMethods {
fn set_cursor(&self, _cursor: Cursor) {} fn set_cursor(&self, _cursor: Cursor) {}
fn new_glwindow( fn new_glwindow(
&self, &self,
events_loop: &winit::event_loop::EventLoopWindowTarget<ServoEvent> events_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent>
) -> Box<dyn webxr::glwindow::GlWindow>; ) -> Box<dyn webxr::glwindow::GlWindow>;
} }