diff options
Diffstat (limited to 'components/script')
38 files changed, 232 insertions, 190 deletions
diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index 8b4d56891be..abe76755878 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -3,7 +3,7 @@ name = "script" version = "0.0.1" authors = ["The Servo Project Developers"] -build = "make -f makefile.cargo" +build = "build.rs" [lib] name = "script" @@ -50,7 +50,7 @@ git = "https://github.com/servo/html5ever" [dependencies.hyper] git = "https://github.com/servo/hyper" -branch = "old_servo_new_cookies" +branch = "servo" [dependencies.js] git = "https://github.com/servo/rust-mozjs" @@ -68,3 +68,5 @@ git = "https://github.com/servo/string-cache" encoding = "0.2" url = "0.2.16" time = "0.1.12" +bitflags = "*" +rustc-serialize = "*" diff --git a/components/script/build.rs b/components/script/build.rs new file mode 100644 index 00000000000..ca5ecaf9369 --- /dev/null +++ b/components/script/build.rs @@ -0,0 +1,18 @@ +/* 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/. */ + +#![feature(io)] + +use std::old_io::process::{Command, ProcessExit, StdioContainer}; + + +fn main() { + let result = Command::new("make") + .args(&["-f", "makefile.cargo"]) + .stdout(StdioContainer::InheritFd(1)) + .stderr(StdioContainer::InheritFd(2)) + .status() + .unwrap(); + assert_eq!(result, ProcessExit::ExitStatus(0)); +} diff --git a/components/script/cors.rs b/components/script/cors.rs index ebc2af7ec76..e326e891765 100644 --- a/components/script/cors.rs +++ b/components/script/cors.rs @@ -10,16 +10,16 @@ //! with CORSRequest being expanded into FetchRequest (etc) use std::ascii::AsciiExt; -use std::fmt::{self, Show}; +use std::fmt::{self, Display}; use std::str::from_utf8; use time; use time::{now, Timespec}; use hyper::header::{Headers, Header, HeaderFormat, HeaderView}; -use hyper::header::shared::util as header_util; +use hyper::header::parsing as header_parsing; use hyper::client::Request; use hyper::mime::{Mime, TopLevel, SubLevel}; -use hyper::header::common::{ContentType, Host}; +use hyper::header::{ContentType, Host}; use hyper::method::Method; use hyper::status::StatusClass::Success; @@ -160,6 +160,7 @@ impl CORSRequest { } cors_response.headers = response.headers.clone(); // Substeps 1-3 (parsing rules: http://fetch.spec.whatwg.org/#http-new-header-syntax) + let methods_substep4 = [self.method.clone()]; let mut methods = match response.headers.get() { Some(&AccessControlAllowMethods(ref v)) => v.as_slice(), _ => return error @@ -169,7 +170,6 @@ impl CORSRequest { _ => return error }; // Substep 4 - let methods_substep4 = [self.method.clone()]; if methods.len() == 0 || preflight.mode == RequestMode::ForcedPreflight { methods = methods_substep4.as_slice(); } @@ -388,19 +388,19 @@ struct AccessControlRequestMethod(pub Method); impl Header for AccessControlRequestMethod { #[inline] - fn header_name(_: Option<AccessControlRequestMethod>) -> &'static str { + fn header_name() -> &'static str { "Access-Control-Request-Method" } fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlRequestMethod> { - header_util::from_one_raw_str(raw).map(AccessControlRequestMethod) + header_parsing::from_one_raw_str(raw).map(AccessControlRequestMethod) } } impl HeaderFormat for AccessControlRequestMethod { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let AccessControlRequestMethod(ref method) = *self; - method.fmt(f) + <_ as Display>::fmt(method, f) } } @@ -409,19 +409,19 @@ struct AccessControlRequestHeaders(pub Vec<String>); impl Header for AccessControlRequestHeaders { #[inline] - fn header_name(_: Option<AccessControlRequestHeaders>) -> &'static str { + fn header_name() -> &'static str { "Access-Control-Request-Headers" } fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlRequestHeaders> { - header_util::from_comma_delimited(raw).map(AccessControlRequestHeaders) + header_parsing::from_comma_delimited(raw).map(AccessControlRequestHeaders) } } impl HeaderFormat for AccessControlRequestHeaders { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let AccessControlRequestHeaders(ref parts) = *self; - header_util::fmt_comma_delimited(f, parts.as_slice()) + header_parsing::fmt_comma_delimited(f, parts.as_slice()) } } @@ -430,19 +430,19 @@ struct AccessControlAllowMethods(pub Vec<Method>); impl Header for AccessControlAllowMethods { #[inline] - fn header_name(_: Option<AccessControlAllowMethods>) -> &'static str { + fn header_name() -> &'static str { "Access-Control-Allow-Methods" } fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlAllowMethods> { - header_util::from_comma_delimited(raw).map(AccessControlAllowMethods) + header_parsing::from_comma_delimited(raw).map(AccessControlAllowMethods) } } impl HeaderFormat for AccessControlAllowMethods { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let AccessControlAllowMethods(ref parts) = *self; - header_util::fmt_comma_delimited(f, parts.as_slice()) + header_parsing::fmt_comma_delimited(f, parts.as_slice()) } } @@ -451,19 +451,19 @@ struct AccessControlAllowHeaders(pub Vec<String>); impl Header for AccessControlAllowHeaders { #[inline] - fn header_name(_: Option<AccessControlAllowHeaders>) -> &'static str { + fn header_name() -> &'static str { "Access-Control-Allow-Headers" } fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlAllowHeaders> { - header_util::from_comma_delimited(raw).map(AccessControlAllowHeaders) + header_parsing::from_comma_delimited(raw).map(AccessControlAllowHeaders) } } impl HeaderFormat for AccessControlAllowHeaders { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let AccessControlAllowHeaders(ref parts) = *self; - header_util::fmt_comma_delimited(f, parts.as_slice()) + header_parsing::fmt_comma_delimited(f, parts.as_slice()) } } @@ -476,7 +476,7 @@ enum AccessControlAllowOrigin { impl Header for AccessControlAllowOrigin { #[inline] - fn header_name(_: Option<AccessControlAllowOrigin>) -> &'static str { + fn header_name() -> &'static str { "Access-Control-Allow-Origin" } @@ -498,8 +498,8 @@ impl Header for AccessControlAllowOrigin { impl HeaderFormat for AccessControlAllowOrigin { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - AccessControlAllowOrigin::AllowStar => "*".fmt(f), - AccessControlAllowOrigin::AllowOrigin(ref url) => url.fmt(f) + AccessControlAllowOrigin::AllowStar => <_ as Display>::fmt("*", f), + AccessControlAllowOrigin::AllowOrigin(ref url) => <_ as Display>::fmt(url, f) } } } @@ -509,19 +509,19 @@ struct AccessControlMaxAge(pub u32); impl Header for AccessControlMaxAge { #[inline] - fn header_name(_: Option<AccessControlMaxAge>) -> &'static str { + fn header_name() -> &'static str { "Access-Control-Max-Age" } fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlMaxAge> { - header_util::from_one_raw_str(raw).map(AccessControlMaxAge) + header_parsing::from_one_raw_str(raw).map(AccessControlMaxAge) } } impl HeaderFormat for AccessControlMaxAge { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let AccessControlMaxAge(ref num) = *self; - num.fmt(f) + <_ as Display>::fmt(num, f) } } diff --git a/components/script/devtools.rs b/components/script/devtools.rs index e5683d4819a..5333b9a4cee 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -2,7 +2,6 @@ * 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 devtools_traits; use devtools_traits::{EvaluateJSReply, NodeInfo, Modification}; use dom::bindings::conversions::FromJSValConvertible; use dom::bindings::conversions::StringificationBehavior; @@ -31,16 +30,16 @@ pub fn handle_evaluate_js(page: &Rc<Page>, pipeline: PipelineId, eval: String, r let rval = window.r().evaluate_js_on_global_with_result(eval.as_slice()); reply.send(if rval.is_undefined() { - devtools_traits::VoidValue + EvaluateJSReply::VoidValue } else if rval.is_boolean() { - devtools_traits::BooleanValue(rval.to_boolean()) + EvaluateJSReply::BooleanValue(rval.to_boolean()) } else if rval.is_double() { - devtools_traits::NumberValue(FromJSValConvertible::from_jsval(cx, rval, ()).unwrap()) + EvaluateJSReply::NumberValue(FromJSValConvertible::from_jsval(cx, rval, ()).unwrap()) } else if rval.is_string() { //FIXME: use jsstring_to_str when jsval grows to_jsstring - devtools_traits::StringValue(FromJSValConvertible::from_jsval(cx, rval, StringificationBehavior::Default).unwrap()) + EvaluateJSReply::StringValue(FromJSValConvertible::from_jsval(cx, rval, StringificationBehavior::Default).unwrap()) } else if rval.is_null() { - devtools_traits::NullValue + EvaluateJSReply::NullValue } else { //FIXME: jsvals don't have an is_int32/is_number yet assert!(rval.is_object()); diff --git a/components/script/dom/bindings/cell.rs b/components/script/dom/bindings/cell.rs index fc0a845b748..81085256821 100644 --- a/components/script/dom/bindings/cell.rs +++ b/components/script/dom/bindings/cell.rs @@ -10,7 +10,7 @@ use js::jsapi::{JSTracer}; use util::task_state; use util::task_state::{SCRIPT, IN_GC}; -use std::cell::{RefCell, Ref, RefMut}; +use std::cell::{BorrowState, RefCell, Ref, RefMut}; /// A mutable field in the DOM. /// @@ -52,7 +52,7 @@ impl<T> DOMRefCell<T> { /// /// For safety checks in debug builds only. pub fn is_mutably_borrowed(&self) -> bool { - self.value.try_borrow().is_some() + self.value.borrow_state() == BorrowState::Writing } /// Attempts to immutably borrow the wrapped value. @@ -67,7 +67,10 @@ impl<T> DOMRefCell<T> { /// Panics if this is called off the script thread. pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { debug_assert!(task_state::get().is_script()); - self.value.try_borrow() + match self.value.borrow_state() { + BorrowState::Writing => None, + _ => Some(self.value.borrow()), + } } /// Mutably borrows the wrapped value. @@ -82,7 +85,10 @@ impl<T> DOMRefCell<T> { /// Panics if this is called off the script thread. pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { debug_assert!(task_state::get().is_script()); - self.value.try_borrow_mut() + match self.value.borrow_state() { + BorrowState::Unused => Some(self.value.borrow_mut()), + _ => None, + } } } diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index edb64705c3e..1fdf13f5fe7 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1800,7 +1800,7 @@ def CreateBindingJSObject(descriptor, parent=None): assert not descriptor.isGlobal() create += """ let handler = RegisterBindings::proxy_handlers[PrototypeList::Proxies::%s as uint]; -let mut private = PrivateValue(squirrel_away_unique(object) as *const libc::c_void); +let mut private = PrivateValue(boxed::into_raw(object) as *const libc::c_void); let obj = with_compartment(cx, proto, || { NewProxyObject(cx, handler, &private, @@ -1820,7 +1820,7 @@ assert!(!obj.is_null());\ assert!(!obj.is_null()); JS_SetReservedSlot(obj, DOM_OBJECT_SLOT as u32, - PrivateValue(squirrel_away_unique(object) as *const libc::c_void));""" + PrivateValue(boxed::into_raw(object) as *const libc::c_void));""" return create class CGWrapMethod(CGAbstractMethod): @@ -3015,8 +3015,11 @@ class CGUnionConversionStruct(CGThing): pre="fn from_jsval(cx: *mut JSContext, value: JSVal, _option: ()) -> Result<%s, ()> {\n" % self.type, post="\n}") return CGWrapper( - CGIndenter(method), - pre="impl FromJSValConvertible for %s {\ntype Config = ();\n" % self.type, + CGIndenter(CGList([ + CGGeneric("type Config = ();"), + method, + ], "\n")), + pre="impl FromJSValConvertible for %s {\n" % self.type, post="\n}") def try_method(self, t): @@ -3978,7 +3981,7 @@ let this: *const %s = unwrap::<%s>(obj); def finalizeHook(descriptor, hookName, context): release = """\ let value = unwrap::<%s>(obj); -let _: Box<%s> = mem::transmute(value); +let _ = Box::from_raw(value as *mut %s); debug!("%s finalize: {:p}", this);\ """ % (descriptor.concreteType, descriptor.concreteType, descriptor.concreteType) return release @@ -4557,7 +4560,6 @@ class CGBindingRoot(CGThing): 'dom::bindings::utils::has_property_on_prototype', 'dom::bindings::utils::is_platform_object', 'dom::bindings::utils::{Reflectable}', - 'dom::bindings::utils::{squirrel_away_unique}', 'dom::bindings::utils::throwing_constructor', 'dom::bindings::utils::get_dictionary_property', 'dom::bindings::utils::{NativeProperties, NativePropertyHooks}', @@ -4587,6 +4589,7 @@ class CGBindingRoot(CGThing): 'libc', 'util::str::DOMString', 'std::borrow::ToOwned', + 'std::boxed', 'std::cmp', 'std::iter::repeat', 'std::mem', @@ -5239,10 +5242,10 @@ class GlobalGenRoots(): impl ${selfName} for ${baseName} { #[inline] fn ${fname}(&self) -> bool { -let base: &${parentName} = ${parentName}Cast::from_actual(self); + let base: &${parentName} = ${parentName}Cast::from_actual(self); base.${fname}() } -}\ +} """).substitute({'fname': 'is_' + name.lower(), 'selfName': name + 'Derived', 'baseName': protoDescriptor.concreteType, @@ -5251,9 +5254,10 @@ let base: &${parentName} = ${parentName}Cast::from_actual(self); derived += [CGGeneric('\n')] cast = [CGGeneric(string.Template("""\ -pub trait ${castTraitName} : Sized { +pub struct ${name}Cast; +impl ${name}Cast { #[inline(always)] - fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, Self>> { + pub fn to_ref<'a, T: ${toBound}+Reflectable>(base: JSRef<'a, T>) -> Option<JSRef<'a, ${name}>> { match base.${checkFn}() { true => unsafe { Some(base.transmute()) }, false => None @@ -5261,7 +5265,7 @@ pub trait ${castTraitName} : Sized { } #[inline(always)] - fn to_borrowed_ref<'a, 'b, T: ${toBound}+Reflectable>(base: &'a JSRef<'b, T>) -> Option<&'a JSRef<'b, Self>> { + pub fn to_borrowed_ref<'a, 'b, T: ${toBound}+Reflectable>(base: &'a JSRef<'b, T>) -> Option<&'a JSRef<'b, ${name}>> { match base.${checkFn}() { true => unsafe { Some(base.transmute_borrowed()) }, false => None @@ -5270,7 +5274,7 @@ pub trait ${castTraitName} : Sized { #[inline(always)] #[allow(unrooted_must_root)] - fn to_layout_js<T: ${toBound}+Reflectable>(base: &LayoutJS<T>) -> Option<LayoutJS<Self>> { + pub fn to_layout_js<T: ${toBound}+Reflectable>(base: &LayoutJS<T>) -> Option<LayoutJS<${name}>> { unsafe { match (*base.unsafe_get()).${checkFn}() { true => Some(base.transmute_copy()), @@ -5280,30 +5284,29 @@ pub trait ${castTraitName} : Sized { } #[inline(always)] - fn from_ref<'a, T: ${fromBound}+Reflectable>(derived: JSRef<'a, T>) -> JSRef<'a, Self> { + pub fn from_ref<'a, T: ${fromBound}+Reflectable>(derived: JSRef<'a, T>) -> JSRef<'a, ${name}> { unsafe { derived.transmute() } } #[inline(always)] - fn from_borrowed_ref<'a, 'b, T: ${fromBound}+Reflectable>(derived: &'a JSRef<'b, T>) -> &'a JSRef<'b, Self> { + pub fn from_borrowed_ref<'a, 'b, T: ${fromBound}+Reflectable>(derived: &'a JSRef<'b, T>) -> &'a JSRef<'b, ${name}> { unsafe { derived.transmute_borrowed() } } #[inline(always)] - fn from_temporary<T: ${fromBound}+Reflectable>(derived: Temporary<T>) -> Temporary<Self> { + pub fn from_temporary<T: ${fromBound}+Reflectable>(derived: Temporary<T>) -> Temporary<${name}> { unsafe { derived.transmute() } } #[inline(always)] - fn from_actual<'a, T: ${fromBound}+Reflectable>(derived: &T) -> &'a Self { + pub fn from_actual<'a, T: ${fromBound}+Reflectable>(derived: &T) -> &'a ${name} { unsafe { mem::transmute(derived) } } } """).substitute({'checkFn': 'is_' + name.lower(), - 'castTraitName': name + 'Cast', + 'name': name, 'fromBound': name + 'Base', - 'toBound': name + 'Derived'})), - CGGeneric("impl %s for %s {}\n\n" % (name + 'Cast', name))] + 'toBound': name + 'Derived'}))] allprotos += protos + derived + cast diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index 529c24ac2d6..62f71cea5d6 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -308,7 +308,7 @@ pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { unsafe { let mut length = 0; let chars = JS_GetStringCharsAndLength(cx, s, &mut length); - let char_vec = slice::from_raw_buf(&chars, length as uint); + let char_vec = slice::from_raw_parts(chars, length as uint); String::from_utf16(char_vec).unwrap() } } @@ -367,7 +367,7 @@ impl FromJSValConvertible for ByteString { let mut length = 0; let chars = JS_GetStringCharsAndLength(cx, string, &mut length); - let char_vec = slice::from_raw_buf(&chars, length as uint); + let char_vec = slice::from_raw_parts(chars, length as uint); if char_vec.iter().any(|&c| c > 0xFF) { // XXX Throw diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index bed13bcc32d..806e3c21ffe 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -20,7 +20,7 @@ use std::ffi::CString; use std::ptr; /// DOM exceptions that can be thrown by a native DOM method. -#[derive(Show, Clone)] +#[derive(Debug, Clone)] pub enum Error { /// IndexSizeError IndexSize, diff --git a/components/script/dom/bindings/js.rs b/components/script/dom/bindings/js.rs index 970281c2977..a842583cecb 100644 --- a/components/script/dom/bindings/js.rs +++ b/components/script/dom/bindings/js.rs @@ -83,6 +83,14 @@ impl<T: Reflectable> Unrooted<T> { } } + /// Create a new unrooted value from a `JS<T>`. + #[allow(unrooted_must_root)] + pub fn from_js(ptr: JS<T>) -> Unrooted<T> { + Unrooted { + ptr: ptr.ptr + } + } + /// Get the `Reflector` for this pointer. pub fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { @@ -189,7 +197,7 @@ pub struct JS<T> { impl<T> JS<T> { /// Returns `LayoutJS<T>` containing the same pointer. - fn to_layout(self) -> LayoutJS<T> { + pub unsafe fn to_layout(self) -> LayoutJS<T> { LayoutJS { ptr: self.ptr.clone() } @@ -283,7 +291,7 @@ impl<U: Reflectable> JS<U> { impl<T: Reflectable> Reflectable for JS<T> { fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { - (*self.unsafe_get()).reflector() + (**self.ptr).reflector() } } } @@ -382,16 +390,10 @@ impl<T: Reflectable> MutNullableJS<T> { self.ptr.get().map(Temporary::new) } - /// Retrieve a copy of the inner optional `JS<T>`. For use by layout, which - /// can't use safe types like Temporary. - pub unsafe fn get_inner(&self) -> Option<JS<T>> { - self.ptr.get() - } - /// Retrieve a copy of the inner optional `JS<T>` as `LayoutJS<T>`. /// For use by layout, which can't use safe types like Temporary. pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutJS<T>> { - self.get_inner().map(|js| js.to_layout()) + self.ptr.get().map(|js| js.to_layout()) } /// Retrieve a copy of the current inner value. If it is `None`, it is @@ -411,12 +413,6 @@ impl<T: Reflectable> MutNullableJS<T> { } impl<T: Reflectable> JS<T> { - /// Returns an unsafe pointer to the interior of this object. - /// This should only be used by the DOM bindings. - pub unsafe fn unsafe_get(&self) -> *const T { - *self.ptr - } - /// Store an unrooted value in this field. This is safe under the /// assumption that JS<T> values are only used as fields in DOM types that /// are reachable in the GC graph, so this unrooted value becomes diff --git a/components/script/dom/bindings/str.rs b/components/script/dom/bindings/str.rs index f9ac9947af8..54ad9c45fb3 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -152,7 +152,8 @@ impl Hash<SipHasher> for ByteString { } impl FromStr for ByteString { - fn from_str(s: &str) -> Option<ByteString> { - Some(ByteString::new(s.to_owned().into_bytes())) + type Err = (); + fn from_str(s: &str) -> Result<ByteString, ()> { + Ok(ByteString::new(s.to_owned().into_bytes())) } } diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index 5737830994d..2dfb35d3f48 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -57,7 +57,7 @@ use std::collections::HashMap; use std::collections::hash_state::HashState; use std::ffi::CString; use std::hash::{Hash, Hasher}; -use std::io::timer::Timer; +use std::old_io::timer::Timer; use std::rc::Rc; use std::sync::mpsc::{Receiver, Sender}; use string_cache::{Atom, Namespace}; diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index 5c68dfce33d..568d52eba46 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -15,9 +15,9 @@ use dom::window; use libc; use libc::c_uint; +use std::boxed; use std::cell::Cell; use std::ffi::CString; -use std::mem; use std::ptr; use js::glue::UnwrapObject; use js::glue::{IsWrapper, RUST_JSID_IS_INT, RUST_JSID_TO_INT}; @@ -64,11 +64,6 @@ impl GlobalStaticData { } } -/// Leak the given pointer. -pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *const T { - mem::transmute(x) -} - // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. @@ -343,7 +338,7 @@ pub fn initialize_global(global: *mut JSObject) { ([0 as *mut JSObject; PrototypeList::ID::Count as uint]); unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0); - let box_ = squirrel_away_unique(proto_array); + let box_ = boxed::into_raw(proto_array); JS_SetReservedSlot(global, DOM_PROTOTYPE_SLOT, PrivateValue(box_ as *const libc::c_void)); diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index e76ab04d92b..103fc2a1f78 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -129,7 +129,7 @@ impl<'a> BlobMethods for JSRef<'a, Blob> { let start = relativeStart.to_uint().unwrap(); let end = (relativeStart + span).to_uint().unwrap(); let mut bytes: Vec<u8> = Vec::new(); - bytes.push_all(vec.slice(start, end)); + bytes.push_all(&vec[start..end]); Blob::new(global.r(), Some(bytes), relativeContentType.as_slice()) } } diff --git a/components/script/dom/characterdata.rs b/components/script/dom/characterdata.rs index 0ea9ef1e0cd..598fc11213e 100644 --- a/components/script/dom/characterdata.rs +++ b/components/script/dom/characterdata.rs @@ -81,7 +81,7 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { } fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> { - Ok(self.data.borrow().as_slice().slice(offset as uint, count as uint).to_owned()) + Ok(self.data.borrow()[offset as uint .. count as uint].to_owned()) } fn AppendData(self, arg: DOMString) -> ErrorResult { @@ -107,9 +107,9 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { } else { count }; - let mut data = self.data.borrow().as_slice().slice(0, offset as uint).to_owned(); + let mut data = self.data.borrow()[..offset as uint].to_owned(); data.push_str(arg.as_slice()); - data.push_str(self.data.borrow().as_slice().slice((offset + count) as uint, length as uint)); + data.push_str(&self.data.borrow()[(offset + count) as uint..]); *self.data.borrow_mut() = data; // FIXME: Once we have `Range`, we should implement step7 to step11 Ok(()) diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index cff30395d2a..4dec1c3bd45 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -7,7 +7,7 @@ use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use devtools_traits::{SendConsoleMessage, ConsoleMessage}; +use devtools_traits::{DevtoolsControlMsg, ConsoleMessage}; use util::str::DOMString; #[dom_struct] @@ -68,7 +68,8 @@ fn propagate_console_msg(console: &JSRef<Console>, console_message: ConsoleMessa GlobalRef::Window(window_ref) => { let pipelineId = window_ref.page().id; console.global.root().r().as_window().page().devtools_chan.as_ref().map(|chan| { - chan.send(SendConsoleMessage(pipelineId, console_message.clone())).unwrap(); + chan.send(DevtoolsControlMsg::SendConsoleMessage( + pipelineId, console_message.clone())).unwrap(); }); }, diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index c38cd80dd20..c6304d08d20 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -775,7 +775,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { root.traverse_preorder() .find(|node| node.type_id() == NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement))) .map(|title_elem| { - let mut children = title_elem.children().filter_map(|n| { + let children = title_elem.children().filter_map(|n| { let t: Option<JSRef<Text>> = TextCast::to_ref(n); t }); diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index 98a17d50d51..f28ea1f9eff 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -14,7 +14,7 @@ use util::str::DOMString; use std::borrow::ToOwned; #[repr(uint)] -#[derive(Copy, Show)] +#[derive(Copy, Debug)] #[jstraceable] pub enum DOMErrorName { IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR as uint, diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 69eb3f2ee23..ad1e70b30d1 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -92,7 +92,7 @@ impl ElementDerived for EventTarget { } } -#[derive(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Debug)] #[jstraceable] pub enum ElementTypeId { HTMLElement(HTMLElementTypeId), @@ -163,7 +163,7 @@ unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name // cast to point to T in RefCell<T> directly let attrs = elem.attrs.borrow_for_layout(); attrs.iter().find(|attr: & &JS<Attr>| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); *name == (*attr).local_name_atom_forever() && (*attr).namespace() == namespace }) @@ -174,7 +174,7 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &Atom) -> Option<&'a str> { get_attr_for_layout(self, namespace, name).map(|attr| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); (*attr).value_ref_forever() }) } @@ -183,7 +183,7 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &Atom) -> Vec<&'a str> { let attrs = self.attrs.borrow_for_layout(); (*attrs).iter().filter_map(|attr: &JS<Attr>| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); if *name == (*attr).local_name_atom_forever() { Some((*attr).value_ref_forever()) } else { @@ -197,11 +197,11 @@ impl RawLayoutElementHelpers for Element { -> Option<Atom> { let attrs = self.attrs.borrow_for_layout(); (*attrs).iter().find(|attr: & &JS<Attr>| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); *name == (*attr).local_name_atom_forever() && (*attr).namespace() == namespace }).and_then(|attr| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); (*attr).value_atom_forever() }) } @@ -210,10 +210,10 @@ impl RawLayoutElementHelpers for Element { unsafe fn has_class_for_layout(&self, name: &Atom) -> bool { let attrs = self.attrs.borrow_for_layout(); (*attrs).iter().find(|attr: & &JS<Attr>| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); (*attr).local_name_atom_forever() == atom!("class") }).map_or(false, |attr| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); (*attr).value_tokens_forever().map(|tokens| { tokens.iter().any(|atom| atom == name) }) @@ -224,10 +224,10 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]> { let attrs = self.attrs.borrow_for_layout(); (*attrs).iter().find(|attr: & &JS<Attr>| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); (*attr).local_name_atom_forever() == atom!("class") }).and_then(|attr| { - let attr = attr.unsafe_get(); + let attr = attr.to_layout().unsafe_get(); (*attr).value_tokens_forever() }) } @@ -1404,8 +1404,8 @@ impl<'a> style::node::TElement<'a> for JSRef<'a, Element> { has_class(self, name) } - fn each_class<F>(self, callback: F) - where F: Fn(&Atom) + fn each_class<F>(self, mut callback: F) + where F: FnMut(&Atom) { match self.get_attribute(ns!(""), &atom!("class")).root() { None => {} diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 85f3279aa9b..5d8e5a8f809 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -88,9 +88,7 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { match (*self.data.borrow())[name][0].clone() { FormDatum::StringData(ref s) => Some(eString(s.clone())), FormDatum::FileData(ref f) => { - Some(eFile(unsafe { - Unrooted::from_raw(f.unsafe_get()) - })) + Some(eFile(Unrooted::from_js(*f))) } } } else { diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 06a9456913c..e609169ff05 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -107,7 +107,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { EventTargetCast::from_ref(*self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, - name.slice_from(2), + &name[2..], attr.value().as_slice().to_owned()); } diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 243c51e3b90..161e72ddc69 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -165,9 +165,7 @@ impl HTMLCollection { } fn traverse<'a>(root: JSRef<'a, Node>) - -> FilterMap<JSRef<'a, Node>, - JSRef<'a, Element>, - Skip<TreeIterator<'a>>, + -> FilterMap<Skip<TreeIterator<'a>>, fn(JSRef<Node>) -> Option<JSRef<Element>>> { root.traverse_preorder() .skip(1) diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index c5a8249fc14..dd5cd1cb7e0 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -200,13 +200,13 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLElement> { window.r().reflector().get_jsobject()); let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self); evtarget.set_event_handler_uncompiled(cx, url, reflector, - name.slice_from(2), + &name[2..], attr.value().as_slice().to_owned()); } } } -#[derive(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Debug)] #[jstraceable] pub enum HTMLElementTypeId { HTMLElement, diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 04b1c5019c3..be6f1fc9fcb 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -23,7 +23,7 @@ use dom::htmlbuttonelement::{HTMLButtonElement}; use dom::htmltextareaelement::{HTMLTextAreaElement, HTMLTextAreaElementHelpers}; use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node}; use hyper::method::Method; -use hyper::header::common::ContentType; +use hyper::header::ContentType; use hyper::mime; use msg::constellation_msg::LoadData; use util::str::DOMString; @@ -332,7 +332,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { // TODO: Handle `dirnames` (needs directionality support) // https://html.spec.whatwg.org/multipage/dom.html#the-directionality let mut ret: Vec<FormDatum> = data_set.collect(); - for mut datum in ret.iter_mut() { + for datum in ret.iter_mut() { match datum.ty.as_slice() { "file" | "textarea" => (), _ => { diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index d8bfc492f42..73613b8fcee 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -317,7 +317,7 @@ fn broadcast_radio_checked(broadcaster: JSRef<HTMLInputElement>, group: Option<& fn do_broadcast<'a>(doc_node: JSRef<'a, Node>, broadcaster: JSRef<'a, HTMLInputElement>, owner: Option<JSRef<'a, HTMLFormElement>>, group: Option<&str>) { // There is no DOM tree manipulation here, so this is safe - let mut iter = unsafe { + let iter = unsafe { doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap() .filter_map(|t| HTMLInputElementCast::to_ref(t)) .filter(|&r| in_same_group(r, owner, group) && broadcaster != r) diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 0105d08d226..331d43e8aba 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -38,7 +38,7 @@ impl HTMLMediaElement { } } -#[derive(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Debug)] #[jstraceable] pub enum HTMLMediaElementTypeId { HTMLAudioElement, diff --git a/components/script/dom/htmlserializer.rs b/components/script/dom/htmlserializer.rs index a0ab5b82d03..7d0cc77387c 100644 --- a/components/script/dom/htmlserializer.rs +++ b/components/script/dom/htmlserializer.rs @@ -22,7 +22,7 @@ pub fn serialize(iterator: &mut NodeIterator) -> String { let mut html = String::new(); let mut open_elements: Vec<String> = vec!(); let depth = iterator.depth; - for node in *iterator { + for node in iterator { while open_elements.len() > depth { html.push_str("</"); html.push_str(open_elements.pop().unwrap().as_slice()); diff --git a/components/script/dom/htmltablecellelement.rs b/components/script/dom/htmltablecellelement.rs index e847ba6afd0..6d9c20626da 100644 --- a/components/script/dom/htmltablecellelement.rs +++ b/components/script/dom/htmltablecellelement.rs @@ -16,7 +16,7 @@ use cssparser::RGBA; use util::str::{self, DOMString, LengthOrPercentageOrAuto}; use std::cell::Cell; -#[derive(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Debug)] #[jstraceable] pub enum HTMLTableCellElementTypeId { HTMLTableDataCellElement, diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 5bb79e827f0..253e987e454 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -261,7 +261,7 @@ impl LayoutDataRef { unsafe impl Send for LayoutDataRef {} /// The different types of nodes. -#[derive(Copy, PartialEq, Show)] +#[derive(Copy, PartialEq, Debug)] #[jstraceable] pub enum NodeTypeId { DocumentType, @@ -1020,10 +1020,7 @@ impl RawLayoutNodeHelpers for Node { // pub type ChildElementIterator<'a> = - Peekable<JSRef<'a, Element>, - FilterMap<JSRef<'a, Node>, - JSRef<'a, Element>, - NodeChildrenIterator<'a>, + Peekable<FilterMap<NodeChildrenIterator<'a>, fn(JSRef<Node>) -> Option<JSRef<Element>>>>; pub struct NodeChildrenIterator<'a> { @@ -1666,7 +1663,7 @@ impl Node { } } - pub fn collect_text_contents<'a, T: Iterator<Item=JSRef<'a, Node>>>(mut iterator: T) -> String { + pub fn collect_text_contents<'a, T: Iterator<Item=JSRef<'a, Node>>>(iterator: T) -> String { let mut content = String::new(); for node in iterator { let text: Option<JSRef<Text>> = TextCast::to_ref(node); diff --git a/components/script/dom/servohtmlparser.rs b/components/script/dom/servohtmlparser.rs index 1a2fd4fe564..c41cdcdd93c 100644 --- a/components/script/dom/servohtmlparser.rs +++ b/components/script/dom/servohtmlparser.rs @@ -92,7 +92,8 @@ struct Tracer { trc: *mut JSTracer, } -impl tree_builder::Tracer<JS<Node>> for Tracer { +impl tree_builder::Tracer for Tracer { + type Handle = JS<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: JS<Node>) { node.trace(self.trc); @@ -107,7 +108,7 @@ impl JSTraceable for ServoHTMLParser { let tracer = Tracer { trc: trc, }; - let tracer = &tracer as &tree_builder::Tracer<JS<Node>>; + let tracer = &tracer as &tree_builder::Tracer<Handle=JS<Node>>; unsafe { // Assertion: If the parser is mutably borrowed, we're in the diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 1564d77541a..5fc5e5fcf17 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -47,7 +47,7 @@ use js::rust::with_compartment; use url::{Url, UrlParser}; use libc; -use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; +use serialize::base64::{FromBase64, ToBase64, STANDARD}; use std::cell::{Ref, RefMut}; use std::default::Default; use std::ffi::CString; @@ -140,7 +140,7 @@ pub fn base64_btoa(btoa: DOMString) -> Fallible<DOMString> { // http://www.whatwg.org/html/#atob pub fn base64_atob(atob: DOMString) -> Fallible<DOMString> { // "Let input be the string being parsed." - let mut input = atob.as_slice(); + let input = atob.as_slice(); // "Remove all space characters from input." // serialize::base64::from_base64 ignores \r and \n, @@ -152,16 +152,16 @@ pub fn base64_atob(atob: DOMString) -> Fallible<DOMString> { let without_spaces = input.chars() .filter(|&c| ! is_html_space(c)) .collect::<String>(); - input = without_spaces.as_slice(); + let mut input = without_spaces.as_slice(); // "If the length of input divides by 4 leaving no remainder, then: // if input ends with one or two U+003D EQUALS SIGN (=) characters, // remove them from input." if input.len() % 4 == 0 { if input.ends_with("==") { - input = input.slice_to(input.len() - 2) + input = &input[..input.len() - 2] } else if input.ends_with("=") { - input = input.slice_to(input.len() - 1) + input = &input[..input.len() - 1] } } @@ -385,10 +385,13 @@ impl<'a> WindowHelpers for JSRef<'a, Window> { let url = UrlParser::new().base_url(&base_url).parse(href.as_slice()); // FIXME: handle URL parse errors more gracefully. let url = url.unwrap(); - if href.as_slice().starts_with("#") { - self.script_chan.send(ScriptMsg::TriggerFragment(self.page.id, url)); - } else { - self.script_chan.send(ScriptMsg::TriggerLoad(self.page.id, LoadData::new(url))); + match url.fragment { + Some(fragment) => { + self.script_chan.send(ScriptMsg::TriggerFragment(self.page.id, fragment)); + }, + None => { + self.script_chan.send(ScriptMsg::TriggerLoad(self.page.id, LoadData::new(url))); + } } } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index f9f75fbbf7e..5bef26a7c84 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -33,8 +33,7 @@ use encoding::label::encoding_from_whatwg_label; use encoding::types::{DecoderTrap, Encoding, EncodingRef, EncoderTrap}; use hyper::header::Headers; -use hyper::header::common::{Accept, ContentLength, ContentType}; -use hyper::header::quality_item::QualityItem; +use hyper::header::{Accept, ContentLength, ContentType, QualityItem}; use hyper::http::RawStatus; use hyper::mime::{self, Mime}; use hyper::method::Method; @@ -55,7 +54,7 @@ use std::borrow::ToOwned; use std::cell::Cell; use std::sync::mpsc::{Sender, Receiver, channel}; use std::default::Default; -use std::io::Timer; +use std::old_io::Timer; use std::str::FromStr; use std::time::duration::Duration; use time; @@ -361,8 +360,8 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { match upper.as_slice() { "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "CONNECT" | "TRACE" | - "TRACK" => upper.parse(), - _ => s.parse() + "TRACK" => upper.parse().ok(), + _ => s.parse().ok() } }); // Step 2 @@ -830,7 +829,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // Substep 2 status.map(|RawStatus(code, reason)| { self.status.set(code); - *self.status_text.borrow_mut() = ByteString::new(reason.into_bytes()); + *self.status_text.borrow_mut() = ByteString::new(reason.into_owned().into_bytes()); }); headers.as_ref().map(|h| *self.response_headers.borrow_mut() = h.clone()); @@ -990,13 +989,13 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // http://fetch.spec.whatwg.org/#concept-response-header-list use std::fmt; use hyper::header::{Header, HeaderFormat}; - use hyper::header::common::SetCookie; + use hyper::header::SetCookie; // a dummy header so we can use headers.remove::<SetCookie2>() #[derive(Clone)] struct SetCookie2; impl Header for SetCookie2 { - fn header_name(_: Option<SetCookie2>) -> &'static str { + fn header_name() -> &'static str { "set-cookie2" } diff --git a/components/script/layout_interface.rs b/components/script/layout_interface.rs index ff2f643fd63..c82370207cf 100644 --- a/components/script/layout_interface.rs +++ b/components/script/layout_interface.rs @@ -77,7 +77,7 @@ pub struct HitTestResponse(pub UntrustedNodeAddress); pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>); /// Why we're doing reflow. -#[derive(PartialEq, Show)] +#[derive(PartialEq, Debug)] pub enum ReflowGoal { /// We're reflowing in order to send a display list to the screen. ForDisplay, diff --git a/components/script/lib.rs b/components/script/lib.rs index e3cc44e9f49..cedb7d361d5 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -2,18 +2,30 @@ * 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/. */ -#![feature(unsafe_destructor, plugin, box_syntax, int_uint)] +#![feature(alloc)] +#![feature(box_syntax)] +#![feature(collections)] +#![feature(core)] +#![feature(hash)] +#![feature(int_uint)] +#![feature(io)] +#![feature(libc)] +#![feature(plugin)] +#![feature(rustc_private)] +#![feature(std_misc)] +#![feature(unicode)] +#![feature(unsafe_destructor)] #![deny(unsafe_blocks)] #![allow(non_snake_case)] #![allow(missing_copy_implementations)] -#![allow(unstable)] #![doc="The script crate contains all matters DOM."] #[macro_use] extern crate log; +#[macro_use] extern crate bitflags; extern crate core; extern crate devtools_traits; extern crate cssparser; @@ -26,7 +38,7 @@ extern crate js; extern crate libc; extern crate msg; extern crate net; -extern crate "rustc-serialize" as rustc_serialize; +extern crate "rustc-serialize" as serialize; extern crate time; extern crate canvas; extern crate script_traits; diff --git a/components/script/page.rs b/components/script/page.rs index 55729fd3591..b369a5e3337 100644 --- a/components/script/page.rs +++ b/components/script/page.rs @@ -327,25 +327,19 @@ impl Page { /// layout task has finished any pending request messages. fn join_layout(&self) { let mut layout_join_port = self.layout_join_port.borrow_mut(); - if layout_join_port.is_some() { - let join_port = replace(&mut *layout_join_port, None); - match join_port { - Some(ref join_port) => { - match join_port.try_recv() { - Err(Empty) => { - info!("script: waiting on layout"); - join_port.recv().unwrap(); - } - Ok(_) => {} - Err(Disconnected) => { - panic!("Layout task failed while script was waiting for a result."); - } - } - - debug!("script: layout joined") + if let Some(join_port) = replace(&mut *layout_join_port, None) { + match join_port.try_recv() { + Err(Empty) => { + info!("script: waiting on layout"); + join_port.recv().unwrap(); + } + Ok(_) => {} + Err(Disconnected) => { + panic!("Layout task failed while script was waiting for a result."); } - None => panic!("reader forked but no join port?"), } + + debug!("script: layout joined") } } diff --git a/components/script/parse/html.rs b/components/script/parse/html.rs index 387d031ff6c..6da3dac1ec8 100644 --- a/components/script/parse/html.rs +++ b/components/script/parse/html.rs @@ -55,7 +55,8 @@ impl SinkHelpers for servohtmlparser::Sink { } } -impl<'a> TreeSink<JS<Node>> for servohtmlparser::Sink { +impl<'a> TreeSink for servohtmlparser::Sink { + type Handle = JS<Node>; fn get_document(&mut self) -> JS<Node> { let doc = self.document.root(); let node: JSRef<Node> = NodeCast::from_ref(doc.r()); @@ -162,6 +163,10 @@ impl<'a> TreeSink<JS<Node>> for servohtmlparser::Sink { let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(node.r()); script.map(|script| script.prepare()); } + + fn reparent_children(&mut self, _node: JS<Node>, _new_parent: JS<Node>) { + panic!("unimplemented") + } } pub fn parse_html(document: JSRef<Document>, diff --git a/components/script/script_task.rs b/components/script/script_task.rs index 4b64700b8bc..8573efa9d3f 100644 --- a/components/script/script_task.rs +++ b/components/script/script_task.rs @@ -31,7 +31,7 @@ use dom::htmlelement::HTMLElementTypeId; use dom::htmliframeelement::HTMLIFrameElement; use dom::keyboardevent::KeyboardEvent; use dom::mouseevent::MouseEvent; -use dom::node::{self, Node, NodeHelpers, NodeDamage, NodeTypeId}; +use dom::node::{self, Node, NodeHelpers, NodeDamage, NodeTypeId, window_from_node}; use dom::window::{Window, WindowHelpers, ScriptHelpers}; use dom::worker::{Worker, TrustedWorkerAddress}; use parse::html::{HTMLInput, parse_html}; @@ -41,9 +41,8 @@ use page::{Page, IterablePage, Frame}; use timers::TimerId; use devtools; -use devtools_traits::{DevtoolsControlChan, DevtoolsControlPort, NewGlobal, GetRootNode, DevtoolsPageInfo}; -use devtools_traits::{DevtoolScriptControlMsg, EvaluateJS, GetDocumentElement}; -use devtools_traits::{GetChildren, GetLayout, ModifyAttribute, WantsLiveNotifications}; +use devtools_traits::{DevtoolsControlChan, DevtoolsControlPort, DevtoolsPageInfo}; +use devtools_traits::{DevtoolsControlMsg, DevtoolScriptControlMsg}; use script_traits::CompositorEvent; use script_traits::CompositorEvent::{ResizeEvent, ReflowEvent, ClickEvent}; use script_traits::CompositorEvent::{MouseDownEvent, MouseUpEvent}; @@ -71,7 +70,7 @@ use util::task_state; use geom::point::Point2D; use hyper::header::{Header, Headers, HeaderFormat}; -use hyper::header::shared::util as header_util; +use hyper::header::parsing as header_parsing; use js::jsapi::{JS_SetWrapObjectCallbacks, JS_SetGCZeal, JS_DEFAULT_ZEAL_FREQ, JS_GC}; use js::jsapi::{JSContext, JSRuntime, JSObject}; use js::jsapi::{JS_SetGCParameter, JSGC_MAX_BYTES}; @@ -84,7 +83,7 @@ use libc; use std::any::Any; use std::borrow::ToOwned; use std::cell::Cell; -use std::fmt::{self, Show}; +use std::fmt::{self, Display}; use std::mem::replace; use std::num::ToPrimitive; use std::rc::Rc; @@ -109,7 +108,7 @@ pub trait Runnable { pub enum ScriptMsg { /// Acts on a fragment URL load on the specified pipeline (only dispatched /// to ScriptTask). - TriggerFragment(PipelineId, Url), + TriggerFragment(PipelineId, String), /// Begins a content-initiated load on the specified pipeline (only /// dispatched to ScriptTask). TriggerLoad(PipelineId, LoadData), @@ -610,8 +609,8 @@ impl ScriptTask { match msg { ScriptMsg::TriggerLoad(id, load_data) => self.trigger_load(id, load_data), - ScriptMsg::TriggerFragment(id, url) => - self.trigger_fragment(id, url), + ScriptMsg::TriggerFragment(id, fragment) => + self.trigger_fragment(id, fragment), ScriptMsg::FireTimer(TimerSource::FromWindow(id), timer_id) => self.handle_fire_timer_msg(id, timer_id), ScriptMsg::FireTimer(TimerSource::FromWorker, _) => @@ -633,19 +632,19 @@ impl ScriptTask { fn handle_msg_from_devtools(&self, msg: DevtoolScriptControlMsg) { match msg { - EvaluateJS(id, s, reply) => + DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => devtools::handle_evaluate_js(&*self.page.borrow(), id, s, reply), - GetRootNode(id, reply) => + DevtoolScriptControlMsg::GetRootNode(id, reply) => devtools::handle_get_root_node(&*self.page.borrow(), id, reply), - GetDocumentElement(id, reply) => + DevtoolScriptControlMsg::GetDocumentElement(id, reply) => devtools::handle_get_document_element(&*self.page.borrow(), id, reply), - GetChildren(id, node_id, reply) => + DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => devtools::handle_get_children(&*self.page.borrow(), id, node_id, reply), - GetLayout(id, node_id, reply) => + DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => devtools::handle_get_layout(&*self.page.borrow(), id, node_id, reply), - ModifyAttribute(id, node_id, modifications) => + DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => devtools::handle_modify_attribute(&*self.page.borrow(), id, node_id, modifications), - WantsLiveNotifications(pipeline_id, to_send) => + DevtoolScriptControlMsg::WantsLiveNotifications(pipeline_id, to_send) => devtools::handle_wants_live_notifications(&*self.page.borrow(), pipeline_id, to_send), } } @@ -947,8 +946,9 @@ impl ScriptTask { title: document.r().Title(), url: final_url }; - chan.send(NewGlobal(pipeline_id, self.devtools_sender.clone(), - page_info)).unwrap(); + chan.send(DevtoolsControlMsg::NewGlobal(pipeline_id, + self.devtools_sender.clone(), + page_info)).unwrap(); } } } @@ -1113,9 +1113,9 @@ impl ScriptTask { /// The entry point for content to notify that a fragment url has been requested /// for the given pipeline. - fn trigger_fragment(&self, pipeline_id: PipelineId, url: Url) { + fn trigger_fragment(&self, pipeline_id: PipelineId, fragment: String) { let page = get_page(&*self.page.borrow(), pipeline_id); - match page.find_fragment_node(url.fragment.unwrap()).root() { + match page.find_fragment_node(fragment).root() { Some(node) => { self.scroll_fragment_point(pipeline_id, node.r()); } @@ -1363,13 +1363,13 @@ struct LastModified(pub Tm); impl Header for LastModified { #[inline] - fn header_name(_: Option<LastModified>) -> &'static str { + fn header_name() -> &'static str { "Last-Modified" } // Parses an RFC 2616 compliant date/time string, fn parse_header(raw: &[Vec<u8>]) -> Option<LastModified> { - header_util::from_one_raw_str(raw).and_then(|s: String| { + header_parsing::from_one_raw_str(raw).and_then(|s: String| { let s = s.as_slice(); strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| { strptime(s, "%A, %d-%b-%y %T %Z") @@ -1386,8 +1386,8 @@ impl HeaderFormat for LastModified { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let LastModified(ref tm) = *self; match tm.tm_utcoff { - 0 => tm.rfc822().fmt(f), - _ => tm.to_utc().rfc822().fmt(f) + 0 => <_ as Display>::fmt(&tm.rfc822(), f), + _ => <_ as Display>::fmt(&tm.to_utc().rfc822(), f) } } } @@ -1432,6 +1432,20 @@ impl DocumentProgressHandler { let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(document.r()); event.r().set_trusted(true); let _ = wintarget.dispatch_event_with_target(doctarget, event.r()); + + let window_ref = window.r(); + let browser_context = window_ref.browser_context(); + let browser_context = browser_context.as_ref().unwrap(); + + browser_context.frame_element().map(|frame_element| { + let frame_element = frame_element.root(); + let frame_window = window_from_node(frame_element.r()).root(); + let event = Event::new(GlobalRef::Window(frame_window.r()), "load".to_owned(), + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable).root(); + let target: JSRef<EventTarget> = EventTargetCast::from_ref(frame_element.r()); + event.r().fire(target); + }); } } diff --git a/components/script/textinput.rs b/components/script/textinput.rs index f741ff03b21..8c1a6214098 100644 --- a/components/script/textinput.rs +++ b/components/script/textinput.rs @@ -136,8 +136,8 @@ impl TextInput { let new_lines = { let prefix = self.lines[begin.line].slice_chars(0, begin.index); let suffix = self.lines[end.line].slice_chars(end.index, self.lines[end.line].chars().count()); - let lines_prefix = self.lines.slice(0, begin.line); - let lines_suffix = self.lines.slice(end.line + 1, self.lines.len()); + let lines_prefix = &self.lines[..begin.line]; + let lines_suffix = &self.lines[end.line + 1..]; let mut insert_lines = if self.multiline { insert.as_slice().split('\n').map(|s| s.to_owned()).collect() diff --git a/components/script/timers.rs b/components/script/timers.rs index a5e0c5bf312..8f361ebcb7b 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -24,7 +24,7 @@ use std::collections::HashMap; use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::Select; use std::hash::{Hash, Hasher, Writer}; -use std::io::timer::Timer; +use std::old_io::timer::Timer; use std::time::duration::Duration; #[derive(PartialEq, Eq)] |