Skip to content

Commit

Permalink
Rework MediaType to be an atom-based struct instead of an enum.
Browse files Browse the repository at this point in the history
MozReview-Commit-ID: 1Tfrs9PBkhA
  • Loading branch information
bradwerth committed Aug 9, 2017
1 parent 77cb537 commit 557ffa9
Show file tree
Hide file tree
Showing 9 changed files with 92 additions and 72 deletions.
3 changes: 3 additions & 0 deletions components/atoms/static_atoms.txt
Expand Up @@ -70,3 +70,6 @@ gattserverdisconnected
onchange

reftest-wait

screen
print
4 changes: 2 additions & 2 deletions components/layout_thread/lib.rs
Expand Up @@ -481,7 +481,7 @@ impl LayoutThread {
// The device pixel ratio is incorrect (it does not have the hidpi value),
// but it will be set correctly when the initial reflow takes place.
let device = Device::new(
MediaType::Screen,
MediaType::screen(),
opts::get().initial_window_size.to_f32() * ScaleFactor::new(1.0),
ScaleFactor::new(opts::get().device_pixels_per_px.unwrap_or(1.0)));

Expand Down Expand Up @@ -1156,7 +1156,7 @@ impl LayoutThread {
let document_shared_lock = document.style_shared_lock();
self.document_shared_lock = Some(document_shared_lock.clone());
let author_guard = document_shared_lock.read();
let device = Device::new(MediaType::Screen, initial_viewport, device_pixel_ratio);
let device = Device::new(MediaType::screen(), initial_viewport, device_pixel_ratio);
self.stylist.set_device(device, &author_guard, &data.document_stylesheets);

self.viewport_size =
Expand Down
2 changes: 1 addition & 1 deletion components/script/dom/mediaquerylist.rs
Expand Up @@ -77,7 +77,7 @@ impl MediaQueryList {
if let Some(window_size) = self.document.window().window_size() {
let viewport_size = window_size.initial_viewport;
let device_pixel_ratio = window_size.device_pixel_ratio;
let device = Device::new(MediaType::Screen, viewport_size, device_pixel_ratio);
let device = Device::new(MediaType::screen(), viewport_size, device_pixel_ratio);
self.media_query_list.evaluate(&device, self.document.quirks_mode())
} else {
false
Expand Down
20 changes: 11 additions & 9 deletions components/style/gecko/media_queries.rs
Expand Up @@ -18,6 +18,7 @@ use gecko_bindings::structs::{nsCSSKeyword, nsCSSProps_KTableEntry, nsCSSValue,
use gecko_bindings::structs::{nsMediaExpression_Range, nsMediaFeature};
use gecko_bindings::structs::{nsMediaFeature_ValueType, nsMediaFeature_RangeType, nsMediaFeature_RequirementFlags};
use gecko_bindings::structs::{nsPresContext, RawGeckoPresContextOwned};
use gecko_bindings::structs::nsIAtom;
use media_queries::MediaType;
use parser::ParserContext;
use properties::{ComputedValues, StyleBuilder};
Expand All @@ -31,7 +32,7 @@ use string_cache::Atom;
use style_traits::{CSSPixel, DevicePixel};
use style_traits::{ToCss, ParseError, StyleParseError};
use style_traits::viewport::ViewportConstraints;
use values::{CSSFloat, specified};
use values::{CSSFloat, specified, CustomIdent};
use values::computed::{self, ToComputedValue};

/// The `Device` in Gecko wraps a pres context, has a default values computed,
Expand Down Expand Up @@ -140,15 +141,16 @@ impl Device {
/// Returns the current media type of the device.
pub fn media_type(&self) -> MediaType {
unsafe {
// FIXME(emilio): Gecko allows emulating random media with
// mIsEmulatingMedia / mMediaEmulated . Refactor both sides so that
// is supported (probably just making MediaType an Atom).
if self.pres_context().mMedium == atom!("screen").as_ptr() {
MediaType::Screen
// Gecko allows emulating random media with mIsEmulatingMedia and
// mMediaEmulated.
let context = self.pres_context();
let medium_to_use = if context.mIsEmulatingMedia() != 0 {
context.mMediaEmulated.raw::<nsIAtom>()
} else {
debug_assert!(self.pres_context().mMedium == atom!("print").as_ptr());
MediaType::Print
}
context.mMedium
};

MediaType(CustomIdent(Atom::from(medium_to_use)))
}
}

Expand Down
60 changes: 30 additions & 30 deletions components/style/media_queries.rs
Expand Up @@ -13,7 +13,9 @@ use parser::ParserContext;
use selectors::parser::SelectorParseError;
use serialize_comma_separated_list;
use std::fmt;
use str::string_as_ascii_lowercase;
use style_traits::{ToCss, ParseError, StyleParseError};
use values::CustomIdent;

#[cfg(feature = "servo")]
pub use servo::media_queries::{Device, Expression};
Expand Down Expand Up @@ -108,9 +110,7 @@ impl ToCss for MediaQuery {
write!(dest, "all")?;
}
},
MediaQueryType::Known(MediaType::Screen) => write!(dest, "screen")?,
MediaQueryType::Known(MediaType::Print) => write!(dest, "print")?,
MediaQueryType::Unknown(ref desc) => write!(dest, "{}", desc)?,
MediaQueryType::Concrete(MediaType(ref desc)) => desc.to_css(dest)?,
}

if self.expressions.is_empty() {
Expand All @@ -137,56 +137,56 @@ impl ToCss for MediaQuery {
pub enum MediaQueryType {
/// A media type that matches every device.
All,
/// A known media type, that we parse and understand.
Known(MediaType),
/// An unknown media type.
Unknown(Atom),
/// A specific media type.
Concrete(MediaType),
}

impl MediaQueryType {
fn parse(ident: &str) -> Result<Self, ()> {
match_ignore_ascii_case! { ident,
"all" => return Ok(MediaQueryType::All),
// From https://drafts.csswg.org/mediaqueries/#mq-syntax:
//
// The <media-type> production does not include the keywords only,
// not, and, and or.
"not" | "or" | "and" | "only" => return Err(()),
_ => (),
};

Ok(match MediaType::parse(ident) {
Some(media_type) => MediaQueryType::Known(media_type),
None => MediaQueryType::Unknown(Atom::from(ident)),
})
// If parseable, accept this type as a concrete type.
MediaType::parse(ident).map(MediaQueryType::Concrete)
}

fn matches(&self, other: MediaType) -> bool {
match *self {
MediaQueryType::All => true,
MediaQueryType::Known(ref known_type) => *known_type == other,
MediaQueryType::Unknown(..) => false,
MediaQueryType::Concrete(ref known_type) => *known_type == other,
}
}
}

/// https://drafts.csswg.org/mediaqueries/#media-types
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum MediaType {
/// The "screen" media type.
Screen,
/// The "print" media type.
Print,
}
pub struct MediaType(pub CustomIdent);

impl MediaType {
fn parse(name: &str) -> Option<Self> {
Some(match_ignore_ascii_case! { name,
"screen" => MediaType::Screen,
"print" => MediaType::Print,
_ => return None
})
/// The `screen` media type.
pub fn screen() -> Self {
MediaType(CustomIdent(atom!("screen")))
}

/// The `print` media type.
pub fn print() -> Self {
MediaType(CustomIdent(atom!("print")))
}

fn parse(name: &str) -> Result<Self, ()> {
// From https://drafts.csswg.org/mediaqueries/#mq-syntax:
//
// The <media-type> production does not include the keywords not, or, and, and only.
//
// Here we also perform the to-ascii-lowercase part of the serialization
// algorithm: https://drafts.csswg.org/cssom/#serializing-media-queries
match_ignore_ascii_case! { name,
"not" | "or" | "and" | "only" => Err(()),
_ => Ok(MediaType(CustomIdent(Atom::from(string_as_ascii_lowercase(name))))),
}
}
}
impl MediaQuery {
Expand Down
11 changes: 11 additions & 0 deletions components/style/str.rs
Expand Up @@ -8,6 +8,7 @@

use num_traits::ToPrimitive;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::convert::AsRef;
use std::iter::{Filter, Peekable};
use std::str::Split;
Expand Down Expand Up @@ -151,3 +152,13 @@ pub fn starts_with_ignore_ascii_case(string: &str, prefix: &str) -> bool {
string.len() >= prefix.len() &&
string.as_bytes()[0..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes())
}

/// Returns an ascii lowercase version of a string, only allocating if needed.
pub fn string_as_ascii_lowercase<'a>(input: &'a str) -> Cow<'a, str> {
if input.bytes().any(|c| matches!(c, b'A'...b'Z')) {
input.to_ascii_lowercase().into()
} else {
// Already ascii lowercase.
Cow::Borrowed(input)
}
}
46 changes: 25 additions & 21 deletions tests/unit/style/media_queries.rs
Expand Up @@ -15,7 +15,7 @@ use style::media_queries::*;
use style::servo::media_queries::*;
use style::shared_lock::SharedRwLock;
use style::stylesheets::{AllRules, Stylesheet, StylesheetInDocument, Origin, CssRule};
use style::values::specified;
use style::values::{CustomIdent, specified};
use style_traits::ToCss;

pub struct CSSErrorReporterTest;
Expand All @@ -40,7 +40,7 @@ fn test_media_rule<F>(css: &str, callback: F)
let stylesheet = Stylesheet::from_str(
css, url, Origin::Author, media_list, lock,
None, &CSSErrorReporterTest, QuirksMode::NoQuirks, 0u64);
let dummy = Device::new(MediaType::Screen, TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));
let dummy = Device::new(MediaType::screen(), TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));
let mut rule_count = 0;
let guard = stylesheet.shared_lock.read();
for rule in stylesheet.iter_rules::<AllRules>(&dummy, &guard) {
Expand Down Expand Up @@ -77,23 +77,23 @@ fn test_mq_screen() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Screen), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::screen()), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});

test_media_rule("@media only screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Screen), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::screen()), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});

test_media_rule("@media not screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Screen), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::screen()), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
Expand All @@ -104,23 +104,23 @@ fn test_mq_print() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Print), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::print()), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});

