From 90ad5920e2e518422ad7248fca7e5191b475600c Mon Sep 17 00:00:00 2001 From: Delan Azabani Date: Tue, 12 Sep 2023 14:27:10 +0800 Subject: [PATCH] [NFC] servoshell: fix rust-analyzer and rustfmt breakage (#30340) --- Cargo.lock | 1 + Cargo.toml | 1 + ports/servoshell/Cargo.toml | 1 + ports/servoshell/app.rs | 82 +++++++++++--------- ports/servoshell/backtrace.rs | 3 +- ports/servoshell/browser.rs | 42 ++++++----- ports/servoshell/crash_handler.rs | 8 +- ports/servoshell/events_loop.rs | 35 ++++----- ports/servoshell/headed_window.rs | 100 ++++++++++++------------- ports/servoshell/headless_window.rs | 21 +++--- ports/servoshell/keyutils.rs | 2 +- ports/servoshell/main.rs | 55 ++++++++++++-- ports/servoshell/main2.rs | 66 +++++----------- ports/servoshell/minibrowser.rs | 47 ++++++++---- ports/servoshell/parser.rs | 1 + ports/servoshell/platform/macos/mod.rs | 3 +- ports/servoshell/prefs.rs | 7 +- ports/servoshell/resources.rs | 7 +- ports/servoshell/test.rs | 1 + ports/servoshell/window_trait.rs | 4 +- 20 files changed, 271 insertions(+), 216 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 578f1ce9b5d..e3b2a4f886c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5483,6 +5483,7 @@ dependencies = [ "arboard", "backtrace", "cc", + "cfg-if 1.0.0", "egui", "egui-winit", "egui_glow", diff --git a/Cargo.toml b/Cargo.toml index 0d2ddc74f10..9a2157cd63d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ backtrace = "0.3" base64 = "0.21.3" bitflags = "2.4" byteorder = "1.0" +cfg-if = "1.0.0" encoding_rs = "0.8" euclid = "0.22" cookie = "0.12" diff --git a/ports/servoshell/Cargo.toml b/ports/servoshell/Cargo.toml index d1d4ded25fc..8dcf51e5a8c 100644 --- a/ports/servoshell/Cargo.toml +++ b/ports/servoshell/Cargo.toml @@ -46,6 +46,7 @@ xr-profile = ["libservo/xr-profile"] [target.'cfg(not(target_os = "android"))'.dependencies] arboard = "3" backtrace = { workspace = true } +cfg-if = { workspace = true } egui = "0.22.0" egui_glow = { version = "0.22.0", features = ["winit"] } egui-winit = { version = "0.22.0", default-features = false, features = ["clipboard", "wayland"] } diff --git a/ports/servoshell/app.rs b/ports/servoshell/app.rs index 38463e41bc4..8094ac01e98 100644 --- a/ports/servoshell/app.rs +++ b/ports/servoshell/app.rs @@ -4,6 +4,22 @@ //! 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::embedder::EmbedderCallbacks; use crate::events_loop::{EventsLoop, WakerEvent}; @@ -11,20 +27,6 @@ use crate::minibrowser::Minibrowser; use crate::parser::get_default_url; use crate::window_trait::WindowPortsMethods; 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 { servo: Option>, @@ -80,7 +82,9 @@ impl App { // Make sure the gl context is made current. let webrender_surfman = window.webrender_surfman(); 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 { 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) => { 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(); // This should be safe because run_forever does, in fact, // run forever. The event loop window target doesn't get @@ -134,7 +139,7 @@ impl App { let w = unsafe { std::mem::transmute::< &EventLoopWindowTarget, - &'static EventLoopWindowTarget + &'static EventLoopWindowTarget, >(w.unwrap()) }; let factory = Box::new(move || Ok(window.new_glwindow(w))); @@ -150,21 +155,21 @@ impl App { let window = window.clone(); // Implements embedder methods, used by libservo and constellation. - let embedder = Box::new(EmbedderCallbacks::new( - ev_waker.clone(), - xr_discovery, - )); + let embedder = Box::new(EmbedderCallbacks::new(ev_waker.clone(), xr_discovery)); let servo_data = Servo::new(embedder, window.clone(), user_agent.clone()); let mut servo = servo_data.servo; 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(); app.windows.insert(window.id(), window.clone()); app.servo = Some(servo); - } + }, winit::event::Event::RedrawRequested(_) => { // 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. need_recomposite = true; - } + }, - _ => {} + _ => {}, } // 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) { // Update the minibrowser immediately. While we could update by requesting a // 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 { app.servo.as_mut().unwrap().present(); } - } + }, None => {}, } }); @@ -309,15 +315,13 @@ impl App { // Window level events winit::event::Event::WindowEvent { window_id, event, .. - } => { - match self.windows.get(&window_id) { - None => { - warn!("Got an event from unknown window"); - }, - Some(window) => { - window.queue_embedder_events_for_winit_event(event); - }, - } + } => match self.windows.get(&window_id) { + None => { + warn!("Got an event from unknown window"); + }, + Some(window) => { + window.queue_embedder_events_for_winit_event(event); + }, }, winit::event::Event::LoopDestroyed | @@ -364,7 +368,11 @@ impl App { // 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() { return Some(PumpResult::Shutdown); } diff --git a/ports/servoshell/backtrace.rs b/ports/servoshell/backtrace.rs index fff4db5b103..44feb32b2e7 100644 --- a/ports/servoshell/backtrace.rs +++ b/ports/servoshell/backtrace.rs @@ -9,9 +9,10 @@ //! FIXME: if/when a future version of the `backtrace` crate has //! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead. -use backtrace::{BytesOrWideString, PrintFmt}; use std::fmt::{self, Write}; +use backtrace::{BytesOrWideString, PrintFmt}; + #[inline(never)] pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> { write!( diff --git a/ports/servoshell/browser.rs b/ports/servoshell/browser.rs index 184cf031cc1..752d194bd64 100644 --- a/ports/servoshell/browser.rs +++ b/ports/servoshell/browser.rs @@ -2,33 +2,32 @@ * 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/. */ -use crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL}; -use crate::parser::sanitize_url; -use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; +use std::fs::File; +use std::io::Write; +use std::rc::Rc; +use std::time::Duration; +use std::{env, thread}; + use arboard::Clipboard; use euclid::{Point2D, Vector2D}; use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher}; -use log::{error, debug, trace, warn, info}; -use servo::compositing::windowing::{WebRenderDebugOption, EmbedderEvent}; +use log::{debug, error, info, trace, warn}; +use servo::compositing::windowing::{EmbedderEvent, WebRenderDebugOption}; use servo::embedder_traits::{ ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest, PromptDefinition, PromptOrigin, PromptResult, }; -use servo::msg::constellation_msg::TopLevelBrowsingContextId as BrowserId; -use servo::msg::constellation_msg::TraversalDirection; +use servo::msg::constellation_msg::{TopLevelBrowsingContextId as BrowserId, TraversalDirection}; use servo::script_traits::TouchEventType; use servo::servo_config::opts; use servo::servo_url::ServoUrl; 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 crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL}; +use crate::parser::sanitize_url; +use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; + pub struct Browser { current_url: Option, current_url_string: Option, @@ -282,7 +281,11 @@ where pub fn handle_servo_events(&mut self, events: Vec<(Option, EmbedderMsg)>) -> bool { let mut need_present = false; 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 { EmbedderMsg::Status(_status) => { // FIXME: surface this status string in the UI somehow @@ -422,7 +425,8 @@ where self.handle_key_from_servo(browser_id, key_event); }, EmbedderMsg::GetClipboardContents(sender) => { - let contents = self.clipboard + let contents = self + .clipboard .as_mut() .and_then(|clipboard| clipboard.get_text().ok()) .unwrap_or_else(|| { @@ -482,7 +486,8 @@ where if let Err(e) = sender.send(selected) { let reason = 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) => { @@ -495,7 +500,8 @@ where }; if let Err(e) = res { 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) => { diff --git a/ports/servoshell/crash_handler.rs b/ports/servoshell/crash_handler.rs index 1420c2f173f..3dd6aa86604 100644 --- a/ports/servoshell/crash_handler.rs +++ b/ports/servoshell/crash_handler.rs @@ -7,9 +7,13 @@ pub fn install() {} #[cfg(any(target_os = "macos", target_os = "linux"))] pub fn install() { - use crate::backtrace; + use std::io::Write; + use std::sync::atomic; + use std::thread; + use sig::ffi::Sig; - use std::{io::Write, sync::atomic, thread}; + + use crate::backtrace; extern "C" fn handler(sig: i32) { // Only print crash message and backtrace the first time, to avoid diff --git a/ports/servoshell/events_loop.rs b/ports/servoshell/events_loop.rs index c9bc35753ce..2a3c76629ba 100644 --- a/ports/servoshell/events_loop.rs +++ b/ports/servoshell/events_loop.rs @@ -4,11 +4,11 @@ //! 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::time; +use log::warn; +use servo::embedder_traits::EventLoopWaker; #[cfg(target_os = "macos")] use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; @@ -34,14 +34,18 @@ impl EventsLoop { // but on Linux, the event loop requires a X11 server. #[cfg(not(any(target_os = "linux", target_os = "macos")))] 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")] pub fn new(headless: bool, _has_output_file: bool) -> EventsLoop { EventsLoop(if headless { EventLoop::Headless(Arc::new((Mutex::new(false), Condvar::new()))) } 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")] @@ -82,30 +86,27 @@ impl EventsLoop { } pub fn run_forever(self, mut callback: F) - where F: FnMut( - winit::event::Event<'_, WakerEvent>, - Option<&winit::event_loop::EventLoopWindowTarget>, - &mut winit::event_loop::ControlFlow - ) { + where + F: FnMut( + winit::event::Event<'_, WakerEvent>, + Option<&winit::event_loop::EventLoopWindowTarget>, + &mut winit::event_loop::ControlFlow, + ), + { match self.0 { EventLoop::Winit(events_loop) => { - let events_loop = events_loop - .expect("Can't run an unavailable event loop."); + let events_loop = events_loop.expect("Can't run an unavailable event loop."); events_loop.run(move |e, window_target, ref mut control_flow| { callback(e, Some(window_target), control_flow) }); - } + }, EventLoop::Headless(ref data) => { let (flag, condvar) = &**data; let mut event = winit::event::Event::NewEvents(winit::event::StartCause::Init); loop { self.sleep(flag, condvar); let mut control_flow = winit::event_loop::ControlFlow::Poll; - callback( - event, - None, - &mut control_flow - ); + callback(event, None, &mut control_flow); event = winit::event::Event::::UserEvent(WakerEvent); if control_flow != winit::event_loop::ControlFlow::Poll { diff --git a/ports/servoshell/headed_window.rs b/ports/servoshell/headed_window.rs index 1e91459d3d5..e00cbf0dd1d 100644 --- a/ports/servoshell/headed_window.rs +++ b/ports/servoshell/headed_window.rs @@ -4,48 +4,44 @@ //! A winit window implementation. -use crate::events_loop::{EventsLoop, WakerEvent}; -use crate::keyutils::keyboard_event_from_winit; -use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; -use euclid::{ - Angle, Point2D, Rotation3D, Scale, Size2D, UnknownUnit, - Vector2D, Vector3D, -}; -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 std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::rc::Rc; + +use euclid::{Angle, Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector2D, Vector3D}; +use log::{debug, info, trace}; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; -use servo::keyboard_types::{Key, KeyState, KeyboardEvent}; -use servo::compositing::windowing::{AnimationState, MouseWindowEvent, EmbedderEvent}; -use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; +use servo::compositing::windowing::{ + AnimationState, EmbedderCoordinates, EmbedderEvent, MouseWindowEvent, WindowMethods, +}; use servo::embedder_traits::Cursor; +use servo::keyboard_types::{Key, KeyState, KeyboardEvent}; use servo::script_traits::{TouchEventType, WheelDelta, WheelMode}; -use servo::servo_config::opts; -use servo::servo_config::pref; +use servo::servo_config::{opts, pref}; use servo::servo_geometry::DeviceIndependentPixel; use servo::style_traits::DevicePixel; use servo::webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize}; use servo::webrender_api::ScrollLocation; use servo::webrender_surfman::WebrenderSurfman; 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")] use surfman::platform::generic::multi::connection::NativeConnection; #[cfg(target_os = "linux")] use surfman::platform::generic::multi::context::NativeContext; -use surfman::Connection; -use surfman::Context; -use surfman::Device; -use surfman::GLApi; -use surfman::GLVersion; -use surfman::SurfaceType; +use surfman::{Connection, Context, Device, GLApi, GLVersion, SurfaceType}; #[cfg(target_os = "windows")] use winapi; 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 { winit_window: winit::window::Window, @@ -107,7 +103,9 @@ impl Window { .with_inner_size(PhysicalSize::new(width as f64, height as f64)) .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"))] { @@ -115,7 +113,11 @@ impl Window { 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 { width: screen_width, @@ -127,8 +129,8 @@ impl Window { // Initialize surfman let display_handle = winit_window.raw_display_handle(); - let connection = - Connection::from_raw_display_handle(display_handle).expect("Failed to create connection"); + let connection = Connection::from_raw_display_handle(display_handle) + .expect("Failed to create connection"); let adapter = connection .create_adapter() .expect("Failed to create adapter"); @@ -310,9 +312,7 @@ impl WindowPortsMethods for Window { fn page_height(&self) -> f32 { let dpr = self.servo_hidpi_factor(); - let size = self - .winit_window - .inner_size(); + let size = self.winit_window.inner_size(); size.height as f32 * dpr.get() } @@ -332,12 +332,13 @@ impl WindowPortsMethods for Window { fn set_fullscreen(&self, state: bool) { if self.fullscreen.get() != state { - self.winit_window - .set_fullscreen( - if state { - Some(winit::window::Fullscreen::Borderless(Some(self.primary_monitor.clone()))) - } else { None } - ); + self.winit_window.set_fullscreen(if state { + Some(winit::window::Fullscreen::Borderless(Some( + self.primary_monitor.clone(), + ))) + } else { + None + }); } self.fullscreen.set(state); } @@ -400,7 +401,9 @@ impl WindowPortsMethods for Window { fn queue_embedder_events_for_winit_event(&self, event: winit::event::WindowEvent<'_>) { match event { 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::MouseInput { state, button, .. } => { if button == MouseButton::Left || button == MouseButton::Right { @@ -489,7 +492,7 @@ impl WindowPortsMethods for Window { fn new_glwindow( &self, - event_loop: &winit::event_loop::EventLoopWindowTarget + event_loop: &winit::event_loop::EventLoopWindowTarget, ) -> Box { let size = self.winit_window.outer_size(); @@ -498,7 +501,8 @@ impl WindowPortsMethods for Window { .with_inner_size(size) .with_visible(true); - let winit_window = window_builder.build(event_loop) + let winit_window = window_builder + .build(event_loop) .expect("Failed to create window."); let pose = Rc::new(XRWindowPose { @@ -523,9 +527,7 @@ impl WindowMethods for Window { // Needed to convince the type system that winit's physical pixels // are actually device pixels. let dpr: Scale = Scale::new(1.0); - let PhysicalSize { width, height } = self - .winit_window - .outer_size(); + let PhysicalSize { width, height } = self.winit_window.outer_size(); let PhysicalPosition { x, y } = self .winit_window .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 screen = (self.screen_size.to_f32() * dpr).to_i32(); - let PhysicalSize { width, height } = self - .winit_window - .inner_size(); + let PhysicalSize { width, height } = self.winit_window.inner_size(); // Subtract the minibrowser toolbar height if any let toolbar_height = self.toolbar_height.get(); let inner_size = Size2D::new(width as f32, height as f32) * dpr; let viewport_size = inner_size - Size2D::new(0f32, toolbar_height); let viewport_origin = DeviceIntPoint::zero(); // bottom left - let viewport = DeviceIntRect::new( - viewport_origin, viewport_size.to_i32() - ); + let viewport = DeviceIntRect::new(viewport_origin, viewport_size.to_i32()); let framebuffer = DeviceIntSize::from_untyped(viewport.size.to_untyped()); EmbedderCoordinates { diff --git a/ports/servoshell/headless_window.rs b/ports/servoshell/headless_window.rs index ad8d29011fd..54058f55cae 100644 --- a/ports/servoshell/headless_window.rs +++ b/ports/servoshell/headless_window.rs @@ -4,23 +4,22 @@ //! A headless window implementation. -use crate::events_loop::WakerEvent; -use crate::window_trait::WindowPortsMethods; +use std::cell::Cell; +use std::rc::Rc; + use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D}; -use servo::compositing::windowing::{AnimationState, EmbedderEvent}; -use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; +use servo::compositing::windowing::{ + AnimationState, EmbedderCoordinates, EmbedderEvent, WindowMethods, +}; use servo::servo_geometry::DeviceIndependentPixel; use servo::style_traits::DevicePixel; use servo::webrender_api::units::DeviceIntRect; use servo::webrender_surfman::WebrenderSurfman; use servo_media::player::context as MediaPlayerCtxt; -use std::cell::Cell; -use std::rc::Rc; -use surfman::Connection; -use surfman::Context; -use surfman::Device; -use surfman::SurfaceType; +use surfman::{Connection, Context, Device, SurfaceType}; +use crate::events_loop::WakerEvent; +use crate::window_trait::WindowPortsMethods; pub struct Window { webrender_surfman: WebrenderSurfman, @@ -104,7 +103,7 @@ impl WindowPortsMethods for Window { fn new_glwindow( &self, - _events_loop: &winit::event_loop::EventLoopWindowTarget + _events_loop: &winit::event_loop::EventLoopWindowTarget, ) -> Box { unimplemented!() } diff --git a/ports/servoshell/keyutils.rs b/ports/servoshell/keyutils.rs index 2586929b3bc..ef8800078be 100644 --- a/ports/servoshell/keyutils.rs +++ b/ports/servoshell/keyutils.rs @@ -2,9 +2,9 @@ * 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/. */ +use keyboard_types::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers}; use log::info; 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. #[cfg(target_os = "macos")] diff --git a/ports/servoshell/main.rs b/ports/servoshell/main.rs index 50c00307a0d..f252cdb3ef2 100644 --- a/ports/servoshell/main.rs +++ b/ports/servoshell/main.rs @@ -20,13 +20,52 @@ // mode is turned on. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] -#[cfg(not(target_os = "android"))] -include!("main2.rs"); +cfg_if::cfg_if! { + if #[cfg(not(target_os = "android"))] { + #[cfg(any(target_os = "macos", target_os = "linux"))] + #[macro_use] + extern crate sig; -#[cfg(target_os = "android")] -pub fn main() { - println!( - "Cannot start /ports/servo/ on Android. \ - Use /support/android/apk/ + /ports/libsimpleservo/ instead" - ); + #[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() { + println!( + "Cannot start /ports/servo/ on Android. \ + Use /support/android/apk/ + /ports/libsimpleservo/ instead" + ); + } + } } diff --git a/ports/servoshell/main2.rs b/ports/servoshell/main2.rs index df654c22bea..25404277f56 100644 --- a/ports/servoshell/main2.rs +++ b/ports/servoshell/main2.rs @@ -2,55 +2,20 @@ * 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/. */ -#[cfg(any(target_os = "macos", target_os = "linux"))] -#[macro_use] -extern crate sig; +use std::io::Write; +use std::{env, panic, process, thread}; -#[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 log::{error, warn}; use servo::config::opts::{self, ArgumentParsingResult}; 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 { - #[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) {} -} +use crate::app::App; pub fn main() { - crash_handler::install(); + crate::crash_handler::install(); - resources::init(); + crate::resources::init(); // Parse the command line options and store them globally let args: Vec = 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 // log_panics::init()? @@ -133,7 +98,7 @@ pub fn main() { let _ = writeln!(&mut stderr, "{} (thread {})", msg, name); } if env::var("RUST_BACKTRACE").is_ok() { - let _ = backtrace::print(&mut stderr); + let _ = crate::backtrace::print(&mut stderr); } drop(stderr); @@ -171,11 +136,20 @@ pub fn main() { 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 { - format!("Servo {}-{}", env!("CARGO_PKG_VERSION"), env!("VERGEN_GIT_SHA")) + format!( + "Servo {}-{}", + env!("CARGO_PKG_VERSION"), + env!("VERGEN_GIT_SHA") + ) } diff --git a/ports/servoshell/minibrowser.rs b/ports/servoshell/minibrowser.rs index bc8f741514b..0bf22d77587 100644 --- a/ports/servoshell/minibrowser.rs +++ b/ports/servoshell/minibrowser.rs @@ -2,14 +2,20 @@ * 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/. */ - 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 log::{warn, trace}; -use servo::{servo_url::ServoUrl, compositing::windowing::EmbedderEvent}; +use egui::{Key, Modifiers, TopBottomPanel}; +use log::{trace, warn}; +use servo::compositing::windowing::EmbedderEvent; +use servo::servo_url::ServoUrl; 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 context: EguiGlow, @@ -30,9 +36,7 @@ pub enum MinibrowserEvent { impl Minibrowser { pub fn new(webrender_surfman: &WebrenderSurfman, events_loop: &EventsLoop) -> Self { let gl = unsafe { - glow::Context::from_loader_function(|s| { - webrender_surfman.get_proc_address(s) - }) + glow::Context::from_loader_function(|s| webrender_surfman.get_proc_address(s)) }; Self { @@ -48,8 +52,19 @@ impl Minibrowser { /// Update the minibrowser, but don’t paint. pub fn update(&mut self, window: &winit::window::Window, reason: &'static str) { let now = Instant::now(); - trace!("{:?} since last update ({})", now - self.last_update, reason); - let Self { context, event_queue, toolbar_height, last_update, location, location_dirty } = self; + trace!( + "{:?} 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| { TopBottomPanel::top("toolbar").show(ctx, |ui| { ui.allocate_ui_with_layout( @@ -71,7 +86,9 @@ impl Minibrowser { if ui.input(|i| i.clone().consume_key(Modifiers::COMMAND, Key::L)) { 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); location_dirty.set(false); } @@ -92,7 +109,8 @@ impl Minibrowser { /// Takes any outstanding events from the [Minibrowser], converting them to [EmbedderEvent] and /// routing those to the App event queue. pub fn queue_embedder_events_for_minibrowser_events( - &self, browser: &Browser, + &self, + browser: &Browser, app_event_queue: &mut Vec, ) { 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 /// 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) -> bool { + pub fn update_location_in_toolbar( + &mut self, + browser: &mut Browser, + ) -> bool { // User edited without clicking Go? if self.location_dirty.get() { return false; diff --git a/ports/servoshell/parser.rs b/ports/servoshell/parser.rs index 002370747b2..95333d7cb89 100644 --- a/ports/servoshell/parser.rs +++ b/ports/servoshell/parser.rs @@ -4,6 +4,7 @@ use std::env; use std::path::Path; + use log::warn; use servo::net_traits::pub_domains::is_reg_domain; use servo::servo_config::pref; diff --git a/ports/servoshell/platform/macos/mod.rs b/ports/servoshell/platform/macos/mod.rs index d9d14bb9ee8..2c019d20de3 100644 --- a/ports/servoshell/platform/macos/mod.rs +++ b/ports/servoshell/platform/macos/mod.rs @@ -2,9 +2,8 @@ * 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/. */ -use std::ptr; -use std::thread; use std::time::Duration; +use std::{ptr, thread}; pub fn deinit(clean_shutdown: bool) { // An unfortunate hack to make sure the linker's dead code stripping doesn't strip our diff --git a/ports/servoshell/prefs.rs b/ports/servoshell/prefs.rs index 2a82320ca5a..0448850794d 100644 --- a/ports/servoshell/prefs.rs +++ b/ports/servoshell/prefs.rs @@ -2,14 +2,15 @@ * 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/. */ +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; + use getopts::{Matches, Options}; use servo::config::opts::{self, ArgumentParsingResult}; use servo::config::prefs::{self, PrefValue}; use servo::embedder_traits; 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) { // Read user's prefs.json and then parse --pref command line args. diff --git a/ports/servoshell/resources.rs b/ports/servoshell/resources.rs index 0a859ba3950..91ad584c26d 100644 --- a/ports/servoshell/resources.rs +++ b/ports/servoshell/resources.rs @@ -2,12 +2,11 @@ * 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/. */ -use servo::embedder_traits::resources::{self, Resource}; -use std::env; -use std::fs; -use std::io; use std::path::PathBuf; use std::sync::Mutex; +use std::{env, fs, io}; + +use servo::embedder_traits::resources::{self, Resource}; lazy_static::lazy_static! { static ref CMD_RESOURCE_DIR: Mutex> = Mutex::new(None); diff --git a/ports/servoshell/test.rs b/ports/servoshell/test.rs index 7c22d06d1ff..0f870fec995 100644 --- a/ports/servoshell/test.rs +++ b/ports/servoshell/test.rs @@ -3,6 +3,7 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use std::path::Path; + use crate::parser::parse_url_or_filename; #[cfg(not(target_os = "windows"))] diff --git a/ports/servoshell/window_trait.rs b/ports/servoshell/window_trait.rs index 8f780735c23..60f988291d0 100644 --- a/ports/servoshell/window_trait.rs +++ b/ports/servoshell/window_trait.rs @@ -5,11 +5,11 @@ //! Definition of Window. //! Implemented by headless and headed windows. -use crate::events_loop::WakerEvent; use servo::compositing::windowing::{EmbedderEvent, WindowMethods}; use servo::embedder_traits::Cursor; 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) pub const LINE_HEIGHT: f32 = 38.0; @@ -29,7 +29,7 @@ pub trait WindowPortsMethods: WindowMethods { fn set_cursor(&self, _cursor: Cursor) {} fn new_glwindow( &self, - events_loop: &winit::event_loop::EventLoopWindowTarget + events_loop: &winit::event_loop::EventLoopWindowTarget, ) -> Box; fn winit_window(&self) -> Option<&winit::window::Window>; fn set_toolbar_height(&self, height: f32);