[NFC] servoshell: fix rust-analyzer and rustfmt breakage (#30340)

This commit is contained in:
Delan Azabani 2023-09-12 14:27:10 +08:00 committed by GitHub
parent 1bbd0c1e6e
commit 90ad5920e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 271 additions and 216 deletions

1
Cargo.lock generated
View file

@ -5483,6 +5483,7 @@ dependencies = [
"arboard", "arboard",
"backtrace", "backtrace",
"cc", "cc",
"cfg-if 1.0.0",
"egui", "egui",
"egui-winit", "egui-winit",
"egui_glow", "egui_glow",

View file

@ -20,6 +20,7 @@ backtrace = "0.3"
base64 = "0.21.3" base64 = "0.21.3"
bitflags = "2.4" bitflags = "2.4"
byteorder = "1.0" byteorder = "1.0"
cfg-if = "1.0.0"
encoding_rs = "0.8" encoding_rs = "0.8"
euclid = "0.22" euclid = "0.22"
cookie = "0.12" cookie = "0.12"

View file

@ -46,6 +46,7 @@ xr-profile = ["libservo/xr-profile"]
[target.'cfg(not(target_os = "android"))'.dependencies] [target.'cfg(not(target_os = "android"))'.dependencies]
arboard = "3" arboard = "3"
backtrace = { workspace = true } backtrace = { workspace = true }
cfg-if = { workspace = true }
egui = "0.22.0" egui = "0.22.0"
egui_glow = { version = "0.22.0", features = ["winit"] } egui_glow = { version = "0.22.0", features = ["winit"] }
egui-winit = { version = "0.22.0", default-features = false, features = ["clipboard", "wayland"] } egui-winit = { version = "0.22.0", default-features = false, features = ["clipboard", "wayland"] }

View file

@ -4,6 +4,22 @@
//! Application entry point, runs the event loop. //! Application entry point, runs the event loop.
use std::cell::{Cell, RefCell, RefMut};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Instant;
use gleam::gl;
use log::{trace, warn};
use servo::compositing::windowing::EmbedderEvent;
use servo::config::opts;
use servo::servo_config::pref;
use servo::Servo;
use surfman::GLApi;
use webxr::glwindow::GlWindowDiscovery;
use winit::event_loop::EventLoopWindowTarget;
use winit::window::WindowId;
use crate::browser::Browser; use crate::browser::Browser;
use crate::embedder::EmbedderCallbacks; use crate::embedder::EmbedderCallbacks;
use crate::events_loop::{EventsLoop, WakerEvent}; use crate::events_loop::{EventsLoop, WakerEvent};
@ -11,20 +27,6 @@ use crate::minibrowser::Minibrowser;
use crate::parser::get_default_url; use crate::parser::get_default_url;
use crate::window_trait::WindowPortsMethods; use crate::window_trait::WindowPortsMethods;
use crate::{headed_window, headless_window}; use crate::{headed_window, headless_window};
use gleam::gl;
use log::{trace, warn};
use servo::compositing::windowing::EmbedderEvent;
use servo::config::opts;
use servo::servo_config::pref;
use servo::Servo;
use std::cell::{Cell, RefCell, RefMut};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Instant;
use surfman::GLApi;
use webxr::glwindow::GlWindowDiscovery;
use winit::window::WindowId;
use winit::event_loop::EventLoopWindowTarget;
pub struct App { pub struct App {
servo: Option<Servo<dyn WindowPortsMethods>>, servo: Option<Servo<dyn WindowPortsMethods>>,
@ -80,7 +82,9 @@ impl App {
// Make sure the gl context is made current. // Make sure the gl context is made current.
let webrender_surfman = window.webrender_surfman(); let webrender_surfman = window.webrender_surfman();
let webrender_gl = match webrender_surfman.connection().gl_api() { let webrender_gl = match webrender_surfman.connection().gl_api() {
GLApi::GL => unsafe { gl::GlFns::load_with(|s| webrender_surfman.get_proc_address(s)) }, GLApi::GL => unsafe {
gl::GlFns::load_with(|s| webrender_surfman.get_proc_address(s))
},
GLApi::GLES => unsafe { GLApi::GLES => unsafe {
gl::GlesFns::load_with(|s| webrender_surfman.get_proc_address(s)) gl::GlesFns::load_with(|s| webrender_surfman.get_proc_address(s))
}, },
@ -124,7 +128,8 @@ impl App {
winit::event::Event::NewEvents(winit::event::StartCause::Init) => { winit::event::Event::NewEvents(winit::event::StartCause::Init) => {
let surfman = window.webrender_surfman(); let surfman = window.webrender_surfman();
let xr_discovery = if pref!(dom.webxr.glwindow.enabled) && ! opts::get().headless { let xr_discovery = if pref!(dom.webxr.glwindow.enabled) && !opts::get().headless
{
let window = window.clone(); let window = window.clone();
// This should be safe because run_forever does, in fact, // This should be safe because run_forever does, in fact,
// run forever. The event loop window target doesn't get // run forever. The event loop window target doesn't get
@ -134,7 +139,7 @@ impl App {
let w = unsafe { let w = unsafe {
std::mem::transmute::< std::mem::transmute::<
&EventLoopWindowTarget<WakerEvent>, &EventLoopWindowTarget<WakerEvent>,
&'static EventLoopWindowTarget<WakerEvent> &'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)));
@ -150,21 +155,21 @@ impl App {
let window = window.clone(); let window = window.clone();
// Implements embedder methods, used by libservo and constellation. // Implements embedder methods, used by libservo and constellation.
let embedder = Box::new(EmbedderCallbacks::new( let embedder = Box::new(EmbedderCallbacks::new(ev_waker.clone(), xr_discovery));
ev_waker.clone(),
xr_discovery,
));
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.set_external_present(external_present); servo.set_external_present(external_present);
servo.handle_events(vec![EmbedderEvent::NewBrowser(initial_url.to_owned(), servo_data.browser_id)]); servo.handle_events(vec![EmbedderEvent::NewBrowser(
initial_url.to_owned(),
servo_data.browser_id,
)]);
servo.setup_logging(); servo.setup_logging();
app.windows.insert(window.id(), window.clone()); app.windows.insert(window.id(), window.clone());
app.servo = Some(servo); app.servo = Some(servo);
} },
winit::event::Event::RedrawRequested(_) => { winit::event::Event::RedrawRequested(_) => {
// We need to redraw the window for some reason. // We need to redraw the window for some reason.
@ -186,9 +191,9 @@ impl App {
// By default, the next RedrawRequested event will need to recomposite. // By default, the next RedrawRequested event will need to recomposite.
need_recomposite = true; need_recomposite = true;
} },
_ => {} _ => {},
} }
// If self.servo is None here, it means that we're in the process of shutting down, // If self.servo is None here, it means that we're in the process of shutting down,
@ -233,7 +238,8 @@ impl App {
if minibrowser.update_location_in_toolbar(browser) { if minibrowser.update_location_in_toolbar(browser) {
// Update the minibrowser immediately. While we could update by requesting a // Update the minibrowser immediately. While we could update by requesting a
// redraw, doing so would delay the location update by two frames. // redraw, doing so would delay the location update by two frames.
minibrowser.update(window.winit_window().unwrap(), "update_location_in_toolbar"); minibrowser
.update(window.winit_window().unwrap(), "update_location_in_toolbar");
} }
} }
@ -271,7 +277,7 @@ impl App {
if external_present { if external_present {
app.servo.as_mut().unwrap().present(); app.servo.as_mut().unwrap().present();
} }
} },
None => {}, None => {},
} }
}); });
@ -309,15 +315,13 @@ impl App {
// Window level events // Window level events
winit::event::Event::WindowEvent { winit::event::Event::WindowEvent {
window_id, event, .. window_id, event, ..
} => { } => match self.windows.get(&window_id) {
match self.windows.get(&window_id) {
None => { None => {
warn!("Got an event from unknown window"); warn!("Got an event from unknown window");
}, },
Some(window) => { Some(window) => {
window.queue_embedder_events_for_winit_event(event); window.queue_embedder_events_for_winit_event(event);
}, },
}
}, },
winit::event::Event::LoopDestroyed | winit::event::Event::LoopDestroyed |
@ -364,7 +368,11 @@ impl App {
// Route embedder events from the Browser to the relevant Servo components, // Route embedder events from the Browser to the relevant Servo components,
// receives and collects embedder messages from various Servo components, // receives and collects embedder messages from various Servo components,
// and runs the compositor. // 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 Some(PumpResult::Shutdown); return Some(PumpResult::Shutdown);
} }

View file

@ -9,9 +9,10 @@
//! FIXME: if/when a future version of the `backtrace` crate has //! FIXME: if/when a future version of the `backtrace` crate has
//! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead. //! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead.
use backtrace::{BytesOrWideString, PrintFmt};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use backtrace::{BytesOrWideString, PrintFmt};
#[inline(never)] #[inline(never)]
pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> { pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> {
write!( write!(

View file

@ -2,33 +2,32 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL}; use std::fs::File;
use crate::parser::sanitize_url; use std::io::Write;
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; use std::rc::Rc;
use std::time::Duration;
use std::{env, thread};
use arboard::Clipboard; use arboard::Clipboard;
use euclid::{Point2D, Vector2D}; use euclid::{Point2D, Vector2D};
use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher}; use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher};
use log::{error, debug, trace, warn, info}; use log::{debug, error, info, trace, warn};
use servo::compositing::windowing::{WebRenderDebugOption, EmbedderEvent}; use servo::compositing::windowing::{EmbedderEvent, WebRenderDebugOption};
use servo::embedder_traits::{ use servo::embedder_traits::{
ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest, ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest,
PromptDefinition, PromptOrigin, PromptResult, PromptDefinition, PromptOrigin, PromptResult,
}; };
use servo::msg::constellation_msg::TopLevelBrowsingContextId as BrowserId; use servo::msg::constellation_msg::{TopLevelBrowsingContextId as BrowserId, TraversalDirection};
use servo::msg::constellation_msg::TraversalDirection;
use servo::script_traits::TouchEventType; use servo::script_traits::TouchEventType;
use servo::servo_config::opts; use servo::servo_config::opts;
use servo::servo_url::ServoUrl; use servo::servo_url::ServoUrl;
use servo::webrender_api::ScrollLocation; use servo::webrender_api::ScrollLocation;
use std::env;
use std::fs::File;
use std::io::Write;
use std::rc::Rc;
use std::thread;
use std::time::Duration;
use tinyfiledialogs::{self, MessageBoxIcon, OkCancel, YesNo}; use tinyfiledialogs::{self, MessageBoxIcon, OkCancel, YesNo};
use crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL};
use crate::parser::sanitize_url;
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT};
pub struct Browser<Window: WindowPortsMethods + ?Sized> { pub struct Browser<Window: WindowPortsMethods + ?Sized> {
current_url: Option<ServoUrl>, current_url: Option<ServoUrl>,
current_url_string: Option<String>, current_url_string: Option<String>,
@ -282,7 +281,11 @@ where
pub fn handle_servo_events(&mut self, events: Vec<(Option<BrowserId>, EmbedderMsg)>) -> bool { pub fn handle_servo_events(&mut self, events: Vec<(Option<BrowserId>, EmbedderMsg)>) -> bool {
let mut need_present = false; let mut need_present = false;
for (browser_id, msg) in events { for (browser_id, msg) in events {
trace!("embedder <- servo EmbedderMsg ({:?}, {:?})", browser_id.map(|x| format!("{}", x)), msg); trace!(
"embedder <- servo EmbedderMsg ({:?}, {:?})",
browser_id.map(|x| format!("{}", x)),
msg
);
match msg { match msg {
EmbedderMsg::Status(_status) => { EmbedderMsg::Status(_status) => {
// FIXME: surface this status string in the UI somehow // FIXME: surface this status string in the UI somehow
@ -422,7 +425,8 @@ where
self.handle_key_from_servo(browser_id, key_event); self.handle_key_from_servo(browser_id, key_event);
}, },
EmbedderMsg::GetClipboardContents(sender) => { EmbedderMsg::GetClipboardContents(sender) => {
let contents = self.clipboard let contents = self
.clipboard
.as_mut() .as_mut()
.and_then(|clipboard| clipboard.get_text().ok()) .and_then(|clipboard| clipboard.get_text().ok())
.unwrap_or_else(|| { .unwrap_or_else(|| {
@ -482,7 +486,8 @@ 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(EmbedderEvent::SendError(None, reason)); self.event_queue
.push(EmbedderEvent::SendError(None, reason));
}; };
}, },
EmbedderMsg::SelectFiles(patterns, multiple_files, sender) => { EmbedderMsg::SelectFiles(patterns, multiple_files, sender) => {
@ -495,7 +500,8 @@ 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(EmbedderEvent::SendError(None, reason)); self.event_queue
.push(EmbedderEvent::SendError(None, reason));
}; };
}, },
EmbedderMsg::PromptPermission(prompt, sender) => { EmbedderMsg::PromptPermission(prompt, sender) => {

View file

@ -7,9 +7,13 @@ pub fn install() {}
#[cfg(any(target_os = "macos", target_os = "linux"))] #[cfg(any(target_os = "macos", target_os = "linux"))]
pub fn install() { pub fn install() {
use crate::backtrace; use std::io::Write;
use std::sync::atomic;
use std::thread;
use sig::ffi::Sig; use sig::ffi::Sig;
use std::{io::Write, sync::atomic, thread};
use crate::backtrace;
extern "C" fn handler(sig: i32) { extern "C" fn handler(sig: i32) {
// Only print crash message and backtrace the first time, to avoid // Only print crash message and backtrace the first time, to avoid

View file

@ -4,11 +4,11 @@
//! An event loop implementation that works in headless mode. //! An event loop implementation that works in headless mode.
use log::warn;
use servo::embedder_traits::EventLoopWaker;
use std::sync::{Arc, Condvar, Mutex}; use std::sync::{Arc, Condvar, Mutex};
use std::time; use std::time;
use log::warn;
use servo::embedder_traits::EventLoopWaker;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
@ -34,14 +34,18 @@ impl EventsLoop {
// but on Linux, the event loop requires a X11 server. // but on Linux, the event loop requires a X11 server.
#[cfg(not(any(target_os = "linux", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn new(_headless: bool, _has_output_file: bool) -> EventsLoop { pub fn new(_headless: bool, _has_output_file: bool) -> EventsLoop {
EventsLoop(EventLoop::Winit(Some(winit::event_loop::EventLoopBuilder::with_user_event().build()))) EventsLoop(EventLoop::Winit(Some(
winit::event_loop::EventLoopBuilder::with_user_event().build(),
)))
} }
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub fn new(headless: bool, _has_output_file: bool) -> EventsLoop { pub fn new(headless: bool, _has_output_file: bool) -> EventsLoop {
EventsLoop(if headless { EventsLoop(if headless {
EventLoop::Headless(Arc::new((Mutex::new(false), Condvar::new()))) EventLoop::Headless(Arc::new((Mutex::new(false), Condvar::new())))
} else { } else {
EventLoop::Winit(Some(winit::event_loop::EventLoopBuilder::with_user_event().build())) EventLoop::Winit(Some(
winit::event_loop::EventLoopBuilder::with_user_event().build(),
))
}) })
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -82,30 +86,27 @@ 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<'_, WakerEvent>, winit::event::Event<'_, WakerEvent>,
Option<&winit::event_loop::EventLoopWindowTarget<WakerEvent>>, Option<&winit::event_loop::EventLoopWindowTarget<WakerEvent>>,
&mut winit::event_loop::ControlFlow &mut winit::event_loop::ControlFlow,
) { ),
{
match self.0 { match self.0 {
EventLoop::Winit(events_loop) => { EventLoop::Winit(events_loop) => {
let events_loop = events_loop let events_loop = events_loop.expect("Can't run an unavailable event loop.");
.expect("Can't run an unavailable event loop.");
events_loop.run(move |e, window_target, ref mut control_flow| { events_loop.run(move |e, window_target, ref mut control_flow| {
callback(e, Some(window_target), control_flow) callback(e, Some(window_target), control_flow)
}); });
} },
EventLoop::Headless(ref data) => { EventLoop::Headless(ref data) => {
let (flag, condvar) = &**data; let (flag, condvar) = &**data;
let mut event = winit::event::Event::NewEvents(winit::event::StartCause::Init); let mut event = winit::event::Event::NewEvents(winit::event::StartCause::Init);
loop { loop {
self.sleep(flag, condvar); self.sleep(flag, condvar);
let mut control_flow = winit::event_loop::ControlFlow::Poll; let mut control_flow = winit::event_loop::ControlFlow::Poll;
callback( callback(event, None, &mut control_flow);
event,
None,
&mut control_flow
);
event = winit::event::Event::<WakerEvent>::UserEvent(WakerEvent); event = winit::event::Event::<WakerEvent>::UserEvent(WakerEvent);
if control_flow != winit::event_loop::ControlFlow::Poll { if control_flow != winit::event_loop::ControlFlow::Poll {

View file

@ -4,48 +4,44 @@
//! A winit window implementation. //! A winit window implementation.
use crate::events_loop::{EventsLoop, WakerEvent}; use std::cell::{Cell, RefCell};
use crate::keyutils::keyboard_event_from_winit; use std::collections::HashMap;
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; use std::rc::Rc;
use euclid::{
Angle, Point2D, Rotation3D, Scale, Size2D, UnknownUnit, use euclid::{Angle, Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector2D, Vector3D};
Vector2D, Vector3D, use log::{debug, info, trace};
};
use log::{trace, debug, info};
#[cfg(any(target_os = "linux", target_os = "windows"))]
use winit::window::Icon;
use winit::event::{ElementState, KeyboardInput, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode};
use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle};
use servo::keyboard_types::{Key, KeyState, KeyboardEvent}; use servo::compositing::windowing::{
use servo::compositing::windowing::{AnimationState, MouseWindowEvent, EmbedderEvent}; AnimationState, EmbedderCoordinates, EmbedderEvent, MouseWindowEvent, WindowMethods,
use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; };
use servo::embedder_traits::Cursor; use servo::embedder_traits::Cursor;
use servo::keyboard_types::{Key, KeyState, KeyboardEvent};
use servo::script_traits::{TouchEventType, WheelDelta, WheelMode}; use servo::script_traits::{TouchEventType, WheelDelta, WheelMode};
use servo::servo_config::opts; use servo::servo_config::{opts, pref};
use servo::servo_config::pref;
use servo::servo_geometry::DeviceIndependentPixel; use servo::servo_geometry::DeviceIndependentPixel;
use servo::style_traits::DevicePixel; use servo::style_traits::DevicePixel;
use servo::webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize}; use servo::webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};
use servo::webrender_api::ScrollLocation; use servo::webrender_api::ScrollLocation;
use servo::webrender_surfman::WebrenderSurfman; use servo::webrender_surfman::WebrenderSurfman;
use servo_media::player::context::{GlApi, GlContext as PlayerGLContext, NativeDisplay}; use servo_media::player::context::{GlApi, GlContext as PlayerGLContext, NativeDisplay};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
use surfman::platform::generic::multi::connection::NativeConnection; use surfman::platform::generic::multi::connection::NativeConnection;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
use surfman::platform::generic::multi::context::NativeContext; use surfman::platform::generic::multi::context::NativeContext;
use surfman::Connection; use surfman::{Connection, Context, Device, GLApi, GLVersion, SurfaceType};
use surfman::Context;
use surfman::Device;
use surfman::GLApi;
use surfman::GLVersion;
use surfman::SurfaceType;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
use winapi; use winapi;
use winit::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; use winit::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
use winit::event::ModifiersState; use winit::event::{
ElementState, KeyboardInput, ModifiersState, MouseButton, MouseScrollDelta, TouchPhase,
VirtualKeyCode,
};
#[cfg(any(target_os = "linux", target_os = "windows"))]
use winit::window::Icon;
use crate::events_loop::{EventsLoop, WakerEvent};
use crate::keyutils::keyboard_event_from_winit;
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT};
pub struct Window { pub struct Window {
winit_window: winit::window::Window, winit_window: winit::window::Window,
@ -107,7 +103,9 @@ impl Window {
.with_inner_size(PhysicalSize::new(width as f64, height as f64)) .with_inner_size(PhysicalSize::new(width as f64, height as f64))
.with_visible(visible); .with_visible(visible);
let winit_window = window_builder.build(events_loop.as_winit()).expect("Failed to create window."); let winit_window = window_builder
.build(events_loop.as_winit())
.expect("Failed to create window.");
#[cfg(any(target_os = "linux", target_os = "windows"))] #[cfg(any(target_os = "linux", target_os = "windows"))]
{ {
@ -115,7 +113,11 @@ impl Window {
winit_window.set_window_icon(Some(load_icon(icon_bytes))); winit_window.set_window_icon(Some(load_icon(icon_bytes)));
} }
let primary_monitor = events_loop.as_winit().available_monitors().nth(0).expect("No monitor detected"); let primary_monitor = events_loop
.as_winit()
.available_monitors()
.nth(0)
.expect("No monitor detected");
let PhysicalSize { let PhysicalSize {
width: screen_width, width: screen_width,
@ -127,8 +129,8 @@ impl Window {
// Initialize surfman // Initialize surfman
let display_handle = winit_window.raw_display_handle(); let display_handle = winit_window.raw_display_handle();
let connection = let connection = Connection::from_raw_display_handle(display_handle)
Connection::from_raw_display_handle(display_handle).expect("Failed to create connection"); .expect("Failed to create connection");
let adapter = connection let adapter = connection
.create_adapter() .create_adapter()
.expect("Failed to create adapter"); .expect("Failed to create adapter");
@ -310,9 +312,7 @@ impl WindowPortsMethods for Window {
fn page_height(&self) -> f32 { fn page_height(&self) -> f32 {
let dpr = self.servo_hidpi_factor(); let dpr = self.servo_hidpi_factor();
let size = self let size = self.winit_window.inner_size();
.winit_window
.inner_size();
size.height as f32 * dpr.get() size.height as f32 * dpr.get()
} }
@ -332,12 +332,13 @@ impl WindowPortsMethods for Window {
fn set_fullscreen(&self, state: bool) { fn set_fullscreen(&self, state: bool) {
if self.fullscreen.get() != state { if self.fullscreen.get() != state {
self.winit_window self.winit_window.set_fullscreen(if state {
.set_fullscreen( Some(winit::window::Fullscreen::Borderless(Some(
if state { self.primary_monitor.clone(),
Some(winit::window::Fullscreen::Borderless(Some(self.primary_monitor.clone()))) )))
} else { None } } else {
); None
});
} }
self.fullscreen.set(state); self.fullscreen.set(state);
} }
@ -400,7 +401,9 @@ impl WindowPortsMethods for Window {
fn queue_embedder_events_for_winit_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)
},
winit::event::WindowEvent::ModifiersChanged(state) => self.modifiers_state.set(state), winit::event::WindowEvent::ModifiersChanged(state) => self.modifiers_state.set(state),
winit::event::WindowEvent::MouseInput { state, button, .. } => { winit::event::WindowEvent::MouseInput { state, button, .. } => {
if button == MouseButton::Left || button == MouseButton::Right { if button == MouseButton::Left || button == MouseButton::Right {
@ -489,7 +492,7 @@ impl WindowPortsMethods for Window {
fn new_glwindow( fn new_glwindow(
&self, &self,
event_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent> 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();
@ -498,7 +501,8 @@ impl WindowPortsMethods for Window {
.with_inner_size(size) .with_inner_size(size)
.with_visible(true); .with_visible(true);
let winit_window = window_builder.build(event_loop) let winit_window = window_builder
.build(event_loop)
.expect("Failed to create window."); .expect("Failed to create window.");
let pose = Rc::new(XRWindowPose { let pose = Rc::new(XRWindowPose {
@ -523,9 +527,7 @@ impl WindowMethods for Window {
// Needed to convince the type system that winit's physical pixels // Needed to convince the type system that winit's physical pixels
// are actually device pixels. // are actually device pixels.
let dpr: Scale<f32, DeviceIndependentPixel, DevicePixel> = Scale::new(1.0); let dpr: Scale<f32, DeviceIndependentPixel, DevicePixel> = Scale::new(1.0);
let PhysicalSize { width, height } = self let PhysicalSize { width, height } = self.winit_window.outer_size();
.winit_window
.outer_size();
let PhysicalPosition { x, y } = self let PhysicalPosition { x, y } = self
.winit_window .winit_window
.outer_position() .outer_position()
@ -534,18 +536,14 @@ impl WindowMethods for Window {
let win_origin = (Point2D::new(x as f32, y as f32) * dpr).to_i32(); let win_origin = (Point2D::new(x as f32, y as f32) * dpr).to_i32();
let screen = (self.screen_size.to_f32() * dpr).to_i32(); let screen = (self.screen_size.to_f32() * dpr).to_i32();
let PhysicalSize { width, height } = self let PhysicalSize { width, height } = self.winit_window.inner_size();
.winit_window
.inner_size();
// Subtract the minibrowser toolbar height if any // Subtract the minibrowser toolbar height if any
let toolbar_height = self.toolbar_height.get(); let toolbar_height = self.toolbar_height.get();
let inner_size = Size2D::new(width as f32, height as f32) * dpr; let inner_size = Size2D::new(width as f32, height as f32) * dpr;
let viewport_size = inner_size - Size2D::new(0f32, toolbar_height); let viewport_size = inner_size - Size2D::new(0f32, toolbar_height);
let viewport_origin = DeviceIntPoint::zero(); // bottom left let viewport_origin = DeviceIntPoint::zero(); // bottom left
let viewport = DeviceIntRect::new( let viewport = DeviceIntRect::new(viewport_origin, viewport_size.to_i32());
viewport_origin, viewport_size.to_i32()
);
let framebuffer = DeviceIntSize::from_untyped(viewport.size.to_untyped()); let framebuffer = DeviceIntSize::from_untyped(viewport.size.to_untyped());
EmbedderCoordinates { EmbedderCoordinates {

View file

@ -4,23 +4,22 @@
//! A headless window implementation. //! A headless window implementation.
use crate::events_loop::WakerEvent; use std::cell::Cell;
use crate::window_trait::WindowPortsMethods; use std::rc::Rc;
use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D}; use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D};
use servo::compositing::windowing::{AnimationState, EmbedderEvent}; use servo::compositing::windowing::{
use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; AnimationState, EmbedderCoordinates, EmbedderEvent, WindowMethods,
};
use servo::servo_geometry::DeviceIndependentPixel; use servo::servo_geometry::DeviceIndependentPixel;
use servo::style_traits::DevicePixel; use servo::style_traits::DevicePixel;
use servo::webrender_api::units::DeviceIntRect; use servo::webrender_api::units::DeviceIntRect;
use servo::webrender_surfman::WebrenderSurfman; use servo::webrender_surfman::WebrenderSurfman;
use servo_media::player::context as MediaPlayerCtxt; use servo_media::player::context as MediaPlayerCtxt;
use std::cell::Cell; use surfman::{Connection, Context, Device, SurfaceType};
use std::rc::Rc;
use surfman::Connection;
use surfman::Context;
use surfman::Device;
use surfman::SurfaceType;
use crate::events_loop::WakerEvent;
use crate::window_trait::WindowPortsMethods;
pub struct Window { pub struct Window {
webrender_surfman: WebrenderSurfman, webrender_surfman: WebrenderSurfman,
@ -104,7 +103,7 @@ impl WindowPortsMethods for Window {
fn new_glwindow( fn new_glwindow(
&self, &self,
_events_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent> _events_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent>,
) -> Box<dyn webxr::glwindow::GlWindow> { ) -> Box<dyn webxr::glwindow::GlWindow> {
unimplemented!() unimplemented!()
} }

View file

@ -2,9 +2,9 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use keyboard_types::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
use log::info; use log::info;
use winit::event::{ElementState, KeyboardInput, ModifiersState, VirtualKeyCode}; use winit::event::{ElementState, KeyboardInput, ModifiersState, VirtualKeyCode};
use keyboard_types::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
// Some shortcuts use Cmd on Mac and Control on other systems. // Some shortcuts use Cmd on Mac and Control on other systems.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]

View file

@ -20,13 +20,52 @@
// mode is turned on. // mode is turned on.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[cfg(not(target_os = "android"))] cfg_if::cfg_if! {
include!("main2.rs"); if #[cfg(not(target_os = "android"))] {
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[macro_use]
extern crate sig;
#[cfg(target_os = "android")] #[cfg(test)]
mod test;
mod app;
mod backtrace;
mod browser;
mod crash_handler;
mod egui_glue;
mod embedder;
mod events_loop;
mod headed_window;
mod headless_window;
mod keyutils;
mod main2;
mod minibrowser;
mod parser;
mod prefs;
mod resources;
mod window_trait;
pub mod platform {
#[cfg(target_os = "macos")]
pub use crate::platform::macos::deinit;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(not(target_os = "macos"))]
pub fn deinit(_clean_shutdown: bool) {}
}
pub fn main() {
main2::main()
}
} else {
pub fn main() { pub fn main() {
println!( println!(
"Cannot start /ports/servo/ on Android. \ "Cannot start /ports/servo/ on Android. \
Use /support/android/apk/ + /ports/libsimpleservo/ instead" Use /support/android/apk/ + /ports/libsimpleservo/ instead"
); );
} }
}
}

View file

@ -2,55 +2,20 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[cfg(any(target_os = "macos", target_os = "linux"))] use std::io::Write;
#[macro_use] use std::{env, panic, process, thread};
extern crate sig;
#[cfg(test)]
mod test;
mod app;
mod backtrace;
mod browser;
mod crash_handler;
mod egui_glue;
mod embedder;
mod events_loop;
mod headed_window;
mod headless_window;
mod keyutils;
mod minibrowser;
mod parser;
mod prefs;
mod resources;
mod window_trait;
use app::App;
use getopts::Options; use getopts::Options;
use log::{error, warn};
use servo::config::opts::{self, ArgumentParsingResult}; use servo::config::opts::{self, ArgumentParsingResult};
use servo::servo_config::pref; use servo::servo_config::pref;
use std::env;
use std::io::Write;
use std::panic;
use std::process;
use std::thread;
use log::{warn,error};
pub mod platform { use crate::app::App;
#[cfg(target_os = "macos")]
pub use crate::platform::macos::deinit;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(not(target_os = "macos"))]
pub fn deinit(_clean_shutdown: bool) {}
}
pub fn main() { pub fn main() {
crash_handler::install(); crate::crash_handler::install();
resources::init(); crate::resources::init();
// Parse the command line options and store them globally // Parse the command line options and store them globally
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
@ -103,7 +68,7 @@ pub fn main() {
}, },
}; };
prefs::register_user_prefs(&opts_matches); crate::prefs::register_user_prefs(&opts_matches);
// TODO: once log-panics is released, can this be replaced by // TODO: once log-panics is released, can this be replaced by
// log_panics::init()? // log_panics::init()?
@ -133,7 +98,7 @@ pub fn main() {
let _ = writeln!(&mut stderr, "{} (thread {})", msg, name); let _ = writeln!(&mut stderr, "{} (thread {})", msg, name);
} }
if env::var("RUST_BACKTRACE").is_ok() { if env::var("RUST_BACKTRACE").is_ok() {
let _ = backtrace::print(&mut stderr); let _ = crate::backtrace::print(&mut stderr);
} }
drop(stderr); drop(stderr);
@ -171,11 +136,20 @@ pub fn main() {
None None
}; };
App::run(do_not_use_native_titlebar, device_pixels_per_px, user_agent, url_opt.map(|s| s.to_string())); App::run(
do_not_use_native_titlebar,
device_pixels_per_px,
user_agent,
url_opt.map(|s| s.to_string()),
);
platform::deinit(clean_shutdown) crate::platform::deinit(clean_shutdown)
} }
pub fn servo_version() -> String { pub fn servo_version() -> String {
format!("Servo {}-{}", env!("CARGO_PKG_VERSION"), env!("VERGEN_GIT_SHA")) format!(
"Servo {}-{}",
env!("CARGO_PKG_VERSION"),
env!("VERGEN_GIT_SHA")
)
} }

View file

@ -2,14 +2,20 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::{cell::{RefCell, Cell}, sync::Arc, time::Instant}; use std::cell::{Cell, RefCell};
use std::sync::Arc;
use std::time::Instant;
use egui::{TopBottomPanel, Modifiers, Key}; use egui::{Key, Modifiers, TopBottomPanel};
use log::{warn, trace}; use log::{trace, warn};
use servo::{servo_url::ServoUrl, compositing::windowing::EmbedderEvent}; use servo::compositing::windowing::EmbedderEvent;
use servo::servo_url::ServoUrl;
use servo::webrender_surfman::WebrenderSurfman; use servo::webrender_surfman::WebrenderSurfman;
use crate::{egui_glue::EguiGlow, events_loop::EventsLoop, browser::Browser, window_trait::WindowPortsMethods}; use crate::browser::Browser;
use crate::egui_glue::EguiGlow;
use crate::events_loop::EventsLoop;
use crate::window_trait::WindowPortsMethods;
pub struct Minibrowser { pub struct Minibrowser {
pub context: EguiGlow, pub context: EguiGlow,
@ -30,9 +36,7 @@ pub enum MinibrowserEvent {
impl Minibrowser { impl Minibrowser {
pub fn new(webrender_surfman: &WebrenderSurfman, events_loop: &EventsLoop) -> Self { pub fn new(webrender_surfman: &WebrenderSurfman, events_loop: &EventsLoop) -> Self {
let gl = unsafe { let gl = unsafe {
glow::Context::from_loader_function(|s| { glow::Context::from_loader_function(|s| webrender_surfman.get_proc_address(s))
webrender_surfman.get_proc_address(s)
})
}; };
Self { Self {
@ -48,8 +52,19 @@ impl Minibrowser {
/// Update the minibrowser, but dont paint. /// Update the minibrowser, but dont paint.
pub fn update(&mut self, window: &winit::window::Window, reason: &'static str) { pub fn update(&mut self, window: &winit::window::Window, reason: &'static str) {
let now = Instant::now(); let now = Instant::now();
trace!("{:?} since last update ({})", now - self.last_update, reason); trace!(
let Self { context, event_queue, toolbar_height, last_update, location, location_dirty } = self; "{:?} since last update ({})",
now - self.last_update,
reason
);
let Self {
context,
event_queue,
toolbar_height,
last_update,
location,
location_dirty,
} = self;
let _duration = context.run(window, |ctx| { let _duration = context.run(window, |ctx| {
TopBottomPanel::top("toolbar").show(ctx, |ui| { TopBottomPanel::top("toolbar").show(ctx, |ui| {
ui.allocate_ui_with_layout( ui.allocate_ui_with_layout(
@ -71,7 +86,9 @@ impl Minibrowser {
if ui.input(|i| i.clone().consume_key(Modifiers::COMMAND, Key::L)) { if ui.input(|i| i.clone().consume_key(Modifiers::COMMAND, Key::L)) {
location_field.request_focus(); location_field.request_focus();
} }
if location_field.lost_focus() && ui.input(|i| i.clone().key_pressed(Key::Enter)) { if location_field.lost_focus() &&
ui.input(|i| i.clone().key_pressed(Key::Enter))
{
event_queue.borrow_mut().push(MinibrowserEvent::Go); event_queue.borrow_mut().push(MinibrowserEvent::Go);
location_dirty.set(false); location_dirty.set(false);
} }
@ -92,7 +109,8 @@ impl Minibrowser {
/// Takes any outstanding events from the [Minibrowser], converting them to [EmbedderEvent] and /// Takes any outstanding events from the [Minibrowser], converting them to [EmbedderEvent] and
/// routing those to the App event queue. /// routing those to the App event queue.
pub fn queue_embedder_events_for_minibrowser_events( pub fn queue_embedder_events_for_minibrowser_events(
&self, browser: &Browser<dyn WindowPortsMethods>, &self,
browser: &Browser<dyn WindowPortsMethods>,
app_event_queue: &mut Vec<EmbedderEvent>, app_event_queue: &mut Vec<EmbedderEvent>,
) { ) {
for event in self.event_queue.borrow_mut().drain(..) { for event in self.event_queue.borrow_mut().drain(..) {
@ -112,7 +130,10 @@ impl Minibrowser {
/// Updates the location field from the given [Browser], unless the user has started editing it /// Updates the location field from the given [Browser], unless the user has started editing it
/// without clicking Go, returning true iff the location has changed (needing an egui update). /// without clicking Go, returning true iff the location has changed (needing an egui update).
pub fn update_location_in_toolbar(&mut self, browser: &mut Browser<dyn WindowPortsMethods>) -> bool { pub fn update_location_in_toolbar(
&mut self,
browser: &mut Browser<dyn WindowPortsMethods>,
) -> bool {
// User edited without clicking Go? // User edited without clicking Go?
if self.location_dirty.get() { if self.location_dirty.get() {
return false; return false;

View file

@ -4,6 +4,7 @@
use std::env; use std::env;
use std::path::Path; use std::path::Path;
use log::warn; use log::warn;
use servo::net_traits::pub_domains::is_reg_domain; use servo::net_traits::pub_domains::is_reg_domain;
use servo::servo_config::pref; use servo::servo_config::pref;

View file

@ -2,9 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::ptr;
use std::thread;
use std::time::Duration; use std::time::Duration;
use std::{ptr, thread};
pub fn deinit(clean_shutdown: bool) { pub fn deinit(clean_shutdown: bool) {
// An unfortunate hack to make sure the linker's dead code stripping doesn't strip our // An unfortunate hack to make sure the linker's dead code stripping doesn't strip our

View file

@ -2,14 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use getopts::{Matches, Options}; use getopts::{Matches, Options};
use servo::config::opts::{self, ArgumentParsingResult}; use servo::config::opts::{self, ArgumentParsingResult};
use servo::config::prefs::{self, PrefValue}; use servo::config::prefs::{self, PrefValue};
use servo::embedder_traits; use servo::embedder_traits;
use servo::servo_config::basedir; use servo::servo_config::basedir;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
pub fn register_user_prefs(opts_matches: &Matches) { pub fn register_user_prefs(opts_matches: &Matches) {
// Read user's prefs.json and then parse --pref command line args. // Read user's prefs.json and then parse --pref command line args.

View file

@ -2,12 +2,11 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use servo::embedder_traits::resources::{self, Resource};
use std::env;
use std::fs;
use std::io;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Mutex; use std::sync::Mutex;
use std::{env, fs, io};
use servo::embedder_traits::resources::{self, Resource};
lazy_static::lazy_static! { lazy_static::lazy_static! {
static ref CMD_RESOURCE_DIR: Mutex<Option<String>> = Mutex::new(None); static ref CMD_RESOURCE_DIR: Mutex<Option<String>> = Mutex::new(None);

View file

@ -3,6 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::path::Path; use std::path::Path;
use crate::parser::parse_url_or_filename; use crate::parser::parse_url_or_filename;
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]

View file

@ -5,11 +5,11 @@
//! Definition of Window. //! Definition of Window.
//! Implemented by headless and headed windows. //! Implemented by headless and headed windows.
use crate::events_loop::WakerEvent;
use servo::compositing::windowing::{EmbedderEvent, 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};
use crate::events_loop::WakerEvent;
// This should vary by zoom level and maybe actual text size (focused or under cursor) // This should vary by zoom level and maybe actual text size (focused or under cursor)
pub const LINE_HEIGHT: f32 = 38.0; pub const LINE_HEIGHT: f32 = 38.0;
@ -29,7 +29,7 @@ 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<WakerEvent> events_loop: &winit::event_loop::EventLoopWindowTarget<WakerEvent>,
) -> Box<dyn webxr::glwindow::GlWindow>; ) -> Box<dyn webxr::glwindow::GlWindow>;
fn winit_window(&self) -> Option<&winit::window::Window>; fn winit_window(&self) -> Option<&winit::window::Window>;
fn set_toolbar_height(&self, height: f32); fn set_toolbar_height(&self, height: f32);