test_media_rule("@media only print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Print), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::print()), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});

test_media_rule("@media not print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Print), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::print()), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
Expand All @@ -131,23 +131,26 @@ fn test_mq_unknown() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Unknown(Atom::from("fridge")), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(
MediaType(CustomIdent(Atom::from("fridge")))), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});

test_media_rule("@media only glass { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::Unknown(Atom::from("glass")), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(
MediaType(CustomIdent(Atom::from("glass")))), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});

test_media_rule("@media not wood { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::Unknown(Atom::from("wood")), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(
MediaType(CustomIdent(Atom::from("wood")))), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
Expand Down Expand Up @@ -185,12 +188,12 @@ fn test_mq_or() {
assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0];
assert!(q0.qualifier == None, css.to_owned());
assert!(q0.media_type == MediaQueryType::Known(MediaType::Screen), css.to_owned());
assert!(q0.media_type == MediaQueryType::Concrete(MediaType::screen()), css.to_owned());
assert!(q0.expressions.len() == 0, css.to_owned());

let q1 = &list.media_queries[1];
assert!(q1.qualifier == None, css.to_owned());
assert!(q1.media_type == MediaQueryType::Known(MediaType::Print), css.to_owned());
assert!(q1.media_type == MediaQueryType::Concrete(MediaType::print()), css.to_owned());
assert!(q1.expressions.len() == 0, css.to_owned());
});
}
Expand Down Expand Up @@ -228,7 +231,7 @@ fn test_mq_expressions() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Screen), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::screen()), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match *q.expressions[0].kind_for_testing() {
ExpressionKind::Width(Range::Min(ref w)) => assert!(*w == specified::Length::from_px(100.)),
Expand All @@ -240,7 +243,7 @@ fn test_mq_expressions() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Print), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::print()), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match *q.expressions[0].kind_for_testing() {
ExpressionKind::Width(Range::Max(ref w)) => assert!(*w == specified::Length::from_px(43.)),
Expand All @@ -252,7 +255,7 @@ fn test_mq_expressions() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Print), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::print()), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match *q.expressions[0].kind_for_testing() {
ExpressionKind::Width(Range::Eq(ref w)) => assert!(*w == specified::Length::from_px(43.)),
Expand All @@ -264,7 +267,8 @@ fn test_mq_expressions() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::Unknown(Atom::from("fridge")), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(
MediaType(CustomIdent(Atom::from("fridge")))), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match *q.expressions[0].kind_for_testing() {
ExpressionKind::Width(Range::Max(ref w)) => assert!(*w == specified::Length::from_px(52.)),
Expand Down Expand Up @@ -305,7 +309,7 @@ fn test_mq_multiple_expressions() {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::Known(MediaType::Screen), css.to_owned());
assert!(q.media_type == MediaQueryType::Concrete(MediaType::screen()), css.to_owned());
assert!(q.expressions.len() == 2, css.to_owned());
match *q.expressions[0].kind_for_testing() {
ExpressionKind::Width(Range::Min(ref w)) => assert!(*w == specified::Length::from_px(100.)),
Expand Down Expand Up @@ -343,7 +347,7 @@ fn test_mq_malformed_expressions() {

#[test]
fn test_matching_simple() {
let device = Device::new(MediaType::Screen, TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));
let device = Device::new(MediaType::screen(), TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));

media_query_test(&device, "@media not all { a { color: red; } }", 0);
media_query_test(&device, "@media not screen { a { color: red; } }", 0);
Expand All @@ -359,7 +363,7 @@ fn test_matching_simple() {

#[test]
fn test_matching_width() {
let device = Device::new(MediaType::Screen, TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));
let device = Device::new(MediaType::screen(), TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));

media_query_test(&device, "@media { a { color: red; } }", 1);

Expand Down Expand Up @@ -400,7 +404,7 @@ fn test_matching_width() {

#[test]
fn test_matching_invalid() {
let device = Device::new(MediaType::Screen, TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));
let device = Device::new(MediaType::screen(), TypedSize2D::new(200.0, 100.0), ScaleFactor::new(1.0));

media_query_test(&device, "@media fridge { a { color: red; } }", 0);
media_query_test(&device, "@media screen and (height: 100px) { a { color: red; } }", 0);
Expand Down

0 comments on commit 557ffa9

Please sign in to comment.