servo: Merge #5753 - Start using on_refresh_driver_tick #5681 (from JIoJIaJIu:timeline); r=jdm

RequestAnimationFrame
[Task](https://github.com/servo/servo/issues/5681)

Source-Repo: https://github.com/servo/servo
Source-Revision: 5e59e77c416dbe35e8c30ca1c21c9088ed17a079
This commit is contained in:
Guro Bokum 2015-05-06 00:50:13 -05:00
Родитель 1599c829c0
Коммит 8059428350
17 изменённых файлов: 309 добавлений и 68 удалений

Просмотреть файл

@ -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();
}
}

Просмотреть файл

@ -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.

Просмотреть файл

@ -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) {

Просмотреть файл

@ -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;
self.start_time = Some(precise_time_ns());
let mut lock = self.is_recording.lock();
if **lock.as_ref().unwrap() {
return;
}
// TODO(#5681): Need implement requesting animation frame
// http://hg.mozilla.org/mozilla-central/file/0a46652bd992/dom/base/nsGlobalWindow.cpp#l5314
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)
};
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;
}

Просмотреть файл

@ -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(),

Просмотреть файл

@ -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() {

Просмотреть файл

@ -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)]

Просмотреть файл

@ -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();
}

Просмотреть файл

@ -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.

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -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) {

Просмотреть файл

@ -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()),
}
}

Просмотреть файл

@ -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);

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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) {

Просмотреть файл

@ -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.

Просмотреть файл

@ -0,0 +1,5 @@
<script>
window.requestAnimationFrame(function (time) {
alert("time " + time);
});
</script>