Skip to content

Commit

Permalink
Implement matchMedia and MediaQueryList
Browse files Browse the repository at this point in the history
Fixes #13376.
  • Loading branch information
metajack committed Nov 2, 2016
1 parent 99ad367 commit 138a048
Show file tree
Hide file tree
Showing 22 changed files with 500 additions and 20 deletions.
1 change: 1 addition & 0 deletions components/script/Cargo.toml
Expand Up @@ -68,6 +68,7 @@ serde = "0.8"
smallvec = "0.1"
string_cache = {version = "0.2.26", features = ["heap_size", "unstable"]}
style = {path = "../style"}
style_traits = {path = "../style_traits"}
time = "0.1.12"
url = {version = "1.2", features = ["heap_size", "query_encoding"]}
util = {path = "../util"}
Expand Down
6 changes: 5 additions & 1 deletion components/script/dom/bindings/codegen/Bindings.conf
Expand Up @@ -14,12 +14,16 @@

DOMInterfaces = {

'MediaQueryList': {
'weakReferenceable': True,
},

'Promise': {
'spiderMonkeyInterface': True,
},

'Range': {
'weakReferenceable': True,
'weakReferenceable': True,
},

#FIXME(jdm): This should be 'register': False, but then we don't generate enum types
Expand Down
3 changes: 2 additions & 1 deletion components/script/dom/bindings/trace.rs
Expand Up @@ -90,6 +90,7 @@ use std::time::{SystemTime, Instant};
use string_cache::{Atom, Namespace, QualName};
use style::attr::{AttrIdentifier, AttrValue, LengthOrPercentageOrAuto};
use style::element_state::*;
use style::media_queries::MediaQueryList;
use style::properties::PropertyDeclarationBlock;
use style::selector_impl::{ElementSnapshot, PseudoElement};
use style::values::specified::Length;
Expand Down Expand Up @@ -366,7 +367,7 @@ no_jsmanaged_fields!(WebGLProgramId);
no_jsmanaged_fields!(WebGLRenderbufferId);
no_jsmanaged_fields!(WebGLShaderId);
no_jsmanaged_fields!(WebGLTextureId);

no_jsmanaged_fields!(MediaQueryList);

impl JSTraceable for Box<ScriptChan + Send> {
#[inline]
Expand Down
156 changes: 156 additions & 0 deletions components/script/dom/mediaquerylist.rs
@@ -0,0 +1,156 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use cssparser::ToCss;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::MediaQueryListBinding::{self, MediaQueryListMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::weakref::{WeakRef, WeakRefVec};
use dom::document::Document;
use dom::eventtarget::EventTarget;
use euclid::scale_factor::ScaleFactor;
use js::jsapi::JSTracer;
use std::cell::Cell;
use std::rc::Rc;
use style;
use style::media_queries::{Device, MediaType};
use style_traits::{PagePx, ViewportPx};

pub enum MediaQueryListMatchState {
Same(bool),
Changed(bool),
}

#[dom_struct]
pub struct MediaQueryList {
eventtarget: EventTarget,
document: JS<Document>,
media_query_list: style::media_queries::MediaQueryList,
last_match_state: Cell<Option<bool>>
}

impl MediaQueryList {
fn new_inherited(document: &Document,
media_query_list: style::media_queries::MediaQueryList) -> MediaQueryList {
MediaQueryList {
eventtarget: EventTarget::new_inherited(),
document: JS::from_ref(document),
media_query_list: media_query_list,
last_match_state: Cell::new(None),
}
}

pub fn new(document: &Document,
media_query_list: style::media_queries::MediaQueryList) -> Root<MediaQueryList> {
reflect_dom_object(box MediaQueryList::new_inherited(document, media_query_list),
document.window(),
MediaQueryListBinding::Wrap)
}
}

impl MediaQueryList {
fn evaluate_changes(&self) -> MediaQueryListMatchState {
let matches = self.evaluate();

let result = if let Some(old_matches) = self.last_match_state.get() {
if old_matches == matches {
MediaQueryListMatchState::Same(matches)
} else {
MediaQueryListMatchState::Changed(matches)
}
} else {
MediaQueryListMatchState::Changed(matches)
};

self.last_match_state.set(Some(matches));
result
}

pub fn evaluate(&self) -> bool {
if let Some(window_size) = self.document.window().window_size() {
let viewport_size = window_size.visible_viewport;
// TODO: support real ViewportPx, including zoom level
// This information seems not to be tracked currently, so we assume
// ViewportPx == PagePx
let page_to_viewport: ScaleFactor<f32, PagePx, ViewportPx> = ScaleFactor::new(1.0);
let device = Device::new(MediaType::Screen, viewport_size * page_to_viewport);
self.media_query_list.evaluate(&device)
} else {
false
}
}
}

impl MediaQueryListMethods for MediaQueryList {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-media
fn Media(&self) -> DOMString {
let mut s = String::new();
self.media_query_list.to_css(&mut s).unwrap();
DOMString::from_string(s)
}

// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches
fn Matches(&self) -> bool {
match self.last_match_state.get() {
None => self.evaluate(),
Some(state) => state,
}
}

// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-addlistener
fn AddListener(&self, listener: Option<Rc<EventListener>>) {
self.upcast::<EventTarget>().AddEventListener(DOMString::from_string("change".to_owned()),
listener, false);
}

// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-removelistener
fn RemoveListener(&self, listener: Option<Rc<EventListener>>) {
self.upcast::<EventTarget>().RemoveEventListener(DOMString::from_string("change".to_owned()),
listener, false);
}

// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-onchange
event_handler!(change, GetOnchange, SetOnchange);
}

#[derive(HeapSizeOf)]
pub struct WeakMediaQueryListVec {
cell: DOMRefCell<WeakRefVec<MediaQueryList>>,
}

#[allow(unsafe_code)]
impl WeakMediaQueryListVec {
/// Create a new vector of weak references to MediaQueryList
pub fn new() -> Self {
WeakMediaQueryListVec { cell: DOMRefCell::new(WeakRefVec::new()) }
}

pub fn push(&self, mql: &MediaQueryList) {
self.cell.borrow_mut().push(WeakRef::new(mql));
}

/// Evaluate media query lists and report changes
/// https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
pub fn evaluate_and_report_changes(&self) {
for mql in self.cell.borrow().iter() {
if let MediaQueryListMatchState::Changed(_) = mql.root().unwrap().evaluate_changes() {
mql.root().unwrap().upcast::<EventTarget>().fire_simple_event("change");
}
}
}
}

#[allow(unsafe_code)]
impl JSTraceable for WeakMediaQueryListVec {
fn trace(&self, _: *mut JSTracer) {
self.cell.borrow_mut().retain_alive()
}
}
1 change: 1 addition & 0 deletions components/script/dom/mod.rs
Expand Up @@ -357,6 +357,7 @@ pub mod imagedata;
pub mod keyboardevent;
pub mod location;
pub mod mediaerror;
pub mod mediaquerylist;
pub mod messageevent;
pub mod mimetype;
pub mod mimetypearray;
Expand Down
14 changes: 14 additions & 0 deletions components/script/dom/webidls/MediaQueryList.webidl
@@ -0,0 +1,14 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// https://drafts.csswg.org/cssom-view/#mediaquerylist

[Exposed=(Window)]
interface MediaQueryList : EventTarget {
readonly attribute DOMString media;
readonly attribute boolean matches;
void addListener(EventListener? listener);
void removeListener(EventListener? listener);
attribute EventHandler onchange;
};
2 changes: 1 addition & 1 deletion components/script/dom/webidls/Window.webidl
Expand Up @@ -120,7 +120,7 @@ dictionary ScrollToOptions : ScrollOptions {

// http://dev.w3.org/csswg/cssom-view/#extensions-to-the-window-interface
partial interface Window {
//MediaQueryList matchMedia(DOMString query);
[Exposed=(Window), NewObject] MediaQueryList matchMedia(DOMString query);
[SameObject] readonly attribute Screen screen;

// browsing context
Expand Down
25 changes: 25 additions & 0 deletions components/script/dom/window.rs
Expand Up @@ -3,6 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use app_units::Au;
use cssparser::Parser;
use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling;
use dom::bindings::cell::DOMRefCell;
Expand Down Expand Up @@ -35,6 +36,7 @@ use dom::globalscope::GlobalScope;
use dom::history::History;
use dom::htmliframeelement::build_mozbrowser_custom_event;
use dom::location::Location;
use dom::mediaquerylist::{MediaQueryList, WeakMediaQueryListVec};
use dom::messageevent::MessageEvent;
use dom::navigator::Navigator;
use dom::node::{Node, from_untrusted_node_address, window_from_node};
Expand Down Expand Up @@ -87,6 +89,7 @@ use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
use string_cache::Atom;
use style::context::ReflowGoal;
use style::error_reporting::ParseErrorReporter;
use style::media_queries;
use style::properties::longhands::overflow_x;
use style::selector_impl::PseudoElement;
use style::str::HTML_SPACE_CHARACTERS;
Expand Down Expand Up @@ -234,6 +237,9 @@ pub struct Window {

/// A list of scroll offsets for each scrollable element.
scroll_offsets: DOMRefCell<HashMap<UntrustedNodeAddress, Point2D<f32>>>,

/// All the MediaQueryLists we need to update
media_query_lists: WeakMediaQueryListVec,
}

impl Window {
Expand Down Expand Up @@ -310,6 +316,10 @@ impl Window {
pub fn set_scroll_offsets(&self, offsets: HashMap<UntrustedNodeAddress, Point2D<f32>>) {
*self.scroll_offsets.borrow_mut() = offsets
}

pub fn current_viewport(&self) -> Rect<Au> {
self.current_viewport.clone().get()
}
}

#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
Expand Down Expand Up @@ -857,6 +867,16 @@ impl WindowMethods for Window {
}
}

// https://drafts.csswg.org/cssom-view/#dom-window-matchmedia
fn MatchMedia(&self, query: DOMString) -> Root<MediaQueryList> {
let mut parser = Parser::new(&query);
let media_query_list = media_queries::parse_media_query_list(&mut parser);
let document = self.Document();
let mql = MediaQueryList::new(&document, media_query_list);
self.media_query_lists.push(&*mql);
mql
}

#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#fetch-method
fn Fetch(&self, input: RequestOrUSVString, init: &RequestInit) -> Rc<Promise> {
Expand Down Expand Up @@ -1486,6 +1506,10 @@ impl Window {
let custom_event = build_mozbrowser_custom_event(&self, event);
custom_event.upcast::<Event>().fire(self.upcast());
}

pub fn evaluate_media_queries_and_report_changes(&self) {
self.media_query_lists.evaluate_and_report_changes();
}
}

impl Window {
Expand Down Expand Up @@ -1572,6 +1596,7 @@ impl Window {
ignore_further_async_events: Arc::new(AtomicBool::new(false)),
error_reporter: error_reporter,
scroll_offsets: DOMRefCell::new(HashMap::new()),
media_query_lists: WeakMediaQueryListVec::new(),
};

WindowBinding::Wrap(runtime.cx(), win)
Expand Down
1 change: 1 addition & 0 deletions components/script/lib.rs
Expand Up @@ -82,6 +82,7 @@ extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
extern crate tinyfiledialogs;
Expand Down
5 changes: 5 additions & 0 deletions components/script/script_thread.rs
Expand Up @@ -2101,6 +2101,11 @@ impl ScriptThread {
0i32);
uievent.upcast::<Event>().fire(window.upcast());
}

// https://html.spec.whatwg.org/multipage/#event-loop-processing-model
// Step 7.7 - evaluate media queries and report changes
// Since we have resized, we need to re-evaluate MQLs
window.evaluate_media_queries_and_report_changes();
}

/// Initiate a non-blocking fetch for a specified resource. Stores the InProgressLoad
Expand Down
1 change: 1 addition & 0 deletions components/servo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions components/style/lib.rs
Expand Up @@ -135,6 +135,8 @@ pub mod values;
pub mod viewport;
pub mod workqueue;

use cssparser::ToCss;
use std::fmt;
use std::sync::Arc;

/// The CSS properties supported by the style system.
Expand Down Expand Up @@ -174,3 +176,16 @@ pub fn arc_ptr_eq<T: 'static>(a: &Arc<T>, b: &Arc<T>) -> bool {
let b: &T = &**b;
(a as *const T) == (b as *const T)
}

pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T])
-> fmt::Result where W: fmt::Write, T: ToCss {
if list.len() > 0 {
for item in &list[..list.len()-1] {
try!(item.to_css(dest));
try!(write!(dest, ", "));
}
list[list.len()-1].to_css(dest)
} else {
Ok(())
}
}

0 comments on commit 138a048

Please sign in to comment.