diff options
-rw-r--r-- | components/compositing/compositor.rs | 39 | ||||
-rw-r--r-- | components/compositing/compositor_task.rs | 4 | ||||
-rw-r--r-- | components/compositing/constellation.rs | 9 | ||||
-rw-r--r-- | components/devtools/actors/framerate.rs | 95 | ||||
-rw-r--r-- | components/devtools/actors/timeline.rs | 25 | ||||
-rw-r--r-- | components/devtools/lib.rs | 32 | ||||
-rw-r--r-- | components/devtools_traits/lib.rs | 2 | ||||
-rw-r--r-- | components/layout/animation.rs | 17 | ||||
-rw-r--r-- | components/msg/constellation_msg.rs | 10 | ||||
-rw-r--r-- | components/script/devtools.rs | 8 | ||||
-rw-r--r-- | components/script/dom/bindings/trace.rs | 7 | ||||
-rw-r--r-- | components/script/dom/document.rs | 75 | ||||
-rw-r--r-- | components/script/dom/webidls/Window.webidl | 7 | ||||
-rw-r--r-- | components/script/dom/window.rs | 25 | ||||
-rw-r--r-- | components/script/script_task.rs | 11 | ||||
-rw-r--r-- | components/script_traits/lib.rs | 4 | ||||
-rw-r--r-- | tests/html/test_request_animation_frame.html | 5 | ||||
-rw-r--r-- | tests/wpt/include.ini | 2 | ||||
-rw-r--r-- | tests/wpt/metadata/animation-timing/callback-invoked.html.ini | 4 |
19 files changed, 314 insertions, 67 deletions
diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index e09b0685d41..221dcf23f7f 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -27,6 +27,7 @@ use layers::rendergl; use layers::scene::Scene; use msg::compositor_msg::{Epoch, LayerId}; use msg::compositor_msg::{ReadyState, PaintState, ScrollPolicy}; +use msg::constellation_msg::AnimationState; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, NavigationDirection}; use msg::constellation_msg::{Key, KeyModifiers, KeyState, LoadData}; @@ -166,8 +167,11 @@ struct PipelineDetails { /// The status of this pipeline's PaintTask. paint_state: PaintState, - /// Whether animations are running. + /// Whether animations are running animations_running: bool, + + /// Whether there are animation callbacks + animation_callbacks_running: bool, } impl PipelineDetails { @@ -177,6 +181,7 @@ impl PipelineDetails { ready_state: ReadyState::Blank, paint_state: PaintState::Painting, animations_running: false, + animation_callbacks_running: false, } } } @@ -278,9 +283,9 @@ impl<Window: WindowMethods> IOCompositor<Window> { self.change_paint_state(pipeline_id, paint_state); } - (Msg::ChangeRunningAnimationsState(pipeline_id, running_animations), + (Msg::ChangeRunningAnimationsState(pipeline_id, animation_state), ShutdownState::NotShuttingDown) => { - self.change_running_animations_state(pipeline_id, running_animations); + self.change_running_animations_state(pipeline_id, animation_state); } (Msg::ChangePageTitle(pipeline_id, title), ShutdownState::NotShuttingDown) => { @@ -422,11 +427,22 @@ impl<Window: WindowMethods> IOCompositor<Window> { /// recomposite if necessary. fn change_running_animations_state(&mut self, pipeline_id: PipelineId, - animations_running: bool) { - self.get_or_create_pipeline_details(pipeline_id).animations_running = animations_running; - - if animations_running { - self.composite_if_necessary(CompositingReason::Animation); + animation_state: AnimationState) { + match animation_state { + AnimationState::AnimationsPresent => { + self.get_or_create_pipeline_details(pipeline_id).animations_running = true; + self.composite_if_necessary(CompositingReason::Animation); + } + AnimationState::AnimationCallbacksPresent => { + self.get_or_create_pipeline_details(pipeline_id).animation_callbacks_running = true; + self.composite_if_necessary(CompositingReason::Animation); + } + AnimationState::NoAnimationsPresent => { + self.get_or_create_pipeline_details(pipeline_id).animations_running = false; + } + AnimationState::NoAnimationCallbacksPresent => { + self.get_or_create_pipeline_details(pipeline_id).animation_callbacks_running = false; + } } } @@ -921,10 +937,11 @@ impl<Window: WindowMethods> IOCompositor<Window> { /// If there are any animations running, dispatches appropriate messages to the constellation. fn process_animations(&mut self) { for (pipeline_id, pipeline_details) in self.pipeline_details.iter() { - if !pipeline_details.animations_running { - continue + if pipeline_details.animations_running || + pipeline_details.animation_callbacks_running { + + self.constellation_chan.0.send(ConstellationMsg::TickAnimation(*pipeline_id)).unwrap(); } - self.constellation_chan.0.send(ConstellationMsg::TickAnimation(*pipeline_id)).unwrap(); } } diff --git a/components/compositing/compositor_task.rs b/components/compositing/compositor_task.rs index acafbbc8f9b..0f2b1249703 100644 --- a/components/compositing/compositor_task.rs +++ b/components/compositing/compositor_task.rs @@ -19,7 +19,7 @@ use layers::platform::surface::{NativeCompositingGraphicsContext, NativeGraphics use layers::layers::LayerBufferSet; use msg::compositor_msg::{Epoch, LayerId, LayerMetadata, ReadyState}; use msg::compositor_msg::{PaintListener, PaintState, ScriptListener, ScrollPolicy}; -use msg::constellation_msg::{ConstellationChan, PipelineId}; +use msg::constellation_msg::{AnimationState, ConstellationChan, PipelineId}; use msg::constellation_msg::{Key, KeyState, KeyModifiers}; use profile_traits::mem; use profile_traits::time; @@ -202,7 +202,7 @@ pub enum Msg { /// Alerts the compositor that the current page has changed its URL. ChangePageUrl(PipelineId, Url), /// Alerts the compositor that the given pipeline has changed whether it is running animations. - ChangeRunningAnimationsState(PipelineId, bool), + ChangeRunningAnimationsState(PipelineId, AnimationState), /// Alerts the compositor that a `PaintMsg` has been discarded. PaintMsgDiscarded, /// Replaces the current frame tree, typically called during main frame navigation. diff --git a/components/compositing/constellation.rs b/components/compositing/constellation.rs index a9271bc0cfd..5b69a678117 100644 --- a/components/compositing/constellation.rs +++ b/components/compositing/constellation.rs @@ -14,6 +14,7 @@ use gfx::font_cache_task::FontCacheTask; use layout_traits::{LayoutControlMsg, LayoutTaskFactory}; use libc; use msg::compositor_msg::LayerId; +use msg::constellation_msg::AnimationState; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{FrameId, PipelineExitType, PipelineId}; use msg::constellation_msg::{IFrameSandboxState, MozBrowserEvent, NavigationDirection}; @@ -344,8 +345,8 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { sandbox); } ConstellationMsg::SetCursor(cursor) => self.handle_set_cursor_msg(cursor), - ConstellationMsg::ChangeRunningAnimationsState(pipeline_id, animations_running) => { - self.handle_change_running_animations_state(pipeline_id, animations_running) + ConstellationMsg::ChangeRunningAnimationsState(pipeline_id, animation_state) => { + self.handle_change_running_animations_state(pipeline_id, animation_state) } ConstellationMsg::TickAnimation(pipeline_id) => { self.handle_tick_animation(pipeline_id) @@ -560,9 +561,9 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn handle_change_running_animations_state(&mut self, pipeline_id: PipelineId, - animations_running: bool) { + animation_state: AnimationState) { self.compositor_proxy.send(CompositorMsg::ChangeRunningAnimationsState(pipeline_id, - animations_running)) + animation_state)) } fn handle_tick_animation(&mut self, pipeline_id: PipelineId) { diff --git a/components/devtools/actors/framerate.rs b/components/devtools/actors/framerate.rs index 0cb82486342..3e02971a1ed 100644 --- a/components/devtools/actors/framerate.rs +++ b/components/devtools/actors/framerate.rs @@ -5,15 +5,23 @@ use rustc_serialize::json; use std::mem; use std::net::TcpStream; +use std::sync::{Arc, Mutex}; +use std::sync::mpsc::Sender; use time::precise_time_ns; +use msg::constellation_msg::PipelineId; use actor::{Actor, ActorRegistry}; +use actors::timeline::HighResolutionStamp; +use devtools_traits::{DevtoolsControlMsg, DevtoolScriptControlMsg}; pub struct FramerateActor { name: String, + pipeline: PipelineId, + script_sender: Sender<DevtoolScriptControlMsg>, + devtools_sender: Sender<DevtoolsControlMsg>, start_time: Option<u64>, - is_recording: bool, - ticks: Vec<u64>, + is_recording: Arc<Mutex<bool>>, + ticks: Arc<Mutex<Vec<HighResolutionStamp>>>, } impl Actor for FramerateActor { @@ -33,13 +41,19 @@ impl Actor for FramerateActor { impl FramerateActor { /// return name of actor - pub fn create(registry: &ActorRegistry) -> String { + pub fn create(registry: &ActorRegistry, + pipeline_id: PipelineId, + script_sender: Sender<DevtoolScriptControlMsg>, + devtools_sender: Sender<DevtoolsControlMsg>) -> String { let actor_name = registry.new_name("framerate"); let mut actor = FramerateActor { name: actor_name.clone(), + pipeline: pipeline_id, + script_sender: script_sender, + devtools_sender: devtools_sender, start_time: None, - is_recording: false, - ticks: Vec::new(), + is_recording: Arc::new(Mutex::new(false)), + ticks: Arc::new(Mutex::new(Vec::new())), }; actor.start_recording(); @@ -47,36 +61,71 @@ impl FramerateActor { actor_name } - // callback on request animation frame - #[allow(dead_code)] - pub fn on_refresh_driver_tick(&mut self) { - if !self.is_recording { - return; - } - // TODO: Need implement requesting animation frame - // http://hg.mozilla.org/mozilla-central/file/0a46652bd992/dom/base/nsGlobalWindow.cpp#l5314 - - let start_time = self.start_time.as_ref().unwrap(); - self.ticks.push(*start_time - precise_time_ns()); + pub fn add_tick(&self, tick: f64) { + let mut lock = self.ticks.lock(); + let mut ticks = lock.as_mut().unwrap(); + ticks.push(HighResolutionStamp::wrap(tick)); } - pub fn take_pending_ticks(&mut self) -> Vec<u64> { - mem::replace(&mut self.ticks, Vec::new()) + pub fn take_pending_ticks(&self) -> Vec<HighResolutionStamp> { + let mut lock = self.ticks.lock(); + let mut ticks = lock.as_mut().unwrap(); + mem::replace(ticks, Vec::new()) } fn start_recording(&mut self) { - self.is_recording = true; + let mut lock = self.is_recording.lock(); + if **lock.as_ref().unwrap() { + return; + } + self.start_time = Some(precise_time_ns()); + let is_recording = lock.as_mut(); + **is_recording.unwrap() = true; + + fn get_closure(is_recording: Arc<Mutex<bool>>, + name: String, + pipeline: PipelineId, + script_sender: Sender<DevtoolScriptControlMsg>, + devtools_sender: Sender<DevtoolsControlMsg>) + -> Box<Fn(f64, ) + Send> { + + let closure = move |now: f64| { + let msg = DevtoolsControlMsg::FramerateTick(name.clone(), now); + devtools_sender.send(msg).unwrap(); + + if !*is_recording.lock().unwrap() { + return; + } + + let closure = get_closure(is_recording.clone(), + name.clone(), + pipeline.clone(), + script_sender.clone(), + devtools_sender.clone()); + let msg = DevtoolScriptControlMsg::RequestAnimationFrame(pipeline, closure); + script_sender.send(msg).unwrap(); + }; + Box::new(closure) + }; - // TODO(#5681): Need implement requesting animation frame - // http://hg.mozilla.org/mozilla-central/file/0a46652bd992/dom/base/nsGlobalWindow.cpp#l5314 + let closure = get_closure(self.is_recording.clone(), + self.name(), + self.pipeline.clone(), + self.script_sender.clone(), + self.devtools_sender.clone()); + let msg = DevtoolScriptControlMsg::RequestAnimationFrame(self.pipeline, closure); + self.script_sender.send(msg).unwrap(); } fn stop_recording(&mut self) { - if !self.is_recording { + let mut lock = self.is_recording.lock(); + if !**lock.as_ref().unwrap() { return; } - self.is_recording = false; + + let is_recording = lock.as_mut(); + **is_recording.unwrap() = false; self.start_time = None; } diff --git a/components/devtools/actors/timeline.rs b/components/devtools/actors/timeline.rs index 12c361b279d..dc29b8a80b7 100644 --- a/components/devtools/actors/timeline.rs +++ b/components/devtools/actors/timeline.rs @@ -16,7 +16,7 @@ use time::PreciseTime; use actor::{Actor, ActorRegistry}; use actors::memory::{MemoryActor, TimelineMemoryReply}; use actors::framerate::FramerateActor; -use devtools_traits::DevtoolScriptControlMsg; +use devtools_traits::{DevtoolsControlMsg, DevtoolScriptControlMsg}; use devtools_traits::DevtoolScriptControlMsg::{SetTimelineMarkers, DropTimelineMarkers}; use devtools_traits::{TimelineMarker, TracingMetadata, TimelineMarkerType}; use protocol::JsonPacketStream; @@ -25,6 +25,7 @@ use util::task; pub struct TimelineActor { name: String, script_sender: Sender<DevtoolScriptControlMsg>, + devtools_sender: Sender<DevtoolsControlMsg>, marker_types: Vec<TimelineMarkerType>, pipeline: PipelineId, is_recording: Arc<Mutex<bool>>, @@ -93,21 +94,25 @@ struct FramerateEmitterReply { __type__: String, from: String, delta: HighResolutionStamp, - timestamps: Vec<u64>, + timestamps: Vec<HighResolutionStamp>, } /// HighResolutionStamp is struct that contains duration in milliseconds /// with accuracy to microsecond that shows how much time has passed since /// actor registry inited /// analog https://w3c.github.io/hr-time/#sec-DOMHighResTimeStamp -struct HighResolutionStamp(f64); +pub struct HighResolutionStamp(f64); impl HighResolutionStamp { - fn new(start_stamp: PreciseTime, time: PreciseTime) -> HighResolutionStamp { + pub fn new(start_stamp: PreciseTime, time: PreciseTime) -> HighResolutionStamp { let duration = start_stamp.to(time).num_microseconds() .expect("Too big duration in microseconds"); HighResolutionStamp(duration as f64 / 1000 as f64) } + + pub fn wrap(time: f64) -> HighResolutionStamp { + HighResolutionStamp(time) + } } impl Encodable for HighResolutionStamp { @@ -121,7 +126,8 @@ static DEFAULT_TIMELINE_DATA_PULL_TIMEOUT: u32 = 200; //ms impl TimelineActor { pub fn new(name: String, pipeline: PipelineId, - script_sender: Sender<DevtoolScriptControlMsg>) -> TimelineActor { + script_sender: Sender<DevtoolScriptControlMsg>, + devtools_sender: Sender<DevtoolsControlMsg>) -> TimelineActor { let marker_types = vec!(TimelineMarkerType::Reflow, TimelineMarkerType::DOMEvent); @@ -131,6 +137,7 @@ impl TimelineActor { pipeline: pipeline, marker_types: marker_types, script_sender: script_sender, + devtools_sender: devtools_sender, is_recording: Arc::new(Mutex::new(false)), stream: RefCell::new(None), @@ -248,7 +255,11 @@ impl Actor for TimelineActor { // init framerate actor if let Some(with_ticks) = msg.get("withTicks") { if let Some(true) = with_ticks.as_boolean() { - *self.framerate_actor.borrow_mut() = Some(FramerateActor::create(registry)); + let framerate_actor = Some(FramerateActor::create(registry, + self.pipeline.clone(), + self.script_sender.clone(), + self.devtools_sender.clone())); + *self.framerate_actor.borrow_mut() = framerate_actor; } } @@ -352,7 +363,7 @@ impl Emitter { if let Some(ref actor_name) = self.framerate_actor { let mut lock = self.registry.lock(); let registry = lock.as_mut().unwrap(); - let mut framerate_actor = registry.find_mut::<FramerateActor>(actor_name); + let framerate_actor = registry.find_mut::<FramerateActor>(actor_name); let framerateReply = FramerateEmitterReply { __type__: "framerate".to_string(), from: framerate_actor.name(), diff --git a/components/devtools/lib.rs b/components/devtools/lib.rs index c0b50147699..1e51abaaa86 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -31,11 +31,12 @@ extern crate url; use actor::{Actor, ActorRegistry}; use actors::console::ConsoleActor; use actors::network_event::{NetworkEventActor, EventActor, ResponseStartMsg}; -use actors::worker::WorkerActor; +use actors::framerate::FramerateActor; use actors::inspector::InspectorActor; use actors::root::RootActor; use actors::tab::TabActor; use actors::timeline::TimelineActor; +use actors::worker::WorkerActor; use protocol::JsonPacketStream; use devtools_traits::{ConsoleMessage, DevtoolsControlMsg, NetworkEvent}; @@ -170,12 +171,19 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, } } + fn handle_framerate_tick(actors: Arc<Mutex<ActorRegistry>>, actor_name: String, tick: f64) { + let actors = actors.lock().unwrap(); + let framerate_actor = actors.find::<FramerateActor>(&actor_name); + framerate_actor.add_tick(tick); + } + // We need separate actor representations for each script global that exists; // clients can theoretically connect to multiple globals simultaneously. // TODO: move this into the root or tab modules? fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>, ids: (PipelineId, Option<WorkerId>), - scriptSender: Sender<DevtoolScriptControlMsg>, + script_sender: Sender<DevtoolScriptControlMsg>, + devtools_sender: Sender<DevtoolsControlMsg>, actor_pipelines: &mut HashMap<PipelineId, String>, actor_workers: &mut HashMap<(PipelineId, WorkerId), String>, page_info: DevtoolsPageInfo) { @@ -187,7 +195,7 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, let (tab, console, inspector, timeline) = { let console = ConsoleActor { name: actors.new_name("console"), - script_chan: scriptSender.clone(), + script_chan: script_sender.clone(), pipeline: pipeline, streams: RefCell::new(Vec::new()), }; @@ -196,13 +204,14 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, walker: RefCell::new(None), pageStyle: RefCell::new(None), highlighter: RefCell::new(None), - script_chan: scriptSender.clone(), + script_chan: script_sender.clone(), pipeline: pipeline, }; let timeline = TimelineActor::new(actors.new_name("timeline"), pipeline, - scriptSender); + script_sender, + devtools_sender); let DevtoolsPageInfo { title, url } = page_info; let tab = TabActor { @@ -343,11 +352,12 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, } } + let sender_clone = sender.clone(); spawn_named("DevtoolsClientAcceptor".to_owned(), move || { // accept connections and process them, spawning a new task for each one for stream in listener.incoming() { // connection succeeded - sender.send(DevtoolsControlMsg::AddClient(stream.unwrap())).unwrap(); + sender_clone.send(DevtoolsControlMsg::AddClient(stream.unwrap())).unwrap(); } }); @@ -360,9 +370,10 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, handle_client(actors, stream.try_clone().unwrap()) }) } - Ok(DevtoolsControlMsg::ServerExitMsg) | Err(RecvError) => break, - Ok(DevtoolsControlMsg::NewGlobal(ids, scriptSender, pageinfo)) => - handle_new_global(actors.clone(), ids, scriptSender, &mut actor_pipelines, + Ok(DevtoolsControlMsg::FramerateTick(actor_name, tick)) => + handle_framerate_tick(actors.clone(), actor_name, tick), + Ok(DevtoolsControlMsg::NewGlobal(ids, script_sender, pageinfo)) => + handle_new_global(actors.clone(), ids, script_sender, sender.clone(), &mut actor_pipelines, &mut actor_workers, pageinfo), Ok(DevtoolsControlMsg::SendConsoleMessage(id, console_message)) => handle_console_message(actors.clone(), id, console_message, @@ -377,7 +388,8 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, // For now, the id of the first pipeline is passed handle_network_event(actors.clone(), connections, &actor_pipelines, &mut actor_requests, PipelineId(0), request_id, network_event); - } + }, + Ok(DevtoolsControlMsg::ServerExitMsg) | Err(RecvError) => break } } for connection in accepted_connections.iter_mut() { diff --git a/components/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index 4ab74a9e1de..54411122271 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -44,6 +44,7 @@ pub struct DevtoolsPageInfo { /// according to changes in the browser. pub enum DevtoolsControlMsg { AddClient(TcpStream), + FramerateTick(String, f64), NewGlobal((PipelineId, Option<WorkerId>), Sender<DevtoolScriptControlMsg>, DevtoolsPageInfo), SendConsoleMessage(PipelineId, ConsoleMessage), ServerExitMsg, @@ -121,6 +122,7 @@ pub enum DevtoolScriptControlMsg { WantsLiveNotifications(PipelineId, bool), SetTimelineMarkers(PipelineId, Vec<TimelineMarkerType>, Sender<TimelineMarker>), DropTimelineMarkers(PipelineId, Vec<TimelineMarkerType>), + RequestAnimationFrame(PipelineId, Box<Fn(f64, ) + Send>), } #[derive(RustcEncodable)] diff --git a/components/layout/animation.rs b/components/layout/animation.rs index 4bf5dd7ab6e..a2a3e1c5459 100644 --- a/components/layout/animation.rs +++ b/components/layout/animation.rs @@ -10,8 +10,9 @@ use incremental::{self, RestyleDamage}; use clock_ticks; use gfx::display_list::OpaqueNode; use layout_task::{LayoutTask, LayoutTaskData}; -use msg::constellation_msg::{Msg, PipelineId}; +use msg::constellation_msg::{AnimationState, Msg, PipelineId}; use script::layout_interface::Animation; +use script_traits::{ConstellationControlMsg, ScriptControlChan}; use std::mem; use std::sync::mpsc::Sender; use style::animation::{GetMod, PropertyAnimation}; @@ -51,11 +52,18 @@ pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: Pipelin rw_data.running_animations.push(animation) } - let animations_are_running = !rw_data.running_animations.is_empty(); + let animation_state; + if rw_data.running_animations.is_empty() { + animation_state = AnimationState::NoAnimationsPresent; + } else { + animation_state = AnimationState::AnimationsPresent; + } + rw_data.constellation_chan .0 - .send(Msg::ChangeRunningAnimationsState(pipeline_id, animations_are_running)) + .send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state)) .unwrap(); + } /// Recalculates style for an animation. This does *not* run with the DOM lock held. @@ -100,5 +108,8 @@ pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskDat rw_data.running_animations.push(running_animation) } } + + let ScriptControlChan(ref chan) = layout_task.script_chan; + chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap(); } diff --git a/components/msg/constellation_msg.rs b/components/msg/constellation_msg.rs index 40ddb0161dd..98743cdc650 100644 --- a/components/msg/constellation_msg.rs +++ b/components/msg/constellation_msg.rs @@ -223,7 +223,7 @@ pub enum Msg { /// Dispatch a mozbrowser event to a given iframe. Only available in experimental mode. MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent), /// Indicates whether this pipeline is currently running animations. - ChangeRunningAnimationsState(PipelineId, bool), + ChangeRunningAnimationsState(PipelineId, AnimationState), /// Requests that the constellation instruct layout to begin a new tick of the animation. TickAnimation(PipelineId), // Request that the constellation send the current root pipeline id over a provided channel @@ -236,6 +236,14 @@ pub enum Msg { WebDriverCommand(PipelineId, WebDriverScriptCommand) } +#[derive(Clone, Eq, PartialEq)] +pub enum AnimationState { + AnimationsPresent, + AnimationCallbacksPresent, + NoAnimationsPresent, + NoAnimationCallbacksPresent, +} + // https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events pub enum MozBrowserEvent { /// Sent when the scroll position within a browser <iframe> changes. diff --git a/components/script/devtools.rs b/components/script/devtools.rs index cdc0537fa15..d67f57b4e4f 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -14,7 +14,7 @@ use dom::node::{Node, NodeHelpers}; use dom::window::{WindowHelpers, ScriptHelpers}; use dom::element::Element; use dom::document::DocumentHelpers; -use page::Page; +use page::{IterablePage, Page}; use msg::constellation_msg::PipelineId; use script_task::{get_page, ScriptTask}; @@ -147,3 +147,9 @@ pub fn handle_drop_timeline_markers(page: &Rc<Page>, } } } + +pub fn handle_request_animation_frame(page: &Rc<Page>, id: PipelineId, callback: Box<Fn(f64, )>) { + let page = page.find(id).expect("There is no such page"); + let doc = page.document().root(); + doc.r().request_animation_frame(callback); +} diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index ab325ab804b..31f1a78f717 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -281,6 +281,13 @@ impl JSTraceable for Box<ScriptChan+Send> { } } +impl JSTraceable for Box<Fn(f64, )> { + #[inline] + fn trace(&self, _trc: *mut JSTracer) { + // Do nothing + } +} + impl<'a> JSTraceable for &'a str { #[inline] fn trace(&self, _: *mut JSTracer) { diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index f96dd134082..b5750f4a30c 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -11,6 +11,8 @@ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter; +use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{DocumentDerived, EventCast, HTMLBodyElementCast}; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLHeadElementCast, ElementCast}; use dom::bindings::codegen::InheritTypes::{DocumentTypeCast, HTMLHtmlElementCast, NodeCast}; @@ -63,6 +65,7 @@ use dom::window::{Window, WindowHelpers, ReflowReason}; use layout_interface::{HitTestResponse, MouseOverResponse}; use msg::compositor_msg::ScriptListener; +use msg::constellation_msg::AnimationState; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, FocusType, Key, KeyState, KeyModifiers, MozBrowserEvent}; use msg::constellation_msg::{SUPER, ALT, SHIFT, CONTROL}; @@ -82,11 +85,12 @@ use url::Url; use js::jsapi::JSRuntime; use num::ToPrimitive; +use std::iter::FromIterator; use std::borrow::ToOwned; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::ascii::AsciiExt; -use std::cell::{Cell, Ref}; +use std::cell::{Cell, Ref, RefCell}; use std::default::Default; use std::sync::mpsc::channel; use time; @@ -129,6 +133,12 @@ pub struct Document { /// https://html.spec.whatwg.org/multipage/#concept-n-noscript /// True if scripting is enabled for all scripts in this document scripting_enabled: Cell<bool>, + /// https://html.spec.whatwg.org/multipage/#animation-frame-callback-identifier + /// Current identifier of animation frame callback + animation_frame_ident: Cell<i32>, + /// https://html.spec.whatwg.org/multipage/#list-of-animation-frame-callbacks + /// List of animation frame callbacks + animation_frame_list: RefCell<HashMap<i32, Box<Fn(f64)>>>, } impl DocumentDerived for EventTarget { @@ -238,6 +248,12 @@ pub trait DocumentHelpers<'a> { fn set_current_script(self, script: Option<JSRef<HTMLScriptElement>>); fn trigger_mozbrowser_event(self, event: MozBrowserEvent); + /// http://w3c.github.io/animation-timing/#dom-windowanimationtiming-requestanimationframe + fn request_animation_frame(self, callback: Box<Fn(f64, )>) -> i32; + /// http://w3c.github.io/animation-timing/#dom-windowanimationtiming-cancelanimationframe + fn cancel_animation_frame(self, ident: i32); + /// http://w3c.github.io/animation-timing/#dfn-invoke-callbacks-algorithm + fn invoke_animation_callbacks(self); } impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { @@ -793,6 +809,61 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { } } } + + /// http://w3c.github.io/animation-timing/#dom-windowanimationtiming-requestanimationframe + fn request_animation_frame(self, callback: Box<Fn(f64, )>) -> i32 { + let window = self.window.root(); + let window = window.r(); + let ident = self.animation_frame_ident.get() + 1; + + self.animation_frame_ident.set(ident); + self.animation_frame_list.borrow_mut().insert(ident, callback); + + // TODO: Should tick animation only when document is visible + let ConstellationChan(ref chan) = window.constellation_chan(); + let event = ConstellationMsg::ChangeRunningAnimationsState(window.pipeline(), + AnimationState::AnimationCallbacksPresent); + chan.send(event).unwrap(); + + ident + } + + /// http://w3c.github.io/animation-timing/#dom-windowanimationtiming-cancelanimationframe + fn cancel_animation_frame(self, ident: i32) { + self.animation_frame_list.borrow_mut().remove(&ident); + if self.animation_frame_list.borrow().len() == 0 { + let window = self.window.root(); + let window = window.r(); + let ConstellationChan(ref chan) = window.constellation_chan(); + let event = ConstellationMsg::ChangeRunningAnimationsState(window.pipeline(), + AnimationState::NoAnimationCallbacksPresent); + chan.send(event).unwrap(); + } + } + + /// http://w3c.github.io/animation-timing/#dfn-invoke-callbacks-algorithm + fn invoke_animation_callbacks(self) { + let animation_frame_list; + { + let mut list = self.animation_frame_list.borrow_mut(); + animation_frame_list = Vec::from_iter(list.drain()); + + let window = self.window.root(); + let window = window.r(); + let ConstellationChan(ref chan) = window.constellation_chan(); + let event = ConstellationMsg::ChangeRunningAnimationsState(window.pipeline(), + AnimationState::NoAnimationCallbacksPresent); + chan.send(event).unwrap(); + } + let window = self.window.root(); + let window = window.r(); + let performance = window.Performance().root(); + let performance = performance.r(); + + for (_, callback) in animation_frame_list { + callback(*performance.Now()); + } + } } pub enum MouseEventType { @@ -870,6 +941,8 @@ impl Document { focused: Default::default(), current_script: Default::default(), scripting_enabled: Cell::new(true), + animation_frame_ident: Cell::new(0), + animation_frame_list: RefCell::new(HashMap::new()), } } diff --git a/components/script/dom/webidls/Window.webidl b/components/script/dom/webidls/Window.webidl index 8999d9e561d..08caf90004e 100644 --- a/components/script/dom/webidls/Window.webidl +++ b/components/script/dom/webidls/Window.webidl @@ -141,3 +141,10 @@ interface WindowLocalStorage { readonly attribute Storage localStorage; }; Window implements WindowLocalStorage; + +// http://w3c.github.io/animation-timing/#Window-interface-extensions +partial interface Window { + long requestAnimationFrame(FrameRequestCallback callback); + void cancelAnimationFrame(long handle); +}; +callback FrameRequestCallback = void (DOMHighResTimeStamp time); diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 5256b975172..facc50b51e9 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; +use dom::bindings::callback::ExceptionHandling; use dom::bindings::codegen::Bindings::EventHandlerBinding::{OnErrorEventHandlerNonNull, EventHandlerNonNull}; -use dom::bindings::codegen::Bindings::FunctionBinding::Function; -use dom::bindings::codegen::Bindings::WindowBinding; -use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; +use dom::bindings::codegen::Bindings::FunctionBinding::Function; +use dom::bindings::codegen::Bindings::WindowBinding::{self, WindowMethods, FrameRequestCallback}; use dom::bindings::codegen::InheritTypes::{NodeCast, EventTargetCast}; use dom::bindings::global::global_object_for_js_object; use dom::bindings::error::{report_pending_exception, Fallible}; @@ -15,6 +15,7 @@ use dom::bindings::error::Error::InvalidCharacter; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, JSRef, MutNullableHeap, OptionalRootable}; use dom::bindings::js::{Rootable, RootedReference, Temporary}; +use dom::bindings::num::Finite; use dom::bindings::utils::{GlobalStaticData, Reflectable, WindowProxyHandler}; use dom::browsercontext::BrowserContext; use dom::console::Console; @@ -464,6 +465,24 @@ impl<'a> WindowMethods for JSRef<'a, Window> { fn Atob(self, atob: DOMString) -> Fallible<DOMString> { base64_atob(atob) } + + /// http://w3c.github.io/animation-timing/#dom-windowanimationtiming-requestanimationframe + fn RequestAnimationFrame(self, callback: FrameRequestCallback) -> i32 { + let doc = self.Document().root(); + + let callback = move |now: f64| { + // TODO: @jdm The spec says that any exceptions should be suppressed; + callback.Call__(Finite::wrap(now), ExceptionHandling::Report).unwrap(); + }; + + doc.r().request_animation_frame(Box::new(callback)) + } + + /// http://w3c.github.io/animation-timing/#dom-windowanimationtiming-cancelanimationframe + fn CancelAnimationFrame(self, ident: i32) { + let doc = self.Document().root(); + doc.r().cancel_animation_frame(ident); + } } pub trait WindowHelpers { diff --git a/components/script/script_task.rs b/components/script/script_task.rs index ddd314b7a3a..534af2e081f 100644 --- a/components/script/script_task.rs +++ b/components/script/script_task.rs @@ -727,6 +727,8 @@ impl ScriptTask { ConstellationControlMsg::WebDriverCommand(pipeline_id, msg) => { self.handle_webdriver_msg(pipeline_id, msg); } + ConstellationControlMsg::TickAllAnimations(pipeline_id) => + self.handle_tick_all_animations(pipeline_id), } } @@ -776,6 +778,8 @@ impl ScriptTask { devtools::handle_set_timeline_markers(&page, self, marker_types, reply), DevtoolScriptControlMsg::DropTimelineMarkers(_pipeline_id, marker_types) => devtools::handle_drop_timeline_markers(&page, self, marker_types), + DevtoolScriptControlMsg::RequestAnimationFrame(pipeline_id, callback) => + devtools::handle_request_animation_frame(&page, pipeline_id, callback), } } @@ -1016,6 +1020,13 @@ impl ScriptTask { return false; } + /// Handles when layout task finishes all animation in one tick + fn handle_tick_all_animations(&self, id: PipelineId) { + let page = get_page(&self.root_page(), id); + let document = page.document().root(); + document.r().invoke_animation_callbacks(); + } + /// The entry point to document loading. Defines bindings, sets up the window and document /// objects, parses HTML and CSS, and kicks off initial layout. fn load(&self, response: LoadResponse, incomplete: InProgressLoad) { diff --git a/components/script_traits/lib.rs b/components/script_traits/lib.rs index 93ab1e49d58..62143373f0a 100644 --- a/components/script_traits/lib.rs +++ b/components/script_traits/lib.rs @@ -86,7 +86,9 @@ pub enum ConstellationControlMsg { /// Set an iframe to be focused. Used when an element in an iframe gains focus. FocusIFrame(PipelineId, SubpageId), // Passes a webdriver command to the script task for execution - WebDriverCommand(PipelineId, WebDriverScriptCommand) + WebDriverCommand(PipelineId, WebDriverScriptCommand), + /// Notifies script task that all animations are done + TickAllAnimations(PipelineId), } /// The mouse button involved in the event. diff --git a/tests/html/test_request_animation_frame.html b/tests/html/test_request_animation_frame.html new file mode 100644 index 00000000000..29ebac99348 --- /dev/null +++ b/tests/html/test_request_animation_frame.html @@ -0,0 +1,5 @@ +<script> +window.requestAnimationFrame(function (time) { + alert("time " + time); +}); +</script> diff --git a/tests/wpt/include.ini b/tests/wpt/include.ini index 8b2ae260cba..505beee1521 100644 --- a/tests/wpt/include.ini +++ b/tests/wpt/include.ini @@ -1,6 +1,8 @@ skip: true [2dcontext] skip: false +[animation-timing] + skip: false [dom] skip: false [domparsing] diff --git a/tests/wpt/metadata/animation-timing/callback-invoked.html.ini b/tests/wpt/metadata/animation-timing/callback-invoked.html.ini new file mode 100644 index 00000000000..60487ba50cc --- /dev/null +++ b/tests/wpt/metadata/animation-timing/callback-invoked.html.ini @@ -0,0 +1,4 @@ +[callback-invoked.html] + type: testharness + [requestAnimationFrame callback is invoked at least once before the timeout] + expected: FAIL |