Auto merge of #28201 - servo:rustup, r=jdm

Upgrade to rustc 1.52.0-nightly (a8486b64b 2021-02-24)
This commit is contained in:
bors-servo 2021-02-25 18:40:03 -05:00 committed by GitHub
commit 5916911281
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 279 additions and 224 deletions

View file

@ -467,7 +467,7 @@ impl<'a> Iterator for &'a TreeWalker {
// which cannot produce an Err result. // which cannot produce an Err result.
{ {
unreachable!() unreachable!()
}, }
} }
} }
} }

View file

@ -4,6 +4,7 @@
#![feature(assoc_char_funcs)] #![feature(assoc_char_funcs)]
#![feature(const_fn)] #![feature(const_fn)]
#![feature(const_fn_fn_ptr_basics)]
#![feature(core_intrinsics)] #![feature(core_intrinsics)]
#![feature(drain_filter)] #![feature(drain_filter)]
#![feature(plugin)] #![feature(plugin)]

View file

@ -90,7 +90,7 @@ fn has_lint_attr(sym: &Symbols, attrs: &[Attribute], name: Symbol) -> bool {
attrs.iter().any(|attr| { attrs.iter().any(|attr| {
matches!( matches!(
&attr.kind, &attr.kind,
AttrKind::Normal(attr_item) AttrKind::Normal(attr_item, _)
if attr_item.path.segments.len() == 2 && if attr_item.path.segments.len() == 2 &&
attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint && attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint &&
attr_item.path.segments[1].ident.name == name attr_item.path.segments[1].ident.name == name

View file

@ -198,11 +198,12 @@ impl NonTSPseudoClass {
/// revalidation. /// revalidation.
pub fn needs_cache_revalidation(&self) -> bool { pub fn needs_cache_revalidation(&self) -> bool {
self.state_flag().is_empty() && self.state_flag().is_empty() &&
!matches!(*self, !matches!(
// :-moz-any is handled by the revalidation visitor walking *self,
// the things inside it; it does not need to cause // :-moz-any is handled by the revalidation visitor walking
// revalidation on its own. // the things inside it; it does not need to cause
NonTSPseudoClass::MozAny(_) | // revalidation on its own.
NonTSPseudoClass::MozAny(_) |
// :dir() depends on state only, but doesn't use state_flag // :dir() depends on state only, but doesn't use state_flag
// because its semantics don't quite match. Nevertheless, it // because its semantics don't quite match. Nevertheless, it
// doesn't need cache revalidation, because we already compare // doesn't need cache revalidation, because we already compare

View file

@ -29,7 +29,9 @@ use style_traits::{ParseError, StyleParseErrorKind};
/// A pseudo-element, both public and private. /// A pseudo-element, both public and private.
/// ///
/// NB: If you add to this list, be sure to update `each_simple_pseudo_element` too. /// 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)] #[allow(missing_docs)]
#[repr(usize)] #[repr(usize)]
pub enum PseudoElement { pub enum PseudoElement {

View file

@ -102,7 +102,9 @@ pub enum GenericGradient<
pub use self::GenericGradient as Gradient; 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)] #[repr(u8)]
/// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes. /// Whether we used the modern notation or the compatibility `-webkit`, `-moz` prefixes.
pub enum GradientCompatMode { pub enum GradientCompatMode {
@ -129,7 +131,9 @@ pub enum GenericEndingShape<NonNegativeLength, NonNegativeLengthPercentage> {
pub use self::GenericEndingShape as EndingShape; pub use self::GenericEndingShape as EndingShape;
/// A circle shape. /// A circle shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem)] #[derive(
Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToResolvedValue, ToShmem,
)]
#[repr(C, u8)] #[repr(C, u8)]
pub enum GenericCircle<NonNegativeLength> { pub enum GenericCircle<NonNegativeLength> {
/// A circle radius. /// A circle radius.

View file

@ -79,7 +79,9 @@ pub const MAX_FONT_WEIGHT: f32 = 1000.;
/// A specified font-weight value. /// A specified font-weight value.
/// ///
/// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight /// 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 { pub enum FontWeight {
/// `<font-weight-absolute>` /// `<font-weight-absolute>`
Absolute(AbsoluteFontWeight), Absolute(AbsoluteFontWeight),
@ -317,7 +319,9 @@ impl SpecifiedFontStyle {
} }
/// The specified value of the `font-style` property. /// 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)] #[allow(missing_docs)]
pub enum FontStyle { pub enum FontStyle {
Specified(SpecifiedFontStyle), Specified(SpecifiedFontStyle),
@ -366,7 +370,9 @@ pub enum FontStretch {
} }
/// A keyword value for `font-stretch`. /// 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)] #[allow(missing_docs)]
pub enum FontStretchKeyword { pub enum FontStretchKeyword {
Normal, 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 /// Preserve the readability of text when font fallback occurs
pub enum FontSizeAdjust { pub enum FontSizeAdjust {
/// None variant /// None variant

View file

@ -102,7 +102,9 @@ impl Parse for OffsetPath {
} }
/// The direction of offset-rotate. /// 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)] #[repr(u8)]
pub enum OffsetRotateDirection { pub enum OffsetRotateDirection {
/// Unspecified direction keyword. /// Unspecified direction keyword.

View file

@ -9,7 +9,6 @@ use crate::embedder::EmbedderCallbacks;
use crate::events_loop::EventsLoop; use crate::events_loop::EventsLoop;
use crate::window_trait::WindowPortsMethods; use crate::window_trait::WindowPortsMethods;
use crate::{headed_window, headless_window}; use crate::{headed_window, headless_window};
use winit::WindowId;
use servo::compositing::windowing::WindowEvent; use servo::compositing::windowing::WindowEvent;
use servo::config::opts::{self, parse_url_or_filename}; use servo::config::opts::{self, parse_url_or_filename};
use servo::servo_config::pref; use servo::servo_config::pref;
@ -21,6 +20,7 @@ use std::env;
use std::mem; use std::mem;
use std::rc::Rc; use std::rc::Rc;
use webxr::glwindow::GlWindowDiscovery; use webxr::glwindow::GlWindowDiscovery;
use winit::WindowId;
thread_local! { thread_local! {
pub static WINDOWS: RefCell<HashMap<WindowId, Rc<dyn WindowPortsMethods>>> = RefCell::new(HashMap::new()); pub static WINDOWS: RefCell<HashMap<WindowId, Rc<dyn WindowPortsMethods>>> = RefCell::new(HashMap::new());
@ -70,10 +70,7 @@ impl App {
}; };
// 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(events_loop.clone(), xr_discovery));
events_loop.clone(),
xr_discovery,
));
// Handle browser state. // Handle browser state.
let browser = Browser::new(window.clone()); let browser = Browser::new(window.clone());

View file

@ -9,14 +9,18 @@
//! 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 std::fmt::{self, Write};
use backtrace::{BytesOrWideString, PrintFmt}; use backtrace::{BytesOrWideString, PrintFmt};
use std::fmt::{self, Write};
#[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!(w, "{:?}", Print { write!(
print_fn_address: print as usize, w,
}) "{:?}",
Print {
print_fn_address: print as usize,
}
)
} }
struct Print { struct Print {
@ -50,7 +54,7 @@ impl fmt::Debug for Print {
let skip = frame_count < print_fn_frame; let skip = frame_count < print_fn_frame;
frame_count += 1; frame_count += 1;
if skip { if skip {
return true return true;
} }
let mut frame_fmt = f.frame(); 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 { fn print_path(fmt: &mut fmt::Formatter, path: BytesOrWideString) -> fmt::Result {
match path { match path {
BytesOrWideString::Bytes(mut bytes) => { BytesOrWideString::Bytes(mut bytes) => loop {
loop { match std::str::from_utf8(bytes) {
match std::str::from_utf8(bytes) { Ok(s) => {
Ok(s) => { fmt.write_str(s)?;
fmt.write_str(s)?; break;
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) => { BytesOrWideString::Wide(wide) => {
for c in std::char::decode_utf16(wide.iter().cloned()) { for c in std::char::decode_utf16(wide.iter().cloned()) {
fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))? fmt.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
} }
} },
} }
Ok(()) Ok(())
} }

View file

@ -4,12 +4,13 @@
use crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL}; use crate::keyutils::{CMD_OR_ALT, CMD_OR_CONTROL};
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT};
use clipboard::{ClipboardContext, ClipboardProvider};
use euclid::{Point2D, Vector2D}; use euclid::{Point2D, Vector2D};
use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher}; use keyboard_types::{Key, KeyboardEvent, Modifiers, ShortcutMatcher};
use servo::compositing::windowing::{WebRenderDebugOption, WindowEvent}; use servo::compositing::windowing::{WebRenderDebugOption, WindowEvent};
use servo::embedder_traits::{ use servo::embedder_traits::{
ContextMenuResult, EmbedderMsg, FilterPattern, PermissionRequest, PromptDefinition, PromptOrigin, PromptResult, ContextMenuResult, EmbedderMsg, FilterPattern, PermissionPrompt, PermissionRequest,
PermissionPrompt, PromptDefinition, PromptOrigin, PromptResult,
}; };
use servo::msg::constellation_msg::TopLevelBrowsingContextId as BrowserId; use servo::msg::constellation_msg::TopLevelBrowsingContextId as BrowserId;
use servo::msg::constellation_msg::TraversalDirection; use servo::msg::constellation_msg::TraversalDirection;
@ -19,7 +20,6 @@ use servo::servo_config::opts;
use servo::servo_config::pref; use servo::servo_config::pref;
use servo::servo_url::ServoUrl; use servo::servo_url::ServoUrl;
use servo::webrender_api::ScrollLocation; use servo::webrender_api::ScrollLocation;
use clipboard::{ClipboardContext, ClipboardProvider};
use std::env; use std::env;
use std::fs::File; use std::fs::File;
use std::io::Write; use std::io::Write;
@ -294,68 +294,70 @@ where
EmbedderMsg::Prompt(definition, origin) => { EmbedderMsg::Prompt(definition, origin) => {
let res = if opts::get().headless { let res = if opts::get().headless {
match definition { match definition {
PromptDefinition::Alert(_message, sender) => { PromptDefinition::Alert(_message, sender) => sender.send(()),
sender.send(())
}
PromptDefinition::YesNo(_message, sender) => { PromptDefinition::YesNo(_message, sender) => {
sender.send(PromptResult::Primary) sender.send(PromptResult::Primary)
} },
PromptDefinition::OkCancel(_message, sender) => { PromptDefinition::OkCancel(_message, sender) => {
sender.send(PromptResult::Primary) sender.send(PromptResult::Primary)
} },
PromptDefinition::Input(_message, default, sender) => { PromptDefinition::Input(_message, default, sender) => {
sender.send(Some(default.to_owned())) sender.send(Some(default.to_owned()))
} },
} }
} else { } else {
thread::Builder::new() thread::Builder::new()
.name("display alert dialog".to_owned()) .name("display alert dialog".to_owned())
.spawn(move || { .spawn(move || match definition {
match definition { PromptDefinition::Alert(mut message, sender) => {
PromptDefinition::Alert(mut message, sender) => { if origin == PromptOrigin::Untrusted {
if origin == PromptOrigin::Untrusted { message = tiny_dialog_escape(&message);
message = tiny_dialog_escape(&message);
}
tinyfiledialogs::message_box_ok(
"Alert!",
&message,
MessageBoxIcon::Warning,
);
sender.send(())
} }
PromptDefinition::YesNo(mut message, sender) => { tinyfiledialogs::message_box_ok(
if origin == PromptOrigin::Untrusted { "Alert!",
message = tiny_dialog_escape(&message); &message,
} MessageBoxIcon::Warning,
let result = tinyfiledialogs::message_box_yes_no( );
"", &message, MessageBoxIcon::Warning, YesNo::No, sender.send(())
); },
sender.send(match result { PromptDefinition::YesNo(mut message, sender) => {
YesNo::Yes => PromptResult::Primary, if origin == PromptOrigin::Untrusted {
YesNo::No => PromptResult::Secondary, message = tiny_dialog_escape(&message);
})
} }
PromptDefinition::OkCancel(mut message, sender) => { let result = tinyfiledialogs::message_box_yes_no(
if origin == PromptOrigin::Untrusted { "",
message = tiny_dialog_escape(&message); &message,
} MessageBoxIcon::Warning,
let result = tinyfiledialogs::message_box_ok_cancel( YesNo::No,
"", &message, MessageBoxIcon::Warning, OkCancel::Cancel, );
); sender.send(match result {
sender.send(match result { YesNo::Yes => PromptResult::Primary,
OkCancel::Ok => PromptResult::Primary, YesNo::No => PromptResult::Secondary,
OkCancel::Cancel => PromptResult::Secondary, })
}) },
PromptDefinition::OkCancel(mut message, sender) => {
if origin == PromptOrigin::Untrusted {
message = tiny_dialog_escape(&message);
} }
PromptDefinition::Input(mut message, mut default, sender) => { let result = tinyfiledialogs::message_box_ok_cancel(
if origin == PromptOrigin::Untrusted { "",
message = tiny_dialog_escape(&message); &message,
default = tiny_dialog_escape(&default); MessageBoxIcon::Warning,
} OkCancel::Cancel,
let result = tinyfiledialogs::input_box("", &message, &default); );
sender.send(result) 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() .unwrap()
.join() .join()
@ -404,28 +406,26 @@ where
}, },
EmbedderMsg::GetClipboardContents(sender) => { EmbedderMsg::GetClipboardContents(sender) => {
let contents = match self.clipboard_ctx { let contents = match self.clipboard_ctx {
Some(ref mut ctx) => { Some(ref mut ctx) => match ctx.get_contents() {
match ctx.get_contents() { Ok(c) => c,
Ok(c) => c, Err(e) => {
Err(e) => { warn!("Error getting clipboard contents ({}), defaulting to empty string", e);
warn!("Error getting clipboard contents ({}), defaulting to empty string", e); "".to_owned()
"".to_owned() },
},
}
}, },
None => "".to_owned(), None => "".to_owned(),
}; };
if let Err(e) = sender.send(contents) { if let Err(e) = sender.send(contents) {
warn!("Failed to send clipboard ({})", e); warn!("Failed to send clipboard ({})", e);
} }
} },
EmbedderMsg::SetClipboardContents(text) => { EmbedderMsg::SetClipboardContents(text) => {
if let Some(ref mut ctx) = self.clipboard_ctx { if let Some(ref mut ctx) = self.clipboard_ctx {
if let Err(e) = ctx.set_contents(text) { if let Err(e) = ctx.set_contents(text) {
warn!("Error setting clipboard contents ({})", e); warn!("Error setting clipboard contents ({})", e);
} }
} }
} },
EmbedderMsg::SetCursor(cursor) => { EmbedderMsg::SetCursor(cursor) => {
self.window.set_cursor(cursor); self.window.set_cursor(cursor);
}, },
@ -486,7 +486,7 @@ where
EmbedderMsg::PromptPermission(prompt, sender) => { EmbedderMsg::PromptPermission(prompt, sender) => {
let permission_state = prompt_user(prompt); let permission_state = prompt_user(prompt);
let _ = sender.send(permission_state); let _ = sender.send(permission_state);
} },
EmbedderMsg::ShowIME(_kind, _text, _rect) => { EmbedderMsg::ShowIME(_kind, _text, _rect) => {
debug!("ShowIME received"); debug!("ShowIME received");
}, },
@ -504,15 +504,13 @@ where
debug!("MediaSessionEvent received"); debug!("MediaSessionEvent received");
// TODO(ferjm): MediaSession support for winit based browsers. // TODO(ferjm): MediaSession support for winit based browsers.
}, },
EmbedderMsg::OnDevtoolsStarted(port, _token) => { EmbedderMsg::OnDevtoolsStarted(port, _token) => match port {
match port { Ok(p) => info!("Devtools Server running on port {}", p),
Ok(p) => info!("Devtools Server running on port {}", p), Err(()) => error!("Error running devtools server"),
Err(()) => error!("Error running devtools server"),
}
}, },
EmbedderMsg::ShowContextMenu(sender, ..) => { EmbedderMsg::ShowContextMenu(sender, ..) => {
let _ = sender.send(ContextMenuResult::Ignored); let _ = sender.send(ContextMenuResult::Ignored);
} },
} }
} }
} }
@ -643,20 +641,21 @@ fn sanitize_url(request: &str) -> Option<ServoUrl> {
// different programs depending on what the user has installed. // different programs depending on what the user has installed.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn tiny_dialog_escape(raw: &str) -> String { fn tiny_dialog_escape(raw: &str) -> String {
let s:String = raw.chars() let s: String = raw
.filter_map(|c| match c { .chars()
'\n' => Some('\n'), .filter_map(|c| match c {
'\0' ..= '\x1f' => None, '\n' => Some('\n'),
'<' => Some('\u{FF1C}'), '\0'..='\x1f' => None,
'>' => Some('\u{FF1E}'), '<' => Some('\u{FF1C}'),
'&' => Some('\u{FF06}'), '>' => Some('\u{FF1E}'),
_ => Some(c) '&' => Some('\u{FF06}'),
}) _ => Some(c),
.collect(); })
return shellwords::escape(&s); .collect();
return shellwords::escape(&s);
} }
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
fn tiny_dialog_escape(raw: &str) -> String { fn tiny_dialog_escape(raw: &str) -> String {
raw.to_string() raw.to_string()
} }

View file

@ -34,4 +34,3 @@ pub fn install() {
signal!(Sig::IOT, handler); // handle double panics signal!(Sig::IOT, handler); // handle double panics
signal!(Sig::BUS, handler); // handle invalid memory access signal!(Sig::BUS, handler); // handle invalid memory access
} }

View file

@ -4,13 +4,12 @@
//! An event loop implementation that works in headless mode. //! An event loop implementation that works in headless mode.
use winit;
use servo::embedder_traits::EventLoopWaker; use servo::embedder_traits::EventLoopWaker;
use std::sync::{Arc, Condvar, Mutex};
use std::rc::Rc;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex};
use std::time; use std::time;
use winit;
#[allow(dead_code)] #[allow(dead_code)]
enum EventLoop { enum EventLoop {
@ -29,7 +28,9 @@ impl EventsLoop {
// but on Linux, the event loop requires a X11 server. // but on Linux, the event loop requires a X11 server.
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
pub fn new(_headless: bool) -> Rc<RefCell<EventsLoop>> { pub fn new(_headless: bool) -> Rc<RefCell<EventsLoop>> {
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")] #[cfg(target_os = "linux")]
pub fn new(headless: bool) -> Rc<RefCell<EventsLoop>> { pub fn new(headless: bool) -> Rc<RefCell<EventsLoop>> {
@ -51,19 +52,22 @@ impl EventsLoop {
.expect("Can't create waker for unavailable event loop."); .expect("Can't create waker for unavailable event loop.");
Box::new(HeadedEventLoopWaker::new(&events_loop)) Box::new(HeadedEventLoopWaker::new(&events_loop))
}, },
EventLoop::Headless(ref data) => EventLoop::Headless(ref data) => Box::new(HeadlessEventLoopWaker(data.clone())),
Box::new(HeadlessEventLoopWaker(data.clone())),
} }
} }
pub fn as_winit(&self) -> &winit::EventsLoop { pub fn as_winit(&self) -> &winit::EventsLoop {
match self.0 { match self.0 {
EventLoop::Winit(Some(ref event_loop)) => event_loop, EventLoop::Winit(Some(ref event_loop)) => event_loop,
EventLoop::Winit(None) | EventLoop::Headless(..) => EventLoop::Winit(None) | EventLoop::Headless(..) => {
panic!("Can't access winit event loop while using the fake headless event loop"), panic!("Can't access winit event loop while using the fake headless event loop")
},
} }
} }
pub fn poll_events<F>(&mut self, callback: F) where F: FnMut(winit::Event) { pub fn poll_events<F>(&mut self, callback: F)
where
F: FnMut(winit::Event),
{
match self.0 { match self.0 {
EventLoop::Winit(Some(ref mut events_loop)) => events_loop.poll_events(callback), EventLoop::Winit(Some(ref mut events_loop)) => events_loop.poll_events(callback),
EventLoop::Winit(None) => (), EventLoop::Winit(None) => (),
@ -78,17 +82,20 @@ impl EventsLoop {
// check it first and avoid sleeping unnecessarily. // check it first and avoid sleeping unnecessarily.
self.sleep(&data.0, &data.1); self.sleep(&data.0, &data.1);
*data.0.lock().unwrap() = false; *data.0.lock().unwrap() = false;
} },
} }
} }
pub fn run_forever<F>(&mut self, mut callback: F) where F: FnMut(winit::Event) -> winit::ControlFlow { pub fn run_forever<F>(&mut self, mut callback: F)
where
F: FnMut(winit::Event) -> winit::ControlFlow,
{
match self.0 { match self.0 {
EventLoop::Winit(ref mut events_loop) => { EventLoop::Winit(ref mut events_loop) => {
let events_loop = events_loop let events_loop = events_loop
.as_mut() .as_mut()
.expect("Can't run an unavailable event loop."); .expect("Can't run an unavailable event loop.");
events_loop.run_forever(callback); events_loop.run_forever(callback);
} },
EventLoop::Headless(ref data) => { EventLoop::Headless(ref data) => {
let &(ref flag, ref condvar) = &**data; let &(ref flag, ref condvar) = &**data;
while !*flag.lock().unwrap() { while !*flag.lock().unwrap() {
@ -97,7 +104,7 @@ impl EventsLoop {
break; break;
} }
} }
} },
} }
} }
fn sleep(&self, lock: &Mutex<bool>, condvar: &Condvar) { fn sleep(&self, lock: &Mutex<bool>, condvar: &Condvar) {
@ -109,9 +116,9 @@ impl EventsLoop {
if *guard { if *guard {
return; return;
} }
let _ = condvar.wait_timeout( let _ = condvar
guard, time::Duration::from_millis(5) .wait_timeout(guard, time::Duration::from_millis(5))
).unwrap(); .unwrap();
} }
} }

View file

@ -7,29 +7,20 @@
use crate::events_loop::EventsLoop; use crate::events_loop::EventsLoop;
use crate::keyutils::keyboard_event_from_winit; use crate::keyutils::keyboard_event_from_winit;
use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT}; use crate::window_trait::{WindowPortsMethods, LINE_HEIGHT};
use euclid::{ use euclid::{Angle, Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector2D, Vector3D};
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};
#[cfg(any(target_os = "linux", target_os = "windows"))] #[cfg(any(target_os = "linux", target_os = "windows"))]
use image; use image;
use keyboard_types::{Key, KeyState, KeyboardEvent}; use keyboard_types::{Key, KeyState, KeyboardEvent};
use servo::compositing::windowing::{AnimationState, MouseWindowEvent, WindowEvent}; use servo::compositing::windowing::{AnimationState, MouseWindowEvent, WindowEvent};
use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods};
use servo::embedder_traits::Cursor; use servo::embedder_traits::Cursor;
use servo::script_traits::{TouchEventType, WheelMode, WheelDelta}; use servo::script_traits::{TouchEventType, WheelDelta, WheelMode};
use servo::servo_config::opts; use servo::servo_config::opts;
use servo::servo_config::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::ScrollLocation;
use servo::webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize}; use servo::webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};
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::cell::{Cell, RefCell};
@ -48,6 +39,14 @@ use surfman::GLVersion;
use surfman::SurfaceType; use surfman::SurfaceType;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
use winapi; 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")] #[cfg(target_os = "macos")]
fn builder_with_platform_options(mut builder: winit::WindowBuilder) -> winit::WindowBuilder { 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); 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"))] #[cfg(any(target_os = "linux", target_os = "windows"))]
{ {
@ -149,17 +150,17 @@ impl Window {
winit_window.show(); winit_window.show();
// Initialize surfman // Initialize surfman
let connection = Connection::from_winit_window(&winit_window).expect("Failed to create connection"); let connection =
let adapter = connection.create_adapter().expect("Failed to create adapter"); 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 let native_widget = connection
.create_native_widget_from_winit_window(&winit_window) .create_native_widget_from_winit_window(&winit_window)
.expect("Failed to create native widget"); .expect("Failed to create native widget");
let surface_type = SurfaceType::Widget { native_widget }; let surface_type = SurfaceType::Widget { native_widget };
let webrender_surfman = WebrenderSurfman::create( let webrender_surfman = WebrenderSurfman::create(&connection, &adapter, surface_type)
&connection, .expect("Failed to create WR surfman");
&adapter,
surface_type,
).expect("Failed to create WR surfman");
debug!("Created window {:?}", winit_window.id()); debug!("Created window {:?}", winit_window.id());
Window { Window {
@ -190,7 +191,8 @@ impl Window {
// shift ASCII control characters to lowercase // shift ASCII control characters to lowercase
ch = (ch as u8 + 96) as char; 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) (event, key_code)
} else if ch.is_ascii() { } else if ch.is_ascii() {
// Some keys like Backspace emit a control character in winit // 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 // to infer that it's related to this character and set the event
// properties appropriately. // properties appropriately.
if let Some(key_code) = key_code { 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) { 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(if state { Some(self.primary_monitor.clone()) } else { None }); Some(self.primary_monitor.clone())
} else {
None
});
} }
self.fullscreen.set(state); self.fullscreen.set(state);
} }
@ -433,8 +440,9 @@ impl WindowPortsMethods for Window {
}, },
winit::WindowEvent::MouseWheel { delta, phase, .. } => { winit::WindowEvent::MouseWheel { delta, phase, .. } => {
let (mut dx, mut dy, mode) = match delta { let (mut dx, mut dy, mode) = match delta {
MouseScrollDelta::LineDelta(dx, dy) => (dx as f64, (dy * LINE_HEIGHT) as f64, MouseScrollDelta::LineDelta(dx, dy) => {
WheelMode::DeltaLine), (dx as f64, (dy * LINE_HEIGHT) as f64, WheelMode::DeltaLine)
},
MouseScrollDelta::PixelDelta(position) => { MouseScrollDelta::PixelDelta(position) => {
let position = let position =
position.to_physical(self.device_hidpi_factor().get() as f64); 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 // 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 pos = self.mouse_pos.get();
let position = Point2D::new(pos.x as f32, pos.y as f32); let position = Point2D::new(pos.x as f32, pos.y as f32);
let wheel_event = WindowEvent::Wheel(wheel_delta, position); let wheel_event = 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 scroll_location = ScrollLocation::Delta(Vector2D::new(dx as f32, dy as f32));
let phase = winit_phase_to_touch_event_type(phase); let phase = winit_phase_to_touch_event_type(phase);
let scroll_event = WindowEvent::Scroll(scroll_location, self.mouse_pos.get(), phase); let scroll_event =
WindowEvent::Scroll(scroll_location, self.mouse_pos.get(), phase);
// Send events // Send events
self.event_queue.borrow_mut().push(wheel_event); self.event_queue.borrow_mut().push(wheel_event);
@ -489,7 +503,9 @@ impl WindowPortsMethods for Window {
if self.inner_size.get() != new_size { if self.inner_size.get() != new_size {
let physical_size = size.to_physical(self.device_hidpi_factor().get() as f64); let physical_size = size.to_physical(self.device_hidpi_factor().get() as f64);
let physical_size = Size2D::new(physical_size.width, physical_size.height); 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.inner_size.set(new_size);
self.event_queue.borrow_mut().push(WindowEvent::Resize); self.event_queue.borrow_mut().push(WindowEvent::Resize);
} }
@ -499,7 +515,9 @@ impl WindowPortsMethods for Window {
} }
fn new_glwindow(&self, events_loop: &EventsLoop) -> Box<dyn webxr::glwindow::GlWindow> { fn new_glwindow(&self, events_loop: &EventsLoop) -> Box<dyn webxr::glwindow::GlWindow> {
let size = self.winit_window.get_outer_size() let size = self
.winit_window
.get_outer_size()
.expect("Failed to get window outer size"); .expect("Failed to get window outer size");
let mut window_builder = winit::WindowBuilder::new() let mut window_builder = winit::WindowBuilder::new()
@ -509,7 +527,8 @@ impl WindowPortsMethods for Window {
window_builder = builder_with_platform_options(window_builder); 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."); .expect("Failed to create window.");
let pose = Rc::new(XRWindowPose { let pose = Rc::new(XRWindowPose {
@ -576,10 +595,12 @@ impl WindowMethods for Window {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
return match native_context { return match native_context {
NativeContext::Default(NativeContext::Default(native_context)) => NativeContext::Default(NativeContext::Default(native_context)) => {
PlayerGLContext::Egl(native_context.egl_context as usize), 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::Alternate(native_context)) => {
PlayerGLContext::Egl(native_context.egl_context as usize)
},
NativeContext::Alternate(_) => unimplemented!(), NativeContext::Alternate(_) => unimplemented!(),
}; };
@ -607,10 +628,12 @@ impl WindowMethods for Window {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
return match native_connection { return match native_connection {
NativeConnection::Default(NativeConnection::Default(conn)) => NativeConnection::Default(NativeConnection::Default(conn)) => {
NativeDisplay::Egl(conn.0 as usize), NativeDisplay::Egl(conn.0 as usize)
NativeConnection::Default(NativeConnection::Alternate(conn)) => },
NativeDisplay::X11(conn.x11_display as usize), NativeConnection::Default(NativeConnection::Alternate(conn)) => {
NativeDisplay::X11(conn.x11_display as usize)
},
NativeConnection::Alternate(_) => unimplemented!(), NativeConnection::Alternate(_) => unimplemented!(),
}; };
@ -671,8 +694,13 @@ struct XRWindowPose {
} }
impl webxr::glwindow::GlWindow for XRWindow { impl webxr::glwindow::GlWindow for XRWindow {
fn get_render_target(&self, device: &mut Device, _context: &mut Context) -> webxr::glwindow::GlWindowRenderTarget { fn get_render_target(
let native_widget = device.connection() &self,
device: &mut Device,
_context: &mut Context,
) -> webxr::glwindow::GlWindowRenderTarget {
let native_widget = device
.connection()
.create_native_widget_from_winit_window(&self.winit_window) .create_native_widget_from_winit_window(&self.winit_window)
.expect("Failed to create native widget"); .expect("Failed to create native widget");
webxr::glwindow::GlWindowRenderTarget::NativeWidget(native_widget) webxr::glwindow::GlWindowRenderTarget::NativeWidget(native_widget)

View file

@ -7,20 +7,20 @@
use crate::events_loop::EventsLoop; use crate::events_loop::EventsLoop;
use crate::window_trait::WindowPortsMethods; use crate::window_trait::WindowPortsMethods;
use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D}; use euclid::{Point2D, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D};
use winit;
use servo::compositing::windowing::{AnimationState, WindowEvent}; use servo::compositing::windowing::{AnimationState, WindowEvent};
use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods}; use servo::compositing::windowing::{EmbedderCoordinates, WindowMethods};
use servo::servo_geometry::DeviceIndependentPixel; use servo::servo_geometry::DeviceIndependentPixel;
use servo::style_traits::DevicePixel; use servo::style_traits::DevicePixel;
use servo::webrender_api::units::DeviceIntRect; use servo::webrender_api::units::DeviceIntRect;
use servo_media::player::context as MediaPlayerCtxt;
use servo::webrender_surfman::WebrenderSurfman; use servo::webrender_surfman::WebrenderSurfman;
use servo_media::player::context as MediaPlayerCtxt;
use std::cell::Cell; use std::cell::Cell;
use std::rc::Rc; use std::rc::Rc;
use surfman::Connection; use surfman::Connection;
use surfman::Context; use surfman::Context;
use surfman::Device; use surfman::Device;
use surfman::SurfaceType; use surfman::SurfaceType;
use winit;
pub struct Window { pub struct Window {
webrender_surfman: WebrenderSurfman, webrender_surfman: WebrenderSurfman,
@ -36,14 +36,13 @@ impl Window {
) -> Rc<dyn WindowPortsMethods> { ) -> Rc<dyn WindowPortsMethods> {
// Initialize surfman // Initialize surfman
let connection = Connection::new().expect("Failed to create connection"); 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 size = size.to_untyped().to_i32();
let surface_type = SurfaceType::Generic { size }; let surface_type = SurfaceType::Generic { size };
let webrender_surfman = WebrenderSurfman::create( let webrender_surfman = WebrenderSurfman::create(&connection, &adapter, surface_type)
&connection, .expect("Failed to create WR surfman");
&adapter,
surface_type,
).expect("Failed to create WR surfman");
let window = Window { let window = Window {
webrender_surfman, webrender_surfman,
@ -77,7 +76,8 @@ impl WindowPortsMethods for Window {
} }
fn page_height(&self) -> f32 { fn page_height(&self) -> f32 {
let height = self.webrender_surfman let height = self
.webrender_surfman
.context_surface_info() .context_surface_info()
.unwrap_or(None) .unwrap_or(None)
.map(|info| info.size.height) .map(|info| info.size.height)
@ -108,9 +108,10 @@ impl WindowPortsMethods for Window {
} }
impl WindowMethods for Window { impl WindowMethods for Window {
fn get_coordinates(&self) -> EmbedderCoordinates { fn get_coordinates(&self) -> EmbedderCoordinates {
let dpr = self.servo_hidpi_factor(); let dpr = self.servo_hidpi_factor();
let size = self.webrender_surfman let size = self
.webrender_surfman
.context_surface_info() .context_surface_info()
.unwrap_or(None) .unwrap_or(None)
.map(|info| Size2D::from_untyped(info.size)) .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); self.animation_state.set(state);
} }
fn get_gl_context(&self) -> MediaPlayerCtxt::GlContext { fn get_gl_context(&self) -> MediaPlayerCtxt::GlContext {
MediaPlayerCtxt::GlContext::Unknown MediaPlayerCtxt::GlContext::Unknown
} }
@ -148,7 +149,11 @@ impl WindowMethods for Window {
} }
impl webxr::glwindow::GlWindow 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!() unimplemented!()
} }

View file

@ -2,8 +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 winit::{ElementState, KeyboardInput, ModifiersState, VirtualKeyCode};
use keyboard_types::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers}; 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. // Some shortcuts use Cmd on Mac and Control on other systems.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]

View file

@ -2,14 +2,14 @@
* 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;
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::servo_config::basedir;
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use servo::servo_config::basedir;
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.
@ -24,30 +24,35 @@ pub fn register_user_prefs(opts_matches: &Matches) {
let mut userprefs = if let Some(path) = user_prefs_path { let mut userprefs = if let Some(path) = user_prefs_path {
let mut file = File::open(&path).expect("Error opening user prefs"); let mut file = File::open(&path).expect("Error opening user prefs");
let mut txt = String::new(); 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") prefs::read_prefs_map(&txt).expect("Can't parse user prefs file")
} else { } else {
HashMap::new() HashMap::new()
}; };
let argprefs: HashMap<String, PrefValue> = opts_matches.opt_strs("pref").iter().map(|pref| { let argprefs: HashMap<String, PrefValue> = opts_matches
let split: Vec<&str> = pref.splitn(2, '=').collect(); .opt_strs("pref")
let pref_name = split[0]; .iter()
let pref_value = match split.get(1).cloned() { .map(|pref| {
Some("true") | None => PrefValue::Bool(true), let split: Vec<&str> = pref.splitn(2, '=').collect();
Some("false") => PrefValue::Bool(false), let pref_name = split[0];
Some(string) => { let pref_value = match split.get(1).cloned() {
if let Some(int) = string.parse::<i64>().ok() { Some("true") | None => PrefValue::Bool(true),
PrefValue::Int(int) Some("false") => PrefValue::Bool(false),
} else if let Some(float) = string.parse::<f64>().ok() { Some(string) => {
PrefValue::Float(float) if let Some(int) = string.parse::<i64>().ok() {
} else { PrefValue::Int(int)
PrefValue::from(string) } else if let Some(float) = string.parse::<f64>().ok() {
} PrefValue::Float(float)
}, } else {
}; PrefValue::from(string)
(pref_name.to_string(), pref_value) }
}).collect(); },
};
(pref_name.to_string(), pref_value)
})
.collect();
// --pref overrides user prefs.json // --pref overrides user prefs.json
userprefs.extend(argprefs); userprefs.extend(argprefs);
@ -61,11 +66,7 @@ fn test_parse_pref(arg: &str) {
embedder_traits::resources::set_for_tests(); embedder_traits::resources::set_for_tests();
let mut opts = Options::new(); let mut opts = Options::new();
opts.optmulti("", "pref", "", ""); opts.optmulti("", "pref", "", "");
let args = vec![ let args = vec!["servo".to_string(), "--pref".to_string(), arg.to_string()];
"servo".to_string(),
"--pref".to_string(),
arg.to_string()
];
let matches = match opts::from_cmdline_args(opts, &args) { let matches = match opts::from_cmdline_args(opts, &args) {
ArgumentParsingResult::ContentProcess(m, _) => m, ArgumentParsingResult::ContentProcess(m, _) => m,
ArgumentParsingResult::ChromeProcess(m) => m, ArgumentParsingResult::ChromeProcess(m) => m,
@ -107,7 +108,6 @@ fn test_parse_pref_from_command_line() {
assert_eq!(pref!(dom.bluetooth.enabled), true); assert_eq!(pref!(dom.bluetooth.enabled), true);
} }
#[test] #[test]
fn test_invalid_prefs_from_command_line_panics() { fn test_invalid_prefs_from_command_line_panics() {
let err_msg = std::panic::catch_unwind(|| { let err_msg = std::panic::catch_unwind(|| {

View file

@ -6,10 +6,10 @@
//! Implemented by headless and headed windows. //! Implemented by headless and headed windows.
use crate::events_loop::EventsLoop; use crate::events_loop::EventsLoop;
use winit;
use servo::compositing::windowing::{WindowEvent, WindowMethods}; use servo::compositing::windowing::{WindowEvent, 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 winit;
// 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;

View file

@ -1 +1 @@
nightly-2020-09-27 nightly-2021-02-25