diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index 7d23d81bcf0..86aa97466a7 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.rs @@ -467,7 +467,7 @@ impl<'a> Iterator for &'a TreeWalker { // which cannot produce an Err result. { unreachable!() - }, + } } } } diff --git a/components/script/lib.rs b/components/script/lib.rs index e1a07583cdd..86935833157 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -4,6 +4,7 @@ #![feature(assoc_char_funcs)] #![feature(const_fn)] +#![feature(const_fn_fn_ptr_basics)] #![feature(core_intrinsics)] #![feature(drain_filter)] #![feature(plugin)] diff --git a/components/script_plugins/lib.rs b/components/script_plugins/lib.rs index 5259366c7fd..211b6117781 100644 --- a/components/script_plugins/lib.rs +++ b/components/script_plugins/lib.rs @@ -90,7 +90,7 @@ fn has_lint_attr(sym: &Symbols, attrs: &[Attribute], name: Symbol) -> bool { attrs.iter().any(|attr| { matches!( &attr.kind, - AttrKind::Normal(attr_item) + AttrKind::Normal(attr_item, _) if attr_item.path.segments.len() == 2 && attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint && attr_item.path.segments[1].ident.name == name diff --git a/components/style/gecko/selector_parser.rs b/components/style/gecko/selector_parser.rs index fd0494fa4b4..64e62badf3b 100644 --- a/components/style/gecko/selector_parser.rs +++ b/components/style/gecko/selector_parser.rs @@ -198,11 +198,12 @@ impl NonTSPseudoClass { /// revalidation. pub fn needs_cache_revalidation(&self) -> bool { self.state_flag().is_empty() && - !matches!(*self, - // :-moz-any is handled by the revalidation visitor walking - // the things inside it; it does not need to cause - // revalidation on its own. - NonTSPseudoClass::MozAny(_) | + !matches!( + *self, + // :-moz-any is handled by the revalidation visitor walking + // the things inside it; it does not need to cause + // revalidation on its own. + NonTSPseudoClass::MozAny(_) | // :dir() depends on state only, but doesn't use state_flag // because its semantics don't quite match. Nevertheless, it // doesn't need cache revalidation, because we already compare diff --git a/components/style/servo/selector_parser.rs b/components/style/servo/selector_parser.rs index a3a3ca7c2b8..66e87b339d4 100644 --- a/components/style/servo/selector_parser.rs +++ b/components/style/servo/selector_parser.rs @@ -29,7 +29,9 @@ use style_traits::{ParseError, StyleParseErrorKind}; /// A pseudo-element, both public and private. /// /// NB: If you add to this list, be sure to update `each_simple_pseudo_element` too. -#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize, ToShmem)] +#[derive( + Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize, ToShmem, +)] #[allow(missing_docs)] #[repr(usize)] pub enum PseudoElement { diff --git a/components/style/values/generics/image.rs b/components/style/values/generics/image.rs index 6f550bc21f6..9376cad2c2e 100644 --- a/components/style/values/generics/image.rs +++ b/components/style/values/generics/image.rs @@ -102,7 +102,9 @@ pub enum GenericGradient< pub use self::GenericGradient as Gradient; -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem, +)] #[repr(u8)] /// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes. pub enum GradientCompatMode { @@ -129,7 +131,9 @@ pub enum GenericEndingShape { pub use self::GenericEndingShape as EndingShape; /// A circle shape. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem, +)] #[repr(C, u8)] pub enum GenericCircle { /// A circle radius. diff --git a/components/style/values/specified/font.rs b/components/style/values/specified/font.rs index 6fee8c2e770..49368548f98 100644 --- a/components/style/values/specified/font.rs +++ b/components/style/values/specified/font.rs @@ -79,7 +79,9 @@ pub const MAX_FONT_WEIGHT: f32 = 1000.; /// A specified font-weight value. /// /// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, +)] pub enum FontWeight { /// `` Absolute(AbsoluteFontWeight), @@ -317,7 +319,9 @@ impl SpecifiedFontStyle { } /// The specified value of the `font-style` property. -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, +)] #[allow(missing_docs)] pub enum FontStyle { Specified(SpecifiedFontStyle), @@ -366,7 +370,9 @@ pub enum FontStretch { } /// A keyword value for `font-stretch`. -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, +)] #[allow(missing_docs)] pub enum FontStretchKeyword { Normal, @@ -727,7 +733,9 @@ impl Parse for FamilyName { } } -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, +)] /// Preserve the readability of text when font fallback occurs pub enum FontSizeAdjust { /// None variant diff --git a/components/style/values/specified/motion.rs b/components/style/values/specified/motion.rs index 7831b78afe6..944a0110840 100644 --- a/components/style/values/specified/motion.rs +++ b/components/style/values/specified/motion.rs @@ -102,7 +102,9 @@ impl Parse for OffsetPath { } /// The direction of offset-rotate. -#[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, +)] #[repr(u8)] pub enum OffsetRotateDirection { /// Unspecified direction keyword. diff --git a/ports/winit/app.rs b/ports/winit/app.rs index e200015c8c9..9edfd20928d 100644 --- a/ports/winit/app.rs +++ b/ports/winit/app.rs @@ -9,7 +9,6 @@ use crate::embedder::EmbedderCallbacks; use crate::events_loop::EventsLoop; use crate::window_trait::WindowPortsMethods; use crate::{headed_window, headless_window}; -use winit::WindowId; use servo::compositing::windowing::WindowEvent; use servo::config::opts::{self, parse_url_or_filename}; use servo::servo_config::pref; @@ -21,6 +20,7 @@ use std::env; use std::mem; use std::rc::Rc; use webxr::glwindow::GlWindowDiscovery; +use winit::WindowId; thread_local! { pub static WINDOWS: RefCell>> = RefCell::new(HashMap::new()); @@ -70,10 +70,7 @@ impl App { }; // Implements embedder methods, used by libservo and constellation. - let embedder = Box::new(EmbedderCallbacks::new( - events_loop.clone(), - xr_discovery, - )); + let embedder = Box::new(EmbedderCallbacks::new(events_loop.clone(), xr_discovery)); // Handle browser state. let browser = Browser::new(window.clone()); diff --git a/ports/winit/backtrace.rs b/ports/winit/backtrace.rs index aa6bb6b3297..06c400267fa 100644 --- a/ports/winit/backtrace.rs +++ b/ports/winit/backtrace.rs @@ -9,14 +9,18 @@ //! FIXME: if/when a future version of the `backtrace` crate has //! https://github.com/rust-lang/backtrace-rs/pull/265, use that instead. -use std::fmt::{self, Write}; use backtrace::{BytesOrWideString, PrintFmt}; +use std::fmt::{self, Write}; #[inline(never)] pub(crate) fn print(w: &mut dyn std::io::Write) -> Result<(), std::io::Error> { - write!(w, "{:?}", Print { - print_fn_address: print as usize, - }) + write!( + w, + "{:?}", + Print { + print_fn_address: print as usize, + } + ) } struct Print { @@ -50,7 +54,7 @@ impl fmt::Debug for Print { let skip = frame_count < print_fn_frame; frame_count += 1; if skip { - return true + return true; } let mut frame_fmt = f.frame(); @@ -76,28 +80,26 @@ impl fmt::Debug for Print { fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result { match path { - BytesOrWideString::Bytes(mut bytes) => { - loop { - match std::str::from_utf8(bytes) { - Ok(s) => { - fmt.write_str(s)?; - break; + BytesOrWideString::Bytes(mut bytes) => loop { + match std::str::from_utf8(bytes) { + Ok(s) => { + fmt.write_str(s)?; + break; + }, + Err(err) => { + fmt.write_char(std::char::REPLACEMENT_CHARACTER)?; + match err.error_len() { + Some(len) => bytes = &bytes[err.valid_up_to() + len..], + None => break, } - Err(err) => { - fmt.write_char(std::char::REPLACEMENT_CHARACTER)?; - match err.error_len() { - Some(len) => bytes = &bytes[err.valid_up_to() + len..], - None => break, - } - } - } + }, } - } + }, BytesOrWideString::Wide(wide) => { for c in std::char::decode_utf16(wide.iter().cloned()) { fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))? } - } + }, } Ok(()) } diff --git a/ports/winit/browser.rs b/ports/winit/browser.rs index 93cf63fdef4..ba8c4a72e30 100644 --- a/ports/winit/browser.rs +++ b/ports/winit/browser.rs @@ -4,12 +4,13 @@ use crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL}; use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; +use clipboard::{ClipboardContext, ClipboardProvider}; use euclid::{Point2D, Vector2D}; use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher}; use servo::compositing::windowing::{WebRenderDebugOption, WindowEvent}; use servo::embedder_traits::{ - ContextMenuResult, EmbedderMsg, FilterPattern, PermissionRequest, PromptDefinition, PromptOrigin, PromptResult, - PermissionPrompt, + ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest, + PromptDefinition, PromptOrigin, PromptResult, }; use servo::msg::constellation_msg::TopLevelBrowsingContextId as BrowserId; use servo::msg::constellation_msg::TraversalDirection; @@ -19,7 +20,6 @@ use servo::servo_config::opts; use servo::servo_config::pref; use servo::servo_url::ServoUrl; use servo::webrender_api::ScrollLocation; -use clipboard::{ClipboardContext, ClipboardProvider}; use std::env; use std::fs::File; use std::io::Write; @@ -294,68 +294,70 @@ where EmbedderMsg::Prompt(definition, origin) => { let res = if opts::get().headless { match definition { - PromptDefinition::Alert(_message, sender) => { - sender.send(()) - } + PromptDefinition::Alert(_message, sender) => sender.send(()), PromptDefinition::YesNo(_message, sender) => { sender.send(PromptResult::Primary) - } + }, PromptDefinition::OkCancel(_message, sender) => { sender.send(PromptResult::Primary) - } + }, PromptDefinition::Input(_message, default, sender) => { sender.send(Some(default.to_owned())) - } + }, } } else { thread::Builder::new() .name("display alert dialog".to_owned()) - .spawn(move || { - match definition { - PromptDefinition::Alert(mut message, sender) => { - if origin == PromptOrigin::Untrusted { - message = tiny_dialog_escape(&message); - } - tinyfiledialogs::message_box_ok( - "Alert!", - &message, - MessageBoxIcon::Warning, - ); - sender.send(()) + .spawn(move || match definition { + PromptDefinition::Alert(mut message, sender) => { + if origin == PromptOrigin::Untrusted { + message = tiny_dialog_escape(&message); } - PromptDefinition::YesNo(mut message, sender) => { - if origin == PromptOrigin::Untrusted { - message = tiny_dialog_escape(&message); - } - let result = tinyfiledialogs::message_box_yes_no( - "", &message, MessageBoxIcon::Warning, YesNo::No, - ); - sender.send(match result { - YesNo::Yes => PromptResult::Primary, - YesNo::No => PromptResult::Secondary, - }) + tinyfiledialogs::message_box_ok( + "Alert!", + &message, + MessageBoxIcon::Warning, + ); + sender.send(()) + }, + PromptDefinition::YesNo(mut message, sender) => { + if origin == PromptOrigin::Untrusted { + message = tiny_dialog_escape(&message); } - PromptDefinition::OkCancel(mut message, sender) => { - if origin == PromptOrigin::Untrusted { - message = tiny_dialog_escape(&message); - } - let result = tinyfiledialogs::message_box_ok_cancel( - "", &message, MessageBoxIcon::Warning, OkCancel::Cancel, - ); - sender.send(match result { - OkCancel::Ok => PromptResult::Primary, - OkCancel::Cancel => PromptResult::Secondary, - }) + let result = tinyfiledialogs::message_box_yes_no( + "", + &message, + MessageBoxIcon::Warning, + YesNo::No, + ); + sender.send(match result { + YesNo::Yes => PromptResult::Primary, + YesNo::No => PromptResult::Secondary, + }) + }, + PromptDefinition::OkCancel(mut message, sender) => { + if origin == PromptOrigin::Untrusted { + message = tiny_dialog_escape(&message); } - PromptDefinition::Input(mut message, mut default, sender) => { - if origin == PromptOrigin::Untrusted { - message = tiny_dialog_escape(&message); - default = tiny_dialog_escape(&default); - } - let result = tinyfiledialogs::input_box("", &message, &default); - sender.send(result) + let result = tinyfiledialogs::message_box_ok_cancel( + "", + &message, + MessageBoxIcon::Warning, + OkCancel::Cancel, + ); + sender.send(match result { + OkCancel::Ok => PromptResult::Primary, + OkCancel::Cancel => PromptResult::Secondary, + }) + }, + PromptDefinition::Input(mut message, mut default, sender) => { + if origin == PromptOrigin::Untrusted { + message = tiny_dialog_escape(&message); + default = tiny_dialog_escape(&default); } - } + let result = tinyfiledialogs::input_box("", &message, &default); + sender.send(result) + }, }) .unwrap() .join() @@ -404,28 +406,26 @@ where }, EmbedderMsg::GetClipboardContents(sender) => { let contents = match self.clipboard_ctx { - Some(ref mut ctx) => { - match ctx.get_contents() { - Ok(c) => c, - Err(e) => { - warn!("Error getting clipboard contents ({}), defaulting to empty string", e); - "".to_owned() - }, - } + Some(ref mut ctx) => match ctx.get_contents() { + Ok(c) => c, + Err(e) => { + warn!("Error getting clipboard contents ({}), defaulting to empty string", e); + "".to_owned() + }, }, None => "".to_owned(), }; if let Err(e) = sender.send(contents) { warn!("Failed to send clipboard ({})", e); } - } + }, EmbedderMsg::SetClipboardContents(text) => { if let Some(ref mut ctx) = self.clipboard_ctx { if let Err(e) = ctx.set_contents(text) { warn!("Error setting clipboard contents ({})", e); } } - } + }, EmbedderMsg::SetCursor(cursor) => { self.window.set_cursor(cursor); }, @@ -486,7 +486,7 @@ where EmbedderMsg::PromptPermission(prompt, sender) => { let permission_state = prompt_user(prompt); let _ = sender.send(permission_state); - } + }, EmbedderMsg::ShowIME(_kind, _text, _rect) => { debug!("ShowIME received"); }, @@ -504,15 +504,13 @@ where debug!("MediaSessionEvent received"); // TODO(ferjm): MediaSession support for winit based browsers. }, - EmbedderMsg::OnDevtoolsStarted(port, _token) => { - match port { - Ok(p) => info!("Devtools Server running on port {}", p), - Err(()) => error!("Error running devtools server"), - } + EmbedderMsg::OnDevtoolsStarted(port, _token) => match port { + Ok(p) => info!("Devtools Server running on port {}", p), + Err(()) => error!("Error running devtools server"), }, EmbedderMsg::ShowContextMenu(sender, ..) => { let _ = sender.send(ContextMenuResult::Ignored); - } + }, } } } @@ -643,20 +641,21 @@ fn sanitize_url(request: &str) -> Option { // different programs depending on what the user has installed. #[cfg(target_os = "linux")] fn tiny_dialog_escape(raw: &str) -> String { - let s:String = raw.chars() - .filter_map(|c| match c { - '\n' => Some('\n'), - '\0' ..= '\x1f' => None, - '<' => Some('\u{FF1C}'), - '>' => Some('\u{FF1E}'), - '&' => Some('\u{FF06}'), - _ => Some(c) - }) - .collect(); - return shellwords::escape(&s); + let s: String = raw + .chars() + .filter_map(|c| match c { + '\n' => Some('\n'), + '\0'..='\x1f' => None, + '<' => Some('\u{FF1C}'), + '>' => Some('\u{FF1E}'), + '&' => Some('\u{FF06}'), + _ => Some(c), + }) + .collect(); + return shellwords::escape(&s); } #[cfg(not(target_os = "linux"))] fn tiny_dialog_escape(raw: &str) -> String { - raw.to_string() + raw.to_string() } diff --git a/ports/winit/crash_handler.rs b/ports/winit/crash_handler.rs index b16353b9fe1..b80b70b651e 100644 --- a/ports/winit/crash_handler.rs +++ b/ports/winit/crash_handler.rs @@ -34,4 +34,3 @@ pub fn install() { signal!(Sig::IOT, handler); // handle double panics signal!(Sig::BUS, handler); // handle invalid memory access } - diff --git a/ports/winit/events_loop.rs b/ports/winit/events_loop.rs index 20ebbed12b1..5de70bd000d 100644 --- a/ports/winit/events_loop.rs +++ b/ports/winit/events_loop.rs @@ -4,13 +4,12 @@ //! An event loop implementation that works in headless mode. - -use winit; use servo::embedder_traits::EventLoopWaker; -use std::sync::{Arc, Condvar, Mutex}; -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; +use std::sync::{Arc, Condvar, Mutex}; use std::time; +use winit; #[allow(dead_code)] enum EventLoop { @@ -29,7 +28,9 @@ impl EventsLoop { // but on Linux, the event loop requires a X11 server. #[cfg(not(target_os = "linux"))] pub fn new(_headless: bool) -> Rc> { - Rc::new(RefCell::new(EventsLoop(EventLoop::Winit(Some(winit::EventsLoop::new()))))) + Rc::new(RefCell::new(EventsLoop(EventLoop::Winit(Some( + winit::EventsLoop::new(), + ))))) } #[cfg(target_os = "linux")] pub fn new(headless: bool) -> Rc> { @@ -51,19 +52,22 @@ impl EventsLoop { .expect("Can't create waker for unavailable event loop."); Box::new(HeadedEventLoopWaker::new(&events_loop)) }, - EventLoop::Headless(ref data) => - Box::new(HeadlessEventLoopWaker(data.clone())), + EventLoop::Headless(ref data) => Box::new(HeadlessEventLoopWaker(data.clone())), } } pub fn as_winit(&self) -> &winit::EventsLoop { match self.0 { EventLoop::Winit(Some(ref event_loop)) => event_loop, - EventLoop::Winit(None) | EventLoop::Headless(..) => - panic!("Can't access winit event loop while using the fake headless event loop"), + EventLoop::Winit(None) | EventLoop::Headless(..) => { + panic!("Can't access winit event loop while using the fake headless event loop") + }, } } - pub fn poll_events(&mut self, callback: F) where F: FnMut(winit::Event) { + pub fn poll_events(&mut self, callback: F) + where + F: FnMut(winit::Event), + { match self.0 { EventLoop::Winit(Some(ref mut events_loop)) => events_loop.poll_events(callback), EventLoop::Winit(None) => (), @@ -78,17 +82,20 @@ impl EventsLoop { // check it first and avoid sleeping unnecessarily. self.sleep(&data.0, &data.1); *data.0.lock().unwrap() = false; - } + }, } } - pub fn run_forever(&mut self, mut callback: F) where F: FnMut(winit::Event) -> winit::ControlFlow { + pub fn run_forever(&mut self, mut callback: F) + where + F: FnMut(winit::Event) -> winit::ControlFlow, + { match self.0 { EventLoop::Winit(ref mut events_loop) => { let events_loop = events_loop .as_mut() .expect("Can't run an unavailable event loop."); events_loop.run_forever(callback); - } + }, EventLoop::Headless(ref data) => { let &(ref flag, ref condvar) = &**data; while !*flag.lock().unwrap() { @@ -97,7 +104,7 @@ impl EventsLoop { break; } } - } + }, } } fn sleep(&self, lock: &Mutex, condvar: &Condvar) { @@ -109,9 +116,9 @@ impl EventsLoop { if *guard { return; } - let _ = condvar.wait_timeout( - guard, time::Duration::from_millis(5) - ).unwrap(); + let _ = condvar + .wait_timeout(guard, time::Duration::from_millis(5)) + .unwrap(); } } diff --git a/ports/winit/headed_window.rs b/ports/winit/headed_window.rs index e8a6c7def32..6572fc3a6bc 100644 --- a/ports/winit/headed_window.rs +++ b/ports/winit/headed_window.rs @@ -7,29 +7,20 @@ use crate::events_loop::EventsLoop; 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 winit::dpi::{LogicalPosition, LogicalSize, PhysicalSize}; -#[cfg(target_os = "macos")] -use winit::os::macos::{ActivationPolicy, WindowBuilderExt}; -#[cfg(any(target_os = "linux", target_os = "windows"))] -use winit::Icon; -use winit::{ElementState, KeyboardInput, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode}; +use euclid::{Angle, Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector2D, Vector3D}; #[cfg(any(target_os = "linux", target_os = "windows"))] use image; use keyboard_types::{Key, KeyState, KeyboardEvent}; use servo::compositing::windowing::{AnimationState, MouseWindowEvent, WindowEvent}; use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; use servo::embedder_traits::Cursor; -use servo::script_traits::{TouchEventType, WheelMode, WheelDelta}; +use servo::script_traits::{TouchEventType, WheelDelta, WheelMode}; use servo::servo_config::opts; use servo::servo_config::pref; use servo::servo_geometry::DeviceIndependentPixel; use servo::style_traits::DevicePixel; -use servo::webrender_api::ScrollLocation; 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}; @@ -48,6 +39,14 @@ use surfman::GLVersion; use surfman::SurfaceType; #[cfg(target_os = "windows")] use winapi; +use winit::dpi::{LogicalPosition, LogicalSize, PhysicalSize}; +#[cfg(target_os = "macos")] +use winit::os::macos::{ActivationPolicy, WindowBuilderExt}; +#[cfg(any(target_os = "linux", target_os = "windows"))] +use winit::Icon; +use winit::{ + ElementState, KeyboardInput, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode, +}; #[cfg(target_os = "macos")] fn builder_with_platform_options(mut builder: winit::WindowBuilder) -> winit::WindowBuilder { @@ -125,7 +124,9 @@ impl Window { window_builder = builder_with_platform_options(window_builder); - let winit_window = window_builder.build(events_loop.borrow().as_winit()).expect("Failed to create window."); + let winit_window = window_builder + .build(events_loop.borrow().as_winit()) + .expect("Failed to create window."); #[cfg(any(target_os = "linux", target_os = "windows"))] { @@ -149,17 +150,17 @@ impl Window { winit_window.show(); // Initialize surfman - let connection = Connection::from_winit_window(&winit_window).expect("Failed to create connection"); - let adapter = connection.create_adapter().expect("Failed to create adapter"); + let connection = + Connection::from_winit_window(&winit_window).expect("Failed to create connection"); + let adapter = connection + .create_adapter() + .expect("Failed to create adapter"); let native_widget = connection .create_native_widget_from_winit_window(&winit_window) .expect("Failed to create native widget"); let surface_type = SurfaceType::Widget { native_widget }; - let webrender_surfman = WebrenderSurfman::create( - &connection, - &adapter, - surface_type, - ).expect("Failed to create WR surfman"); + let webrender_surfman = WebrenderSurfman::create(&connection, &adapter, surface_type) + .expect("Failed to create WR surfman"); debug!("Created window {:?}", winit_window.id()); Window { @@ -190,7 +191,8 @@ impl Window { // shift ASCII control characters to lowercase ch = (ch as u8 + 96) as char; } - let (mut event, key_code) = if let Some((event, key_code)) = self.last_pressed.replace(None) { + let (mut event, key_code) = if let Some((event, key_code)) = self.last_pressed.replace(None) + { (event, key_code) } else if ch.is_ascii() { // Some keys like Backspace emit a control character in winit @@ -209,7 +211,9 @@ impl Window { // to infer that it's related to this character and set the event // properties appropriately. if let Some(key_code) = key_code { - self.keys_down.borrow_mut().insert(key_code, event.key.clone()); + self.keys_down + .borrow_mut() + .insert(key_code, event.key.clone()); } } @@ -351,8 +355,11 @@ impl WindowPortsMethods for Window { fn set_fullscreen(&self, state: bool) { if self.fullscreen.get() != state { - self.winit_window - .set_fullscreen(if state { Some(self.primary_monitor.clone()) } else { None }); + self.winit_window.set_fullscreen(if state { + Some(self.primary_monitor.clone()) + } else { + None + }); } self.fullscreen.set(state); } @@ -433,8 +440,9 @@ impl WindowPortsMethods for Window { }, winit::WindowEvent::MouseWheel { delta, phase, .. } => { let (mut dx, mut dy, mode) = match delta { - MouseScrollDelta::LineDelta(dx, dy) => (dx as f64, (dy * LINE_HEIGHT) as f64, - WheelMode::DeltaLine), + MouseScrollDelta::LineDelta(dx, dy) => { + (dx as f64, (dy * LINE_HEIGHT) as f64, WheelMode::DeltaLine) + }, MouseScrollDelta::PixelDelta(position) => { let position = position.to_physical(self.device_hidpi_factor().get() as f64); @@ -443,7 +451,12 @@ impl WindowPortsMethods for Window { }; // Create wheel event before snapping to the major axis of movement - let wheel_delta = WheelDelta { x: dx, y: dy, z: 0.0, mode }; + let wheel_delta = WheelDelta { + x: dx, + y: dy, + z: 0.0, + mode, + }; let pos = self.mouse_pos.get(); let position = Point2D::new(pos.x as f32, pos.y as f32); let wheel_event = WindowEvent::Wheel(wheel_delta, position); @@ -458,7 +471,8 @@ impl WindowPortsMethods for Window { let scroll_location = ScrollLocation::Delta(Vector2D::new(dx as f32, dy as f32)); let phase = winit_phase_to_touch_event_type(phase); - let scroll_event = WindowEvent::Scroll(scroll_location, self.mouse_pos.get(), phase); + let scroll_event = + WindowEvent::Scroll(scroll_location, self.mouse_pos.get(), phase); // Send events self.event_queue.borrow_mut().push(wheel_event); @@ -489,7 +503,9 @@ impl WindowPortsMethods for Window { if self.inner_size.get() != new_size { let physical_size = size.to_physical(self.device_hidpi_factor().get() as f64); let physical_size = Size2D::new(physical_size.width, physical_size.height); - self.webrender_surfman.resize(physical_size.to_i32()).expect("Failed to resize"); + self.webrender_surfman + .resize(physical_size.to_i32()) + .expect("Failed to resize"); self.inner_size.set(new_size); self.event_queue.borrow_mut().push(WindowEvent::Resize); } @@ -499,7 +515,9 @@ impl WindowPortsMethods for Window { } fn new_glwindow(&self, events_loop: &EventsLoop) -> Box { - let size = self.winit_window.get_outer_size() + let size = self + .winit_window + .get_outer_size() .expect("Failed to get window outer size"); let mut window_builder = winit::WindowBuilder::new() @@ -509,7 +527,8 @@ impl WindowPortsMethods for Window { window_builder = builder_with_platform_options(window_builder); - let winit_window = window_builder.build(events_loop.as_winit()) + let winit_window = window_builder + .build(events_loop.as_winit()) .expect("Failed to create window."); let pose = Rc::new(XRWindowPose { @@ -576,10 +595,12 @@ impl WindowMethods for Window { #[cfg(target_os = "linux")] return match native_context { - NativeContext::Default(NativeContext::Default(native_context)) => - PlayerGLContext::Egl(native_context.egl_context as usize), - NativeContext::Default(NativeContext::Alternate(native_context)) => - PlayerGLContext::Egl(native_context.egl_context as usize), + NativeContext::Default(NativeContext::Default(native_context)) => { + PlayerGLContext::Egl(native_context.egl_context as usize) + }, + NativeContext::Default(NativeContext::Alternate(native_context)) => { + PlayerGLContext::Egl(native_context.egl_context as usize) + }, NativeContext::Alternate(_) => unimplemented!(), }; @@ -607,10 +628,12 @@ impl WindowMethods for Window { #[cfg(target_os = "linux")] return match native_connection { - NativeConnection::Default(NativeConnection::Default(conn)) => - NativeDisplay::Egl(conn.0 as usize), - NativeConnection::Default(NativeConnection::Alternate(conn)) => - NativeDisplay::X11(conn.x11_display as usize), + NativeConnection::Default(NativeConnection::Default(conn)) => { + NativeDisplay::Egl(conn.0 as usize) + }, + NativeConnection::Default(NativeConnection::Alternate(conn)) => { + NativeDisplay::X11(conn.x11_display as usize) + }, NativeConnection::Alternate(_) => unimplemented!(), }; @@ -671,8 +694,13 @@ struct XRWindowPose { } impl webxr::glwindow::GlWindow for XRWindow { - fn get_render_target(&self, device: &mut Device, _context: &mut Context) -> webxr::glwindow::GlWindowRenderTarget { - let native_widget = device.connection() + fn get_render_target( + &self, + device: &mut Device, + _context: &mut Context, + ) -> webxr::glwindow::GlWindowRenderTarget { + let native_widget = device + .connection() .create_native_widget_from_winit_window(&self.winit_window) .expect("Failed to create native widget"); webxr::glwindow::GlWindowRenderTarget::NativeWidget(native_widget) diff --git a/ports/winit/headless_window.rs b/ports/winit/headless_window.rs index 3f8f5c7ea4c..98a719718c5 100644 --- a/ports/winit/headless_window.rs +++ b/ports/winit/headless_window.rs @@ -7,20 +7,20 @@ use crate::events_loop::EventsLoop; use crate::window_trait::WindowPortsMethods; use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D}; -use winit; use servo::compositing::windowing::{AnimationState, WindowEvent}; use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; use servo::servo_geometry::DeviceIndependentPixel; use servo::style_traits::DevicePixel; use servo::webrender_api::units::DeviceIntRect; -use servo_media::player::context as MediaPlayerCtxt; 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 winit; pub struct Window { webrender_surfman: WebrenderSurfman, @@ -36,14 +36,13 @@ impl Window { ) -> Rc { // Initialize surfman let connection = Connection::new().expect("Failed to create connection"); - let adapter = connection.create_software_adapter().expect("Failed to create adapter"); + let adapter = connection + .create_software_adapter() + .expect("Failed to create adapter"); let size = size.to_untyped().to_i32(); let surface_type = SurfaceType::Generic { size }; - let webrender_surfman = WebrenderSurfman::create( - &connection, - &adapter, - surface_type, - ).expect("Failed to create WR surfman"); + let webrender_surfman = WebrenderSurfman::create(&connection, &adapter, surface_type) + .expect("Failed to create WR surfman"); let window = Window { webrender_surfman, @@ -77,7 +76,8 @@ impl WindowPortsMethods for Window { } fn page_height(&self) -> f32 { - let height = self.webrender_surfman + let height = self + .webrender_surfman .context_surface_info() .unwrap_or(None) .map(|info| info.size.height) @@ -108,9 +108,10 @@ impl WindowPortsMethods for Window { } impl WindowMethods for Window { - fn get_coordinates(&self) -> EmbedderCoordinates { + fn get_coordinates(&self) -> EmbedderCoordinates { let dpr = self.servo_hidpi_factor(); - let size = self.webrender_surfman + let size = self + .webrender_surfman .context_surface_info() .unwrap_or(None) .map(|info| Size2D::from_untyped(info.size)) @@ -126,11 +127,11 @@ impl WindowMethods for Window { } } - fn set_animation_state(&self, state: AnimationState) { + fn set_animation_state(&self, state: AnimationState) { self.animation_state.set(state); } - fn get_gl_context(&self) -> MediaPlayerCtxt::GlContext { + fn get_gl_context(&self) -> MediaPlayerCtxt::GlContext { MediaPlayerCtxt::GlContext::Unknown } @@ -148,7 +149,11 @@ impl WindowMethods for Window { } impl webxr::glwindow::GlWindow for Window { - fn get_render_target(&self, _device: &mut Device, _context: &mut Context) -> webxr::glwindow::GlWindowRenderTarget { + fn get_render_target( + &self, + _device: &mut Device, + _context: &mut Context, + ) -> webxr::glwindow::GlWindowRenderTarget { unimplemented!() } diff --git a/ports/winit/keyutils.rs b/ports/winit/keyutils.rs index 9d7b3285454..5be6e8e9685 100644 --- a/ports/winit/keyutils.rs +++ b/ports/winit/keyutils.rs @@ -2,8 +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 winit::{ElementState, KeyboardInput, ModifiersState, VirtualKeyCode}; use keyboard_types::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers}; +use winit::{ElementState, KeyboardInput, ModifiersState, VirtualKeyCode}; // Some shortcuts use Cmd on Mac and Control on other systems. #[cfg(target_os = "macos")] diff --git a/ports/winit/prefs.rs b/ports/winit/prefs.rs index 16f4de85b81..3d95ea2a65b 100644 --- a/ports/winit/prefs.rs +++ b/ports/winit/prefs.rs @@ -2,14 +2,14 @@ * 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; 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; -use servo::servo_config::basedir; pub fn register_user_prefs(opts_matches: &Matches) { // Read user's prefs.json and then parse --pref command line args. @@ -24,30 +24,35 @@ pub fn register_user_prefs(opts_matches: &Matches) { let mut userprefs = if let Some(path) = user_prefs_path { let mut file = File::open(&path).expect("Error opening user prefs"); let mut txt = String::new(); - file.read_to_string(&mut txt).expect("Can't read user prefs file"); + file.read_to_string(&mut txt) + .expect("Can't read user prefs file"); prefs::read_prefs_map(&txt).expect("Can't parse user prefs file") } else { HashMap::new() }; - let argprefs: HashMap = opts_matches.opt_strs("pref").iter().map(|pref| { - let split: Vec<&str> = pref.splitn(2, '=').collect(); - let pref_name = split[0]; - let pref_value = match split.get(1).cloned() { - Some("true") | None => PrefValue::Bool(true), - Some("false") => PrefValue::Bool(false), - Some(string) => { - if let Some(int) = string.parse::().ok() { - PrefValue::Int(int) - } else if let Some(float) = string.parse::().ok() { - PrefValue::Float(float) - } else { - PrefValue::from(string) - } - }, - }; - (pref_name.to_string(), pref_value) - }).collect(); + let argprefs: HashMap = opts_matches + .opt_strs("pref") + .iter() + .map(|pref| { + let split: Vec<&str> = pref.splitn(2, '=').collect(); + let pref_name = split[0]; + let pref_value = match split.get(1).cloned() { + Some("true") | None => PrefValue::Bool(true), + Some("false") => PrefValue::Bool(false), + Some(string) => { + if let Some(int) = string.parse::().ok() { + PrefValue::Int(int) + } else if let Some(float) = string.parse::().ok() { + PrefValue::Float(float) + } else { + PrefValue::from(string) + } + }, + }; + (pref_name.to_string(), pref_value) + }) + .collect(); // --pref overrides user prefs.json userprefs.extend(argprefs); @@ -61,11 +66,7 @@ fn test_parse_pref(arg: &str) { embedder_traits::resources::set_for_tests(); let mut opts = Options::new(); opts.optmulti("", "pref", "", ""); - let args = vec![ - "servo".to_string(), - "--pref".to_string(), - arg.to_string() - ]; + let args = vec!["servo".to_string(), "--pref".to_string(), arg.to_string()]; let matches = match opts::from_cmdline_args(opts, &args) { ArgumentParsingResult::ContentProcess(m, _) => m, ArgumentParsingResult::ChromeProcess(m) => m, @@ -107,7 +108,6 @@ fn test_parse_pref_from_command_line() { assert_eq!(pref!(dom.bluetooth.enabled), true); } - #[test] fn test_invalid_prefs_from_command_line_panics() { let err_msg = std::panic::catch_unwind(|| { diff --git a/ports/winit/window_trait.rs b/ports/winit/window_trait.rs index 9fee3a66075..a6faa676589 100644 --- a/ports/winit/window_trait.rs +++ b/ports/winit/window_trait.rs @@ -6,10 +6,10 @@ //! Implemented by headless and headed windows. use crate::events_loop::EventsLoop; -use winit; use servo::compositing::windowing::{WindowEvent, WindowMethods}; use servo::embedder_traits::Cursor; use servo::webrender_api::units::{DeviceIntPoint, DeviceIntSize}; +use winit; // This should vary by zoom level and maybe actual text size (focused or under cursor) pub const LINE_HEIGHT: f32 = 38.0; diff --git a/rust-toolchain b/rust-toolchain index 5bc8eb6009c..d6ee05dcfce 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1 +1 @@ -nightly-2020-09-27 +nightly-2021-02-25