Auto merge of #8312 - Ms2ger:DOMString, r=jdm

Make DOMString a newtype around String, rather than a typedef.

<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/servo/servo/8312)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2015-11-04 16:47:41 +05:30
commit abfd1fb1bf
92 changed files with 480 additions and 385 deletions

View file

@ -206,16 +206,16 @@ impl NodeInfoToProtocol for NodeInfo {
NodeActorMsg {
actor: actor_name,
baseURI: self.baseURI,
baseURI: self.baseURI.0,
parent: actors.script_to_actor(self.parent.clone()),
nodeType: self.nodeType,
namespaceURI: self.namespaceURI,
nodeName: self.nodeName,
namespaceURI: self.namespaceURI.0,
nodeName: self.nodeName.0,
numChildren: self.numChildren,
name: self.name,
publicId: self.publicId,
systemId: self.systemId,
name: self.name.0,
publicId: self.publicId.0,
systemId: self.systemId.0,
attrs: self.attrs.into_iter().map(|attr| {
AttrMsg {
@ -233,7 +233,7 @@ impl NodeInfoToProtocol for NodeInfo {
isDocumentElement: self.isDocumentElement,
shortValue: self.shortValue,
shortValue: self.shortValue.0,
incompleteValue: self.incompleteValue,
}
}

View file

@ -225,7 +225,7 @@ fn run_server(sender: Sender<DevtoolsControlMsg>,
let DevtoolsPageInfo { title, url } = page_info;
let tab = TabActor {
name: actors.new_name("tab"),
title: title,
title: title.0,
url: url.serialize(),
console: console.name(),
inspector: inspector.name(),

View file

@ -102,22 +102,22 @@ pub struct AttrInfo {
#[derive(Deserialize, Serialize)]
pub struct NodeInfo {
pub uniqueId: String,
pub baseURI: String,
pub baseURI: DOMString,
pub parent: String,
pub nodeType: u16,
pub namespaceURI: String,
pub nodeName: String,
pub namespaceURI: DOMString,
pub nodeName: DOMString,
pub numChildren: usize,
pub name: String,
pub publicId: String,
pub systemId: String,
pub name: DOMString,
pub publicId: DOMString,
pub systemId: DOMString,
pub attrs: Vec<AttrInfo>,
pub isDocumentElement: bool,
pub shortValue: String,
pub shortValue: DOMString,
pub incompleteValue: bool,
}

View file

@ -982,7 +982,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
}
if let Some(input) = this.downcast::<HTMLInputElement>() {
let data = unsafe { input.get_value_for_layout() };
return TextContent::Text(data);
return TextContent::Text(data.0);
}
if let Some(area) = this.downcast::<HTMLTextAreaElement>() {
let data = unsafe { area.get_value_for_layout() };

View file

@ -183,7 +183,7 @@ impl StorageManager {
let data = self.select_data(storage_type);
sender.send(data.get(&origin)
.and_then(|&(_, ref entry)| entry.get(&name))
.map(|value| value.to_string())).unwrap();
.map(|value| DOMString(value.to_string()))).unwrap();
}
/// Sends Some(old_value) in case there was a previous value with the key name, otherwise sends None

View file

@ -23,6 +23,7 @@ use script_task::get_page;
use std::ffi::CStr;
use std::rc::Rc;
use std::str;
use util::str::DOMString;
use uuid::Uuid;
#[allow(unsafe_code)]
@ -39,7 +40,7 @@ pub fn handle_evaluate_js(global: &GlobalRef, eval: String, reply: IpcSender<Eva
EvaluateJSReply::NumberValue(
FromJSValConvertible::from_jsval(cx, rval.handle(), ()).unwrap())
} else if rval.ptr.is_string() {
EvaluateJSReply::StringValue(jsstring_to_str(cx, rval.ptr.to_string()))
EvaluateJSReply::StringValue(jsstring_to_str(cx, rval.ptr.to_string()).0)
} else if rval.ptr.is_null() {
EvaluateJSReply::NullValue
} else {
@ -159,9 +160,9 @@ pub fn handle_modify_attribute(page: &Rc<Page>,
for modification in modifications {
match modification.newValue {
Some(string) => {
let _ = elem.SetAttribute(modification.attributeName, string);
let _ = elem.SetAttribute(DOMString(modification.attributeName), DOMString(string));
},
None => elem.RemoveAttribute(modification.attributeName),
None => elem.RemoveAttribute(DOMString(modification.attributeName)),
}
}
}

View file

@ -10,6 +10,7 @@ use dom::eventtarget::EventTarget;
use dom::mouseevent::MouseEvent;
use dom::node::window_from_node;
use std::borrow::ToOwned;
use util::str::DOMString;
/// Trait for elements with defined activation behavior
pub trait Activatable {
@ -46,7 +47,7 @@ pub trait Activatable {
// https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event
let win = window_from_node(element);
let target = element.upcast();
let mouse = MouseEvent::new(win.r(), "click".to_owned(),
let mouse = MouseEvent::new(win.r(), DOMString("click".to_owned()),
EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(win.r()), 1,
0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey,
0, None);

View file

@ -46,7 +46,7 @@ impl AttrValue {
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
let tokens = DOMString(str_join(&atoms, "\x20"));
AttrValue::TokenList(tokens, atoms)
}
@ -212,12 +212,12 @@ impl Attr {
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
DOMString((**self.local_name()).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
DOMString((**self.value()).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-value
@ -253,7 +253,7 @@ impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
DOMString((*self.name).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
@ -261,13 +261,13 @@ impl AttrMethods for Attr {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
url => Some(DOMString(url.to_owned())),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
self.prefix().as_ref().map(|p| DOMString((**p).to_owned()))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
@ -326,8 +326,8 @@ impl Attr {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
name: self.Name().0,
value: self.Value().0,
}
}
}

View file

@ -829,7 +829,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None,
default = "None"
else:
assert defaultValue.type.tag() == IDLType.Tags.domstring
default = '"%s".to_owned()' % defaultValue.value
default = 'DOMString("%s".to_owned())' % defaultValue.value
if type.nullable():
default = "Some(%s)" % default

View file

@ -56,7 +56,6 @@ use js::rust::{ToInt64, ToUint64};
use libc;
use num::Float;
use num::traits::{Bounded, Zero};
use std::borrow::ToOwned;
use std::rc::Rc;
use std::{char, ptr, slice};
use util::str::DOMString;
@ -431,6 +430,13 @@ impl ToJSValConvertible for str {
}
}
//http://heycam.github.io/webidl/#es-DOMString
impl ToJSValConvertible for String {
fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
(**self).to_jsval(cx, rval);
}
}
//http://heycam.github.io/webidl/#es-DOMString
impl ToJSValConvertible for DOMString {
fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
@ -452,7 +458,7 @@ pub enum StringificationBehavior {
pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString {
let mut length = 0;
let latin1 = unsafe { JS_StringHasLatin1Chars(s) };
if latin1 {
DOMString(if latin1 {
let chars = unsafe {
JS_GetLatin1StringCharsAndLength(cx, ptr::null(), s, &mut length)
};
@ -497,7 +503,7 @@ pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString {
}
}
s
}
})
}
/// Convert the given `jsid` to a `DOMString`. Fails if the `jsid` is not a
@ -517,7 +523,7 @@ impl FromJSValConvertible for DOMString {
-> Result<DOMString, ()> {
if null_behavior == StringificationBehavior::Empty &&
value.get().is_null() {
Ok("".to_owned())
Ok(DOMString::new())
} else {
let jsstr = unsafe { ToString(cx, value) };
if jsstr.is_null() {
@ -549,7 +555,7 @@ impl FromJSValConvertible for USVString {
}
let latin1 = unsafe { JS_StringHasLatin1Chars(jsstr) };
if latin1 {
return Ok(USVString(jsstring_to_str(cx, jsstr)));
return Ok(USVString(jsstring_to_str(cx, jsstr).0));
}
unsafe {
let mut length = 0;

View file

@ -18,7 +18,6 @@ use libc;
use std::ffi::CString;
use std::{mem, ptr};
use util::mem::HeapSizeOf;
use util::str::DOMString;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Debug, Clone, HeapSizeOf)]
@ -65,9 +64,9 @@ pub enum Error {
TypeMismatch,
/// TypeError JavaScript Error
Type(DOMString),
Type(String),
/// RangeError JavaScript Error
Range(DOMString),
Range(String),
/// A JavaScript exception is already pending.
JSFailed,

View file

@ -83,7 +83,7 @@ use string_cache::{Atom, Namespace};
use style::properties::PropertyDeclarationBlock;
use style::values::specified::Length;
use url::Url;
use util::str::{LengthOrPercentageOrAuto};
use util::str::{DOMString, LengthOrPercentageOrAuto};
/// A trait to allow tracing (only) DOM objects.
@ -285,6 +285,7 @@ no_jsmanaged_fields!(MemProfilerChan);
no_jsmanaged_fields!(PseudoElement);
no_jsmanaged_fields!(Length);
no_jsmanaged_fields!(ElementState);
no_jsmanaged_fields!(DOMString);
impl JSTraceable for Box<ScriptChan + Send> {
#[inline]

View file

@ -452,7 +452,7 @@ pub fn find_enum_string_index(cx: *mut JSContext,
}
let search = jsstring_to_str(cx, jsstr);
Ok(values.iter().position(|value| value == &search))
Ok(values.iter().position(|value| search == *value))
}
/// Returns wether `obj` is a platform object

View file

@ -21,12 +21,12 @@ use util::str::DOMString;
pub struct Blob {
reflector_: Reflector,
bytes: Option<Vec<u8>>,
typeString: DOMString,
typeString: String,
global: GlobalField,
isClosed_: Cell<bool>
}
fn is_ascii_printable(string: &DOMString) -> bool {
fn is_ascii_printable(string: &str) -> bool {
// Step 5.1 in Sec 5.1 of File API spec
// http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob
string.chars().all(|c| { c >= '\x20' && c <= '\x7E' })
@ -60,7 +60,7 @@ impl Blob {
pub fn Constructor_(global: GlobalRef, blobParts: DOMString,
blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible<Root<Blob>> {
//TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView or Blob
let bytes: Option<Vec<u8>> = Some(blobParts.into_bytes());
let bytes: Option<Vec<u8>> = Some(blobParts.0.into_bytes());
let typeString = if is_ascii_printable(&blobPropertyBag.type_) {
&*blobPropertyBag.type_
} else {
@ -85,7 +85,7 @@ impl BlobMethods for Blob {
// https://dev.w3.org/2006/webapi/FileAPI/#dfn-type
fn Type(&self) -> DOMString {
self.typeString.clone()
DOMString(self.typeString.clone())
}
// https://dev.w3.org/2006/webapi/FileAPI/#slice-method-algo
@ -113,13 +113,13 @@ impl BlobMethods for Blob {
}
};
let relativeContentType = match contentType {
None => "".to_owned(),
None => DOMString::new(),
Some(mut str) => {
if is_ascii_printable(&str) {
str.make_ascii_lowercase();
str
} else {
"".to_owned()
DOMString::new()
}
}
};

View file

@ -12,6 +12,7 @@ use dom::bindings::js::Root;
use dom::bindings::num::Finite;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::canvasrenderingcontext2d::parse_color;
use util::str::DOMString;
// https://html.spec.whatwg.org/multipage/#canvasgradient
#[dom_struct]
@ -44,7 +45,7 @@ impl CanvasGradient {
impl CanvasGradientMethods for CanvasGradient {
// https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop
fn AddColorStop(&self, offset: Finite<f64>, color: String) -> ErrorResult {
fn AddColorStop(&self, offset: Finite<f64>, color: DOMString) -> ErrorResult {
if *offset < 0f64 || *offset > 1f64 {
return Err(Error::IndexSize);
}

View file

@ -536,10 +536,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
fn GlobalCompositeOperation(&self) -> DOMString {
let state = self.state.borrow();
match state.global_composition {
DOMString(match state.global_composition {
CompositionOrBlending::Composition(op) => op.to_str().to_owned(),
CompositionOrBlending::Blending(op) => op.to_str().to_owned(),
}
})
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
@ -760,7 +760,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
CanvasFillOrStrokeStyle::Color(ref rgba) => {
let mut result = String::new();
serialize(rgba, &mut result).unwrap();
StringOrCanvasGradientOrCanvasPattern::eString(result)
StringOrCanvasGradientOrCanvasPattern::eString(DOMString(result))
},
CanvasFillOrStrokeStyle::Gradient(ref gradient) => {
StringOrCanvasGradientOrCanvasPattern::eCanvasGradient(Root::from_ref(&*gradient))
@ -800,7 +800,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
CanvasFillOrStrokeStyle::Color(ref rgba) => {
let mut result = String::new();
serialize(rgba, &mut result).unwrap();
StringOrCanvasGradientOrCanvasPattern::eString(result)
StringOrCanvasGradientOrCanvasPattern::eString(DOMString(result))
},
CanvasFillOrStrokeStyle::Gradient(ref gradient) => {
StringOrCanvasGradientOrCanvasPattern::eCanvasGradient(Root::from_ref(&*gradient))
@ -1001,11 +1001,11 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
fn LineCap(&self) -> DOMString {
let state = self.state.borrow();
match state.line_cap {
DOMString(match state.line_cap {
LineCapStyle::Butt => "butt".to_owned(),
LineCapStyle::Round => "round".to_owned(),
LineCapStyle::Square => "square".to_owned(),
}
})
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
@ -1019,11 +1019,11 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
fn LineJoin(&self) -> DOMString {
let state = self.state.borrow();
match state.line_join {
DOMString(match state.line_join {
LineJoinStyle::Round => "round".to_owned(),
LineJoinStyle::Bevel => "bevel".to_owned(),
LineJoinStyle::Miter => "miter".to_owned(),
}
})
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
@ -1098,7 +1098,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
fn ShadowColor(&self) -> DOMString {
let mut result = String::new();
serialize(&self.state.borrow().shadow_color, &mut result).unwrap();
result
DOMString(result)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor

View file

@ -65,7 +65,7 @@ impl CharacterDataMethods for CharacterData {
// Steps 4.
Some(count_bytes) => &data_from_offset[..count_bytes],
};
Ok(substring.to_owned())
Ok(DOMString(substring.to_owned()))
}
// https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata
@ -80,7 +80,7 @@ impl CharacterDataMethods for CharacterData {
// https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count
fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult {
self.ReplaceData(offset, count, "".to_owned())
self.ReplaceData(offset, count, DOMString::new())
}
// https://dom.spec.whatwg.org/#dom-characterdata-replacedata
@ -103,7 +103,7 @@ impl CharacterDataMethods for CharacterData {
new_data.push_str(prefix);
new_data.push_str(&arg);
new_data.push_str(suffix);
new_data
DOMString(new_data)
};
*self.data.borrow_mut() = new_data;
self.content_changed();
@ -150,7 +150,7 @@ impl CharacterData {
}
#[inline]
pub fn append_data(&self, data: &str) {
self.data.borrow_mut().push_str(data);
self.data.borrow_mut().0.push_str(data);
self.content_changed();
}

View file

@ -74,20 +74,17 @@ impl ConsoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/assert
fn Assert(&self, condition: bool, message: Option<DOMString>) {
if !condition {
let message = match message {
Some(ref message) => &**message,
None => "no message",
};
let message = message.unwrap_or_else(|| DOMString("no message".to_owned()));
println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message.to_owned()));
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
}
fn prepare_message(logLevel: LogLevel, message: String) -> ConsoleMessage {
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
//TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
ConsoleMessage {
message: message,
message: message.0,
logLevel: logLevel,
filename: "test".to_owned(),
lineNumber: 1,

View file

@ -76,23 +76,24 @@ use dom::htmlunknownelement::HTMLUnknownElement;
use dom::htmlvideoelement::HTMLVideoElement;
use std::borrow::ToOwned;
use string_cache::{Atom, QualName};
use util::str::DOMString;
pub fn create_element(name: QualName, prefix: Option<Atom>,
document: &Document, creator: ElementCreator)
-> Root<Element> {
let prefix = prefix.map(|p| (*p).to_owned());
let prefix = prefix.map(|p| DOMString((*p).to_owned()));
if name.ns != ns!(HTML) {
return Element::new((*name.local).to_owned(), name.ns, prefix, document);
return Element::new(DOMString((*name.local).to_owned()), name.ns, prefix, document);
}
macro_rules! make(
($ctor:ident) => ({
let obj = $ctor::new((*name.local).to_owned(), prefix, document);
let obj = $ctor::new(DOMString((*name.local).to_owned()), prefix, document);
Root::upcast(obj)
});
($ctor:ident, $($arg:expr),+) => ({
let obj = $ctor::new((*name.local).to_owned(), prefix, document, $($arg),+);
let obj = $ctor::new(DOMString((*name.local).to_owned()), prefix, document, $($arg),+);
Root::upcast(obj)
})
);

View file

@ -20,7 +20,7 @@ impl CSS {
return Err(Error::InvalidCharacter);
}
let mut escaped = DOMString::new();
serialize_identifier(&ident, &mut escaped).unwrap();
serialize_identifier(&ident, &mut escaped.0).unwrap();
Ok(escaped)
}
}

View file

@ -39,10 +39,10 @@ macro_rules! css_properties(
( $([$getter:ident, $setter:ident, $cssprop:expr]),* ) => (
$(
fn $getter(&self) -> DOMString {
self.GetPropertyValue($cssprop.to_owned())
self.GetPropertyValue(DOMString($cssprop.to_owned()))
}
fn $setter(&self, value: DOMString) -> ErrorResult {
self.SetPropertyValue($cssprop.to_owned(), value)
self.SetPropertyValue(DOMString($cssprop.to_owned()), value)
}
)*
);
@ -50,7 +50,7 @@ macro_rules! css_properties(
fn serialize_list(list: &[Ref<PropertyDeclaration>]) -> DOMString {
let str_iter = list.iter().map(|d| d.value());
str_join(str_iter, " ")
DOMString(str_join(str_iter, " "))
}
impl CSSStyleDeclaration {
@ -113,7 +113,7 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
}
});
result.unwrap_or("".to_owned())
DOMString(result.unwrap_or(String::new()))
}
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue
@ -126,7 +126,7 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
if self.readonly {
// Readonly style declarations are used for getComputedStyle.
return self.get_computed_style(&property).unwrap_or("".to_owned());
return self.get_computed_style(&property).unwrap_or(DOMString::new());
}
// Step 2
@ -143,7 +143,7 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
// Step 2.2.2 & 2.2.3
match declaration {
Some(declaration) => list.push(declaration),
None => return "".to_owned(),
None => return DOMString::new(),
}
}
@ -153,8 +153,8 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
// Step 3 & 4
let result = match owner.get_inline_style_declaration(&property) {
Some(declaration) => declaration.value(),
None => "".to_owned(),
Some(declaration) => DOMString(declaration.value()),
None => DOMString::new(),
};
result
}
@ -170,20 +170,20 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
if let Some(longhand_properties) = longhand_properties {
// Step 2.1 & 2.2 & 2.3
if longhand_properties.iter()
.map(|&longhand| self.GetPropertyPriority(longhand.to_owned()))
.map(|&longhand| self.GetPropertyPriority(DOMString(longhand.to_owned())))
.all(|priority| priority == "important") {
return "important".to_owned();
return DOMString("important".to_owned());
}
// Step 3
} else {
if self.owner.get_important_inline_style_declaration(&property).is_some() {
return "important".to_owned();
return DOMString("important".to_owned());
}
}
// Step 4
"".to_owned()
DOMString::new()
}
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty
@ -274,7 +274,7 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyvalue
fn SetPropertyValue(&self, property: DOMString, value: DOMString) -> ErrorResult {
self.SetProperty(property, value, "".to_owned())
self.SetProperty(property, value, DOMString::new())
}
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty
@ -309,12 +309,12 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
fn CssFloat(&self) -> DOMString {
self.GetPropertyValue("float".to_owned())
self.GetPropertyValue(DOMString("float".to_owned()))
}
// https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
fn SetCssFloat(&self, value: DOMString) -> ErrorResult {
self.SetPropertyValue("float".to_owned(), value)
self.SetPropertyValue(DOMString("float".to_owned()), value)
}
// https://dev.w3.org/csswg/cssom/#the-cssstyledeclaration-interface

View file

@ -35,6 +35,7 @@ use std::mem::replace;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use url::Url;
use util::str::DOMString;
use util::task::spawn_named;
use util::task_state;
use util::task_state::{IN_WORKER, SCRIPT};
@ -263,7 +264,7 @@ impl DedicatedWorkerGlobalScope {
{
let _ar = AutoWorkerReset::new(global.r(), worker);
scope.execute_script(source);
scope.execute_script(DOMString(source));
}
let reporter_name = format!("worker-reporter-{}", random::<u64>());

View file

@ -123,7 +123,7 @@ pub struct Document {
implementation: MutNullableHeap<JS<DOMImplementation>>,
location: MutNullableHeap<JS<Location>>,
content_type: DOMString,
last_modified: Option<DOMString>,
last_modified: Option<String>,
encoding_name: DOMRefCell<DOMString>,
is_html_document: bool,
url: Url,
@ -494,7 +494,8 @@ impl Document {
pub fn set_ready_state(&self, state: DocumentReadyState) {
self.ready_state.set(state);
let event = Event::new(GlobalRef::Window(&self.window), "readystatechange".to_owned(),
let event = Event::new(GlobalRef::Window(&self.window),
DOMString("readystatechange".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let target = self.upcast::<EventTarget>();
@ -552,7 +553,7 @@ impl Document {
/// Handles any updates when the document's title has changed.
pub fn title_changed(&self) {
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsertitlechange
self.trigger_mozbrowser_event(MozBrowserEvent::TitleChange(self.Title()));
self.trigger_mozbrowser_event(MozBrowserEvent::TitleChange(self.Title().0));
self.send_title_to_compositor();
}
@ -561,7 +562,7 @@ impl Document {
pub fn send_title_to_compositor(&self) {
let window = self.window();
let compositor = window.compositor();
compositor.send(ScriptToCompositorMsg::SetTitle(window.pipeline(), Some(self.Title()))).unwrap();
compositor.send(ScriptToCompositorMsg::SetTitle(window.pipeline(), Some(self.Title().0))).unwrap();
}
pub fn dirty_all_nodes(&self) {
@ -615,7 +616,7 @@ impl Document {
let y = point.y as i32;
let clickCount = 1;
let event = MouseEvent::new(&self.window,
mouse_event_type_string,
DOMString(mouse_event_type_string),
EventBubbles::Bubbles,
EventCancelable::Cancelable,
Some(&self.window),
@ -653,7 +654,7 @@ impl Document {
let y = point.y.to_i32().unwrap_or(0);
let mouse_event = MouseEvent::new(&self.window,
event_name,
DOMString(event_name),
EventBubbles::Bubbles,
EventCancelable::Cancelable,
Some(&self.window),
@ -802,7 +803,7 @@ impl Document {
|t| t.Target() == target).cloned());
let event = TouchEvent::new(window,
event_name.to_owned(),
DOMString(event_name.to_owned()),
EventBubbles::Bubbles,
EventCancelable::Cancelable,
Some(window),
@ -843,16 +844,17 @@ impl Document {
let is_composing = false;
let is_repeating = state == KeyState::Repeated;
let ev_type = match state {
let ev_type = DOMString(match state {
KeyState::Pressed | KeyState::Repeated => "keydown",
KeyState::Released => "keyup",
}.to_owned();
}.to_owned());
let props = KeyboardEvent::key_properties(key, modifiers);
let keyevent = KeyboardEvent::new(&self.window, ev_type, true, true,
Some(&self.window), 0, Some(key),
props.key_string.to_owned(), props.code.to_owned(),
DOMString(props.key_string.to_owned()),
DOMString(props.code.to_owned()),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
None, props.key_code);
@ -863,9 +865,10 @@ impl Document {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys
if state != KeyState::Released && props.is_printable() && !prevented {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order
let event = KeyboardEvent::new(&self.window, "keypress".to_owned(),
let event = KeyboardEvent::new(&self.window, DOMString("keypress".to_owned()),
true, true, Some(&self.window), 0, Some(key),
props.key_string.to_owned(), props.code.to_owned(),
DOMString(props.key_string.to_owned()),
DOMString(props.code.to_owned()),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
props.char_code, 0);
@ -942,7 +945,7 @@ impl Document {
Some(ref body) => {
body.upcast::<Element>().get_string_attribute(local_name)
},
None => "".to_owned()
None => DOMString::new()
}
}
@ -1176,7 +1179,8 @@ impl Document {
return;
}
self.domcontentloaded_dispatched.set(true);
let event = Event::new(GlobalRef::Window(self.window()), "DOMContentLoaded".to_owned(),
let event = Event::new(GlobalRef::Window(self.window()),
DOMString("DOMContentLoaded".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let doctarget = self.upcast::<EventTarget>();
@ -1251,7 +1255,7 @@ impl Document {
url: Option<Url>,
is_html_document: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<DOMString>,
last_modified: Option<String>,
source: DocumentSource,
doc_loader: DocumentLoader) -> Document {
let url = url.unwrap_or_else(|| Url::parse("about:blank").unwrap());
@ -1270,19 +1274,19 @@ impl Document {
location: Default::default(),
content_type: match content_type {
Some(string) => string,
None => match is_html_document {
None => DOMString(match is_html_document {
// https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
IsHTMLDocument::HTMLDocument => "text/html".to_owned(),
// https://dom.spec.whatwg.org/#concept-document-content-type
IsHTMLDocument::NonHTMLDocument => "application/xml".to_owned()
}
})
},
last_modified: last_modified,
url: url,
// https://dom.spec.whatwg.org/#concept-document-quirks
quirks_mode: Cell::new(NoQuirks),
// https://dom.spec.whatwg.org/#concept-document-encoding
encoding_name: DOMRefCell::new("UTF-8".to_owned()),
encoding_name: DOMRefCell::new(DOMString("UTF-8".to_owned())),
is_html_document: is_html_document == IsHTMLDocument::HTMLDocument,
images: Default::default(),
embeds: Default::default(),
@ -1329,7 +1333,7 @@ impl Document {
url: Option<Url>,
doctype: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<DOMString>,
last_modified: Option<String>,
source: DocumentSource,
doc_loader: DocumentLoader) -> Root<Document> {
let document = reflect_dom_object(box Document::new_inherited(window, url, doctype,
@ -1416,7 +1420,7 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-document-url
fn URL(&self) -> DOMString {
self.url().serialize()
DOMString(self.url().serialize())
}
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
@ -1458,10 +1462,10 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-document-compatmode
fn CompatMode(&self) -> DOMString {
match self.quirks_mode.get() {
DOMString(match self.quirks_mode.get() {
LimitedQuirks | NoQuirks => "CSS1Compat".to_owned(),
Quirks => "BackCompat".to_owned()
}
})
}
// https://dom.spec.whatwg.org/#dom-document-characterset
@ -1543,7 +1547,7 @@ impl DocumentMethods for Document {
let name = Atom::from_slice(&local_name);
// repetition used because string_cache::atom::Atom is non-copyable
let l_name = Atom::from_slice(&local_name);
let value = AttrValue::String("".to_owned());
let value = AttrValue::String(DOMString::new());
Ok(Attr::new(&self.window, name, value, l_name, ns!(""), None, None))
}
@ -1553,7 +1557,7 @@ impl DocumentMethods for Document {
-> Fallible<Root<Attr>> {
let (namespace, prefix, local_name) =
try!(validate_and_extract(namespace, &qualified_name));
let value = AttrValue::String("".to_owned());
let value = AttrValue::String(DOMString::new());
let qualified_name = Atom::from_slice(&qualified_name);
Ok(Attr::new(&self.window, local_name, value, qualified_name,
namespace, prefix, None))
@ -1652,10 +1656,10 @@ impl DocumentMethods for Document {
// https://html.spec.whatwg.org/multipage/#dom-document-lastmodified
fn LastModified(&self) -> DOMString {
match self.last_modified {
DOMString(match self.last_modified {
Some(ref t) => t.clone(),
None => time::now().strftime("%m/%d/%Y %H:%M:%S").unwrap().to_string(),
}
})
}
// https://dom.spec.whatwg.org/#dom-document-createrange
@ -1712,7 +1716,7 @@ impl DocumentMethods for Document {
Some(ref title) => {
// Steps 3-4.
let value = Node::collect_text_contents(title.children());
str_join(split_html_space_chars(&value), " ")
DOMString(str_join(split_html_space_chars(&value), " "))
},
}
}
@ -1979,7 +1983,7 @@ impl DocumentMethods for Document {
let (tx, rx) = ipc::channel().unwrap();
let _ = self.window.resource_task().send(GetCookiesForUrl((*url).clone(), tx, NonHTTP));
let cookies = rx.recv().unwrap();
Ok(cookies.unwrap_or("".to_owned()))
Ok(DOMString(cookies.unwrap_or("".to_owned())))
}
// https://html.spec.whatwg.org/multipage/#dom-document-cookie
@ -1989,7 +1993,7 @@ impl DocumentMethods for Document {
if !is_scheme_host_port_tuple(url) {
return Err(Error::Security);
}
let _ = self.window.resource_task().send(SetCookiesForUrl((*url).clone(), cookie, NonHTTP));
let _ = self.window.resource_task().send(SetCookiesForUrl((*url).clone(), cookie.0, NonHTTP));
Ok(())
}
@ -2139,7 +2143,7 @@ impl DocumentProgressHandler {
fn dispatch_load(&self) {
let document = self.addr.root();
let window = document.window();
let event = Event::new(GlobalRef::Window(window), "load".to_owned(),
let event = Event::new(GlobalRef::Window(window), DOMString("load".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let wintarget = window.upcast::<EventTarget>();
@ -2151,7 +2155,7 @@ impl DocumentProgressHandler {
if let Some(frame_element) = browsing_context.frame_element() {
let frame_window = window_from_node(frame_element);
let event = Event::new(GlobalRef::Window(frame_window.r()), "load".to_owned(),
let event = Event::new(GlobalRef::Window(frame_window.r()), DOMString("load".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(frame_element.upcast());

View file

@ -10,7 +10,6 @@ use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::node::Node;
use std::borrow::ToOwned;
use util::str::DOMString;
// https://dom.spec.whatwg.org/#documenttype
@ -32,8 +31,8 @@ impl DocumentType {
DocumentType {
node: Node::new_inherited(document),
name: name,
public_id: public_id.unwrap_or("".to_owned()),
system_id: system_id.unwrap_or("".to_owned())
public_id: public_id.unwrap_or(DOMString::new()),
system_id: system_id.unwrap_or(DOMString::new())
}
}
#[allow(unrooted_must_root)]

View file

@ -70,7 +70,7 @@ impl DOMExceptionMethods for DOMException {
// https://heycam.github.io/webidl/#idl-DOMException-error-names
fn Name(&self) -> DOMString {
format!("{:?}", self.code)
DOMString(format!("{:?}", self.code))
}
// https://heycam.github.io/webidl/#error-names
@ -102,11 +102,11 @@ impl DOMExceptionMethods for DOMException {
DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed."
};
message.to_owned()
DOMString(message.to_owned())
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-error.prototype.tostring
fn Stringifier(&self) -> String {
format!("{}: {}", self.Name(), self.Message())
fn Stringifier(&self) -> DOMString {
DOMString(format!("{}: {}", self.Name(), self.Message()))
}
}

View file

@ -109,7 +109,7 @@ impl DOMImplementationMethods for DOMImplementation {
{
// Step 3.
let doc_node = doc.upcast::<Node>();
let doc_type = DocumentType::new("html".to_owned(), None, None, doc.r());
let doc_type = DocumentType::new(DOMString("html".to_owned()), None, None, doc.r());
doc_node.AppendChild(doc_type.upcast()).unwrap();
}
@ -117,13 +117,13 @@ impl DOMImplementationMethods for DOMImplementation {
// Step 4.
let doc_node = doc.upcast::<Node>();
let doc_html = Root::upcast::<Node>(
HTMLHtmlElement::new("html".to_owned(), None, doc.r()));
HTMLHtmlElement::new(DOMString("html".to_owned()), None, doc.r()));
doc_node.AppendChild(&doc_html).expect("Appending failed");
{
// Step 5.
let doc_head = Root::upcast::<Node>(
HTMLHeadElement::new("head".to_owned(), None, doc.r()));
HTMLHeadElement::new(DOMString("head".to_owned()), None, doc.r()));
doc_html.AppendChild(&doc_head).unwrap();
// Step 6.
@ -132,7 +132,7 @@ impl DOMImplementationMethods for DOMImplementation {
Some(title_str) => {
// Step 6.1.
let doc_title = Root::upcast::<Node>(
HTMLTitleElement::new("title".to_owned(), None, doc.r()));
HTMLTitleElement::new(DOMString("title".to_owned()), None, doc.r()));
doc_head.AppendChild(&doc_title).unwrap();
// Step 6.2.
@ -143,7 +143,7 @@ impl DOMImplementationMethods for DOMImplementation {
}
// Step 7.
let doc_body = HTMLBodyElement::new("body".to_owned(), None, doc.r());
let doc_body = HTMLBodyElement::new(DOMString("body".to_owned()), None, doc.r());
doc_html.AppendChild(doc_body.upcast()).unwrap();
}

View file

@ -50,7 +50,7 @@ impl DOMParserMethods for DOMParser {
ty: DOMParserBinding::SupportedType)
-> Fallible<Root<Document>> {
let url = self.window.get_url();
let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned();
let content_type = DOMString(DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned());
let doc = self.window.Document();
let doc = doc.r();
let loader = DocumentLoader::new(&*doc.loader());

View file

@ -54,7 +54,7 @@ impl DOMStringMapMethods for DOMStringMap {
},
None => {
*found = false;
String::new()
DOMString::new()
}
}
}

View file

@ -64,7 +64,7 @@ impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(&self, index: u32) -> Option<DOMString> {
self.attribute().and_then(|attr| {
attr.value().as_tokens().get(index as usize).map(|token| (**token).to_owned())
attr.value().as_tokens().get(index as usize).map(|token| DOMString((**token).to_owned()))
})
}
@ -134,7 +134,7 @@ impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
let tokenlist = self.element.get_tokenlist_attribute(&self.local_name);
str_join(&tokenlist, "\x20")
DOMString(str_join(&tokenlist, "\x20"))
}
// check-tidy: no specs after this line

View file

@ -775,7 +775,7 @@ impl Element {
traversal_scope: traversal_scope,
.. Default::default()
}) {
Ok(()) => Ok(String::from_utf8(writer).unwrap()),
Ok(()) => Ok(DOMString(String::from_utf8(writer).unwrap())),
Err(_) => panic!("Cannot serialize element"),
}
}
@ -1014,7 +1014,7 @@ impl Element {
pub fn set_bool_attribute(&self, local_name: &Atom, value: bool) {
if self.has_attribute(local_name) == value { return; }
if value {
self.set_string_attribute(local_name, String::new());
self.set_string_attribute(local_name, DOMString::new());
} else {
self.remove_attribute(&ns!(""), local_name);
}
@ -1023,17 +1023,17 @@ impl Element {
pub fn get_url_attribute(&self, local_name: &Atom) -> DOMString {
assert!(&**local_name == local_name.to_ascii_lowercase());
if !self.has_attribute(local_name) {
return "".to_owned();
return DOMString::new();
}
let url = self.get_string_attribute(local_name);
let doc = document_from_node(self);
let base = doc.url();
// https://html.spec.whatwg.org/multipage/#reflect
// XXXManishearth this doesn't handle `javascript:` urls properly
match UrlParser::new().base_url(&base).parse(&url) {
DOMString(match UrlParser::new().base_url(&base).parse(&url) {
Ok(parsed) => parsed.serialize(),
Err(_) => "".to_owned()
}
})
}
pub fn set_url_attribute(&self, local_name: &Atom, value: DOMString) {
self.set_string_attribute(local_name, value);
@ -1042,7 +1042,7 @@ impl Element {
pub fn get_string_attribute(&self, local_name: &Atom) -> DOMString {
match self.get_attribute(&ns!(""), local_name) {
Some(x) => x.Value(),
None => "".to_owned()
None => DOMString::new()
}
}
pub fn set_string_attribute(&self, local_name: &Atom, value: DOMString) {
@ -1087,7 +1087,7 @@ impl Element {
}
pub fn set_uint_attribute(&self, local_name: &Atom, value: u32) {
assert!(&**local_name == local_name.to_ascii_lowercase());
self.set_attribute(local_name, AttrValue::UInt(value.to_string(), value));
self.set_attribute(local_name, AttrValue::UInt(DOMString(value.to_string()), value));
}
}
@ -1099,7 +1099,7 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-localname
fn LocalName(&self) -> DOMString {
(*self.local_name).to_owned()
DOMString((*self.local_name).to_owned())
}
// https://dom.spec.whatwg.org/#dom-element-prefix
@ -1115,11 +1115,11 @@ impl ElementMethods for Element {
},
None => Cow::Borrowed(&*self.local_name)
};
if self.html_element_in_html_document() {
DOMString(if self.html_element_in_html_document() {
qualified_name.to_ascii_uppercase()
} else {
qualified_name.into_owned()
}
})
}
// https://dom.spec.whatwg.org/#dom-element-id

View file

@ -15,7 +15,6 @@ use dom::bindings::trace::JSTraceable;
use dom::event::{Event, EventBubbles, EventCancelable};
use js::jsapi::{RootedValue, HandleValue, JSContext};
use js::jsval::JSVal;
use std::borrow::ToOwned;
use std::cell::Cell;
use util::str::DOMString;
@ -34,8 +33,8 @@ impl ErrorEvent {
fn new_inherited() -> ErrorEvent {
ErrorEvent {
event: Event::new_inherited(),
message: DOMRefCell::new("".to_owned()),
filename: DOMRefCell::new("".to_owned()),
message: DOMRefCell::new(DOMString::new()),
filename: DOMRefCell::new(DOMString::new()),
lineno: Cell::new(0),
colno: Cell::new(0),
error: MutHeapJSVal::new()
@ -76,12 +75,12 @@ impl ErrorEvent {
init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Root<ErrorEvent>>{
let msg = match init.message.as_ref() {
Some(message) => message.clone(),
None => "".to_owned(),
None => DOMString::new(),
};
let file_name = match init.filename.as_ref() {
None => "".to_owned(),
Some(filename) => filename.clone(),
None => DOMString::new(),
};
let line_num = init.lineno.unwrap_or(0);

View file

@ -169,7 +169,7 @@ impl EventMethods for Event {
// https://dom.spec.whatwg.org/#dom-event-type
fn Type(&self) -> DOMString {
(*self.type_()).to_owned()
DOMString((*self.type_()).to_owned())
}
// https://dom.spec.whatwg.org/#dom-event-target

View file

@ -228,7 +228,7 @@ impl FileReader {
let convert = blob_bytes;
// Step 7
let output = enc.decode(convert, DecoderTrap::Replace).unwrap();
output
DOMString(output)
}
//https://w3c.github.io/FileAPI/#dfn-readAsDataURL
@ -248,7 +248,7 @@ impl FileReader {
format!("data:{};base64,{}", data.blobtype, base64)
};
output
DOMString(output)
}
}
@ -319,11 +319,11 @@ impl FileReaderMethods for FileReader {
impl FileReader {
fn dispatch_progress_event(&self, type_: DOMString, loaded: u64, total: Option<u64>) {
fn dispatch_progress_event(&self, type_: String, loaded: u64, total: Option<u64>) {
let global = self.global.root();
let progressevent = ProgressEvent::new(global.r(),
type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
DOMString(type_), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
total.is_some(), loaded, total.unwrap_or(0));
progressevent.upcast::<Event>().fire(self.upcast());
}

View file

@ -117,7 +117,7 @@ impl FormData {
fn get_file_from_blob(&self, value: &Blob, filename: Option<DOMString>) -> Root<File> {
let global = self.global.root();
let f = value.downcast::<File>();
let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".to_owned()));
let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or(DOMString("blob".to_owned())));
File::new(global.r(), value, name)
}
}

View file

@ -170,7 +170,7 @@ impl Activatable for HTMLAnchorElement {
}
/// https://html.spec.whatwg.org/multipage/#following-hyperlinks-2
fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<DOMString>) {
fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<String>) {
// Step 1: replace.
// Step 2: source browsing context.
// Step 3: target browsing context.
@ -182,7 +182,7 @@ fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<DOMString>) {
// Step 6.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=28925
if let Some(suffix) = hyperlink_suffix {
href.push_str(&suffix);
href.0.push_str(&suffix);
}
// Step 4-5.

View file

@ -181,7 +181,7 @@ impl VirtualMethods for HTMLBodyElement {
};
evtarget.set_event_handler_uncompiled(cx, url, reflector,
&name[2..],
(**attr.value()).to_owned());
DOMString((**attr.value()).to_owned()));
},
_ => {}
}

View file

@ -226,7 +226,7 @@ impl<'a> Activatable for &'a HTMLButtonElement {
if owner.is_none() || self.upcast::<Element>().click_in_progress() {
return;
}
node.query_selector_iter("button[type=submit]".to_owned()).unwrap()
node.query_selector_iter(DOMString("button[type=submit]".to_owned())).unwrap()
.filter_map(Root::downcast::<HTMLButtonElement>)
.find(|r| r.form_owner() == owner)
.map(|s| s.r().synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey));

View file

@ -264,7 +264,7 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
// Step 2.
if self.Width() == 0 || self.Height() == 0 {
return Ok("data:,".to_owned());
return Ok(DOMString("data:,".to_owned()));
}
// Step 3.
@ -285,7 +285,7 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
}
let encoded = encoded.to_base64(STANDARD);
Ok(format!("data:{};base64,{}", mime_type, encoded))
Ok(DOMString(format!("data:{};base64,{}", mime_type, encoded)))
} else {
Err(Error::NotSupported)
}

View file

@ -9,7 +9,6 @@ use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use std::borrow::ToOwned;
use util::str::DOMString;
#[dom_struct]
@ -25,7 +24,7 @@ impl HTMLDialogElement {
HTMLDialogElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
return_value: DOMRefCell::new("".to_owned()),
return_value: DOMRefCell::new(DOMString::new()),
}
}

View file

@ -274,7 +274,7 @@ fn to_snake_case(name: DOMString) -> DOMString {
attr_name.push(ch);
}
}
attr_name
DOMString(attr_name)
}
@ -313,7 +313,7 @@ fn to_camel_case(name: &str) -> Option<DOMString> {
result.push(curr_char);
}
}
Some(result)
Some(DOMString(result))
}
impl HTMLElement {
@ -329,7 +329,7 @@ impl HTMLElement {
pub fn get_custom_attr(&self, local_name: DOMString) -> Option<DOMString> {
let local_name = Atom::from_slice(&to_snake_case(local_name));
self.upcast::<Element>().get_attribute(&ns!(""), &local_name).map(|attr| {
(**attr.value()).to_owned()
DOMString((**attr.value()).to_owned())
})
}
@ -422,7 +422,7 @@ impl VirtualMethods for HTMLElement {
let evtarget = self.upcast::<EventTarget>();
evtarget.set_event_handler_uncompiled(cx, url, reflector,
&name[2..],
(**attr.value()).to_owned());
DOMString((**attr.value()).to_owned()));
},
_ => {}
}

View file

@ -159,7 +159,7 @@ impl HTMLFormElement {
// TODO: Handle browsing contexts
// TODO: Handle validation
let event = Event::new(GlobalRef::Window(win.r()),
"submit".to_owned(),
DOMString("submit".to_owned()),
EventBubbles::Bubbles,
EventCancelable::Cancelable);
event.fire(self.upcast());
@ -171,7 +171,7 @@ impl HTMLFormElement {
// Step 7-8
let mut action = submitter.action();
if action.is_empty() {
action = base.serialize();
action = DOMString(base.serialize());
}
// TODO: Resolve the url relative to the submitter element
// Step 10-15
@ -283,7 +283,7 @@ impl HTMLFormElement {
if prev == '\r' {
buf.push('\n');
}
buf
DOMString(buf)
}
let mut ret = self.get_unclean_dataset(submitter);
@ -311,7 +311,7 @@ impl HTMLFormElement {
let win = window_from_node(self);
let event = Event::new(GlobalRef::Window(win.r()),
"reset".to_owned(),
DOMString("reset".to_owned()),
EventBubbles::Bubbles,
EventCancelable::Cancelable);
event.fire(self.upcast());
@ -491,7 +491,7 @@ pub trait FormControl: DerivedFrom<Element> + Reflectable {
if self.to_element().has_attribute(attr) {
input(self)
} else {
self.form_owner().map_or("".to_owned(), |t| owner(t.r()))
self.form_owner().map_or(DOMString::new(), |t| owner(t.r()))
}
}

View file

@ -144,7 +144,7 @@ impl HTMLIFrameElement {
let mut detail = RootedValue::new(cx, UndefinedValue());
event.detail().to_jsval(cx, detail.handle_mut());
let custom_event = CustomEvent::new(GlobalRef::Window(window.r()),
event.name().to_owned(),
DOMString(event.name().to_owned()),
true,
true,
detail.handle());

View file

@ -79,7 +79,7 @@ impl Runnable for ImageResponseHandlerRunnable {
// Fire image.onload
let window = window_from_node(document.r());
let event = Event::new(GlobalRef::Window(window.r()),
"load".to_owned(),
DOMString("load".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(element.upcast());
@ -146,7 +146,7 @@ impl HTMLImageElement {
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new("img".to_owned(), None, document.r());
let image = HTMLImageElement::new(DOMString("img".to_owned()), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
@ -292,7 +292,7 @@ impl VirtualMethods for HTMLImageElement {
match attr.local_name() {
&atom!(src) => {
self.update_image(mutation.new_value(attr).map(|value| {
((**value).to_owned(), window_from_node(self).get_url())
(DOMString((**value).to_owned()), window_from_node(self).get_url())
}));
},
_ => {},

View file

@ -111,11 +111,11 @@ impl HTMLInputElement {
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document),
input_type: Cell::new(InputType::InputText),
placeholder: DOMRefCell::new("".to_owned()),
placeholder: DOMRefCell::new(DOMString::new()),
checked_changed: Cell::new(false),
value_changed: Cell::new(false),
size: Cell::new(DEFAULT_INPUT_SIZE),
textinput: DOMRefCell::new(TextInput::new(Single, "".to_owned(), chan)),
textinput: DOMRefCell::new(TextInput::new(Single, DOMString::new(), chan)),
activation_state: DOMRefCell::new(InputActivationState::new())
}
}
@ -131,7 +131,7 @@ impl HTMLInputElement {
pub trait LayoutHTMLInputElementHelpers {
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String;
unsafe fn get_value_for_layout(self) -> DOMString;
#[allow(unsafe_code)]
unsafe fn get_size_for_layout(self) -> u32;
#[allow(unsafe_code)]
@ -143,35 +143,37 @@ pub trait LayoutHTMLInputElementHelpers {
}
#[allow(unsafe_code)]
unsafe fn get_raw_textinput_value(input: LayoutJS<HTMLInputElement>) -> String {
unsafe fn get_raw_textinput_value(input: LayoutJS<HTMLInputElement>) -> DOMString {
let textinput = (*input.unsafe_get()).textinput.borrow_for_layout().get_content();
if !textinput.is_empty() {
textinput
} else {
(*input.unsafe_get()).placeholder.borrow_for_layout().to_owned()
(*input.unsafe_get()).placeholder.borrow_for_layout().clone()
}
}
impl LayoutHTMLInputElementHelpers for LayoutJS<HTMLInputElement> {
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String {
unsafe fn get_value_for_layout(self) -> DOMString {
#[allow(unsafe_code)]
unsafe fn get_raw_attr_value(input: LayoutJS<HTMLInputElement>) -> Option<String> {
unsafe fn get_raw_attr_value(input: LayoutJS<HTMLInputElement>, default: &str) -> DOMString {
let elem = input.upcast::<Element>();
(*elem.unsafe_get()).get_attr_val_for_layout(&ns!(""), &atom!("value"))
.map(|s| s.to_owned())
let value = (*elem.unsafe_get())
.get_attr_val_for_layout(&ns!(""), &atom!("value"))
.unwrap_or(default);
DOMString(value.to_owned())
}
match (*self.unsafe_get()).input_type.get() {
InputType::InputCheckbox | InputType::InputRadio => "".to_owned(),
InputType::InputFile | InputType::InputImage => "".to_owned(),
InputType::InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".to_owned()),
InputType::InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.to_owned()),
InputType::InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.to_owned()),
InputType::InputCheckbox | InputType::InputRadio => DOMString::new(),
InputType::InputFile | InputType::InputImage => DOMString::new(),
InputType::InputButton => get_raw_attr_value(self, ""),
InputType::InputSubmit => get_raw_attr_value(self, DEFAULT_SUBMIT_VALUE),
InputType::InputReset => get_raw_attr_value(self, DEFAULT_RESET_VALUE),
InputType::InputPassword => {
let raw = get_raw_textinput_value(self);
// The implementation of get_insertion_point_index_for_layout expects a 1:1 mapping of chars.
raw.chars().map(|_| '●').collect()
DOMString(raw.chars().map(|_| '●').collect())
}
_ => get_raw_textinput_value(self),
}
@ -363,7 +365,7 @@ fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>)
// This function is a workaround for lifetime constraint difficulties.
fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement,
owner: Option<&HTMLFormElement>, group: Option<&Atom>) {
let iter = doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap()
let iter = doc_node.query_selector_iter(DOMString("input[type=radio]".to_owned())).unwrap()
.filter_map(Root::downcast::<HTMLInputElement>)
.filter(|r| in_same_group(r.r(), owner, group) && broadcaster != r.r());
for ref r in iter {
@ -426,9 +428,9 @@ impl HTMLInputElement {
}
let mut value = self.Value();
if ty == "radio" || ty == "checkbox" {
if &*ty == "radio" || &*ty == "checkbox" {
if value.is_empty() {
value = "on".to_owned();
value = DOMString("on".to_owned());
}
}
Some(FormDatum {
@ -560,8 +562,8 @@ impl VirtualMethods for HTMLInputElement {
},
&atom!(value) if !self.value_changed.get() => {
let value = mutation.new_value(attr).map(|value| (**value).to_owned());
self.textinput.borrow_mut().set_content(
value.unwrap_or_else(|| "".to_owned()));
self.textinput.borrow_mut().set_content(DOMString(
value.unwrap_or_else(|| "".to_owned())));
},
&atom!(name) if self.input_type.get() == InputType::InputRadio => {
self.radio_group_updated(
@ -569,9 +571,9 @@ impl VirtualMethods for HTMLInputElement {
},
&atom!(placeholder) => {
let mut placeholder = self.placeholder.borrow_mut();
placeholder.clear();
placeholder.0.clear();
if let AttributeMutation::Set(_) = mutation {
placeholder.extend(
placeholder.0.extend(
attr.value().chars().filter(|&c| c != '\n' && c != '\r'));
}
},
@ -708,7 +710,8 @@ impl Activatable for HTMLInputElement {
let group = self.get_radio_group_name();;
// Safe since we only manipulate the DOM tree after finding an element
let checked_member = doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap()
let checked_member = doc_node.query_selector_iter(DOMString("input[type=radio]".to_owned()))
.unwrap()
.filter_map(Root::downcast::<HTMLInputElement>)
.find(|r| {
in_same_group(r.r(), owner.r(), group.as_ref()) &&
@ -809,13 +812,13 @@ impl Activatable for HTMLInputElement {
let target = self.upcast();
let event = Event::new(GlobalRef::Window(win.r()),
"input".to_owned(),
DOMString("input".to_owned()),
EventBubbles::Bubbles,
EventCancelable::NotCancelable);
event.fire(target);
let event = Event::new(GlobalRef::Window(win.r()),
"change".to_owned(),
DOMString("change".to_owned()),
EventBubbles::Bubbles,
EventCancelable::NotCancelable);
event.fire(target);
@ -840,7 +843,7 @@ impl Activatable for HTMLInputElement {
return;
}
let submit_button;
submit_button = node.query_selector_iter("input[type=submit]".to_owned()).unwrap()
submit_button = node.query_selector_iter(DOMString("input[type=submit]".to_owned())).unwrap()
.filter_map(Root::downcast::<HTMLInputElement>)
.find(|r| r.form_owner() == owner);
match submit_button {
@ -850,7 +853,7 @@ impl Activatable for HTMLInputElement {
}
}
None => {
let inputs = node.query_selector_iter("input".to_owned()).unwrap()
let inputs = node.query_selector_iter(DOMString("input".to_owned())).unwrap()
.filter_map(Root::downcast::<HTMLInputElement>)
.filter(|input| {
input.form_owner() == owner && match &*input.Type() {

View file

@ -261,7 +261,8 @@ impl StylesheetLoadResponder for StylesheetLoadDispatcher {
fn respond(self: Box<StylesheetLoadDispatcher>) {
let elem = self.elem.root();
let window = window_from_node(elem.r());
let event = Event::new(GlobalRef::Window(window.r()), "load".to_owned(),
let event = Event::new(GlobalRef::Window(window.r()),
DOMString("load".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(elem.upcast::<EventTarget>());

View file

@ -80,7 +80,7 @@ fn collect_text(element: &Element, value: &mut DOMString) {
for child in element.upcast::<Node>().children() {
if child.is::<Text>() {
let characterdata = child.downcast::<CharacterData>().unwrap();
value.push_str(&characterdata.Data());
value.0.push_str(&characterdata.Data());
} else if let Some(element_child) = child.downcast() {
collect_text(element_child, value);
}
@ -96,9 +96,9 @@ impl HTMLOptionElementMethods for HTMLOptionElement {
// https://html.spec.whatwg.org/multipage/#dom-option-text
fn Text(&self) -> DOMString {
let mut content = String::new();
let mut content = DOMString::new();
collect_text(self.upcast(), &mut content);
str_join(split_html_space_chars(&content), " ")
DOMString(str_join(split_html_space_chars(&content), " "))
}
// https://html.spec.whatwg.org/multipage/#dom-option-text

View file

@ -120,7 +120,7 @@ static SCRIPT_JS_MIMES: StaticStringVec = &[
#[derive(HeapSizeOf, JSTraceable)]
pub enum ScriptOrigin {
Internal(String, Url),
Internal(DOMString, Url),
External(Result<(Metadata, Vec<u8>), String>),
}
@ -401,7 +401,8 @@ impl HTMLScriptElement {
// TODO: Otherwise, decode the file to Unicode, using character
// encoding as the fallback encoding.
(UTF_8.decode(&*bytes, DecoderTrap::Replace).unwrap(), true,
(DOMString(UTF_8.decode(&*bytes, DecoderTrap::Replace).unwrap()),
true,
metadata.final_url)
},
@ -542,13 +543,13 @@ impl HTMLScriptElement {
}
fn dispatch_event(&self,
type_: DOMString,
type_: String,
bubbles: EventBubbles,
cancelable: EventCancelable) -> bool {
let window = window_from_node(self);
let window = window.r();
let event = Event::new(GlobalRef::Window(window),
type_,
DOMString(type_),
bubbles,
cancelable);
event.fire(self.upcast())

View file

@ -153,11 +153,11 @@ impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
if self.Multiple() {
"select-multiple".to_owned()
DOMString(if self.Multiple() {
"select-multiple"
} else {
"select-one".to_owned()
}
"select-one"
}.to_owned())
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels

View file

@ -73,7 +73,7 @@ impl HTMLTableElementMethods for HTMLTableElement {
let caption = match self.GetCaption() {
Some(caption) => caption,
None => {
let caption = HTMLTableCaptionElement::new("caption".to_owned(),
let caption = HTMLTableCaptionElement::new(DOMString("caption".to_owned()),
None,
document_from_node(self).r());
self.SetCaption(Some(caption.r()));
@ -92,7 +92,7 @@ impl HTMLTableElementMethods for HTMLTableElement {
// https://html.spec.whatwg.org/multipage/#dom-table-createtbody
fn CreateTBody(&self) -> Root<HTMLTableSectionElement> {
let tbody = HTMLTableSectionElement::new("tbody".to_owned(),
let tbody = HTMLTableSectionElement::new(DOMString("tbody".to_owned()),
None,
document_from_node(self).r());
let node = self.upcast::<Node>();

View file

@ -82,7 +82,7 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement {
node.insert_cell_or_row(
index,
|| self.Cells(),
|| HTMLTableDataCellElement::new("td".to_owned(), None, node.owner_doc().r()))
|| HTMLTableDataCellElement::new(DOMString("td".to_owned()), None, node.owner_doc().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-tr-deletecell

View file

@ -67,7 +67,7 @@ impl HTMLTableSectionElementMethods for HTMLTableSectionElement {
node.insert_cell_or_row(
index,
|| self.Rows(),
|| HTMLTableRowElement::new("tr".to_owned(), None, node.owner_doc().r()))
|| HTMLTableRowElement::new(DOMString("tr".to_owned()), None, node.owner_doc().r()))
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow

View file

@ -63,7 +63,7 @@ impl LayoutHTMLTextAreaElementHelpers for LayoutJS<HTMLTextAreaElement> {
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String {
(*self.unsafe_get()).textinput.borrow_for_layout().get_content()
(*self.unsafe_get()).textinput.borrow_for_layout().get_content().0
}
#[allow(unrooted_must_root)]
@ -99,7 +99,7 @@ impl HTMLTextAreaElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document),
textinput: DOMRefCell::new(TextInput::new(Lines::Multiple, "".to_owned(), chan)),
textinput: DOMRefCell::new(TextInput::new(Lines::Multiple, DOMString::new(), chan)),
cols: Cell::new(DEFAULT_COLS),
rows: Cell::new(DEFAULT_ROWS),
value_changed: Cell::new(false),
@ -174,7 +174,7 @@ impl HTMLTextAreaElementMethods for HTMLTextAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-textarea-type
fn Type(&self) -> DOMString {
"textarea".to_owned()
DOMString("textarea".to_owned())
}
// https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue
@ -238,7 +238,7 @@ impl HTMLTextAreaElement {
let window = window_from_node(self);
let window = window.r();
let event = Event::new(GlobalRef::Window(window),
"input".to_owned(),
DOMString("input".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);

View file

@ -45,7 +45,7 @@ impl HTMLTitleElementMethods for HTMLTitleElement {
content.push_str(&text.upcast::<CharacterData>().data());
}
}
content
DOMString(content)
}
// https://html.spec.whatwg.org/multipage/#dom-title-text

View file

@ -17,7 +17,6 @@ use dom::window::Window;
use msg::constellation_msg;
use msg::constellation_msg::{ALT, CONTROL, SHIFT, SUPER};
use msg::constellation_msg::{Key, KeyModifiers};
use std::borrow::ToOwned;
use std::cell::Cell;
use util::str::DOMString;
@ -45,8 +44,8 @@ impl KeyboardEvent {
KeyboardEvent {
uievent: UIEvent::new_inherited(),
key: Cell::new(None),
key_string: DOMRefCell::new("".to_owned()),
code: DOMRefCell::new("".to_owned()),
key_string: DOMRefCell::new(DOMString::new()),
code: DOMRefCell::new(DOMString::new()),
location: Cell::new(0),
ctrl: Cell::new(false),
alt: Cell::new(false),
@ -85,7 +84,7 @@ impl KeyboardEvent {
key_code: u32) -> Root<KeyboardEvent> {
let ev = KeyboardEvent::new_uninitialized(window);
ev.InitKeyboardEvent(type_, canBubble, cancelable, view, key_string, location,
"".to_owned(), repeat, "".to_owned());
DOMString::new(), repeat, DOMString::new());
// FIXME(https://github.com/rust-lang/rust/issues/23338)
{
let ev = ev.r();

View file

@ -135,7 +135,7 @@ impl LocationMethods for Location {
// https://html.spec.whatwg.org/multipage/#dom-location-href
fn Stringifier(&self) -> DOMString {
self.Href().0
DOMString(self.Href().0)
}
// https://html.spec.whatwg.org/multipage/#dom-location-search

View file

@ -84,7 +84,7 @@ macro_rules! make_url_or_base_getter(
let url = element.get_url_attribute(&Atom::from_slice($htmlname));
if url.is_empty() {
let window = window_from_node(self);
window.get_url().serialize()
DOMString(window.get_url().serialize())
} else {
url
}
@ -110,7 +110,7 @@ macro_rules! make_enumerated_getter(
// https://html.spec.whatwg.org/multipage/#attr-fs-method
match &*val {
$($choices)|+ => val,
_ => $default.to_owned()
_ => DOMString($default.to_owned())
}
}
);

View file

@ -28,7 +28,10 @@ pub struct MessageEvent {
impl MessageEvent {
pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent> {
MessageEvent::new_initialized(global, HandleValue::undefined(), "".to_owned(), "".to_owned())
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
pub fn new_initialized(global: GlobalRef,
@ -76,8 +79,8 @@ impl MessageEvent {
scope: GlobalRef,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, "message".to_owned(), false, false, message,
"".to_owned(), "".to_owned());
scope, DOMString("message".to_owned()), false, false, message,
DOMString::new(), DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}

View file

@ -89,7 +89,7 @@ impl NamedNodeMapMethods for NamedNodeMap {
// https://heycam.github.io/webidl/#dfn-supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
self.owner.attrs().iter().map(|attr| {
(**attr.name()).to_owned()
DOMString((**attr.name()).to_owned())
}).collect()
}
}

View file

@ -7,7 +7,7 @@ use util::opts;
use util::str::DOMString;
pub fn Product() -> DOMString {
"Gecko".to_owned()
DOMString("Gecko".to_owned())
}
pub fn TaintEnabled() -> bool {
@ -15,32 +15,32 @@ pub fn TaintEnabled() -> bool {
}
pub fn AppName() -> DOMString {
"Netscape".to_owned() // Like Gecko/Webkit
DOMString("Netscape".to_owned()) // Like Gecko/Webkit
}
pub fn AppCodeName() -> DOMString {
"Mozilla".to_owned()
DOMString("Mozilla".to_owned())
}
#[cfg(target_os = "windows")]
pub fn Platform() -> DOMString {
"Win32".to_owned()
DOMString("Win32".to_owned())
}
#[cfg(any(target_os = "android", target_os = "linux"))]
pub fn Platform() -> DOMString {
"Linux".to_owned()
DOMString("Linux".to_owned())
}
#[cfg(target_os = "macos")]
pub fn Platform() -> DOMString {
"Mac".to_owned()
DOMString("Mac".to_owned())
}
pub fn UserAgent() -> DOMString {
opts::get().user_agent.clone()
DOMString(opts::get().user_agent.clone())
}
pub fn AppVersion() -> DOMString {
"4.0".to_owned()
DOMString("4.0".to_owned())
}

View file

@ -784,14 +784,14 @@ impl Node {
baseURI: self.BaseURI(),
parent: self.GetParentNode().map(|node| node.get_unique_id()).unwrap_or("".to_owned()),
nodeType: self.NodeType(),
namespaceURI: "".to_owned(), //FIXME
namespaceURI: DOMString::new(), //FIXME
nodeName: self.NodeName(),
numChildren: self.ChildNodes().Length() as usize,
//FIXME doctype nodes only
name: "".to_owned(),
publicId: "".to_owned(),
systemId: "".to_owned(),
name: DOMString::new(),
publicId: DOMString::new(),
systemId: DOMString::new(),
attrs: self.downcast().map(Element::summarize).unwrap_or(vec![]),
isDocumentElement:
@ -800,7 +800,7 @@ impl Node {
.map(|elem| elem.upcast::<Node>() == self)
.unwrap_or(false),
shortValue: self.GetNodeValue().unwrap_or("".to_owned()), //FIXME: truncate
shortValue: self.GetNodeValue().unwrap_or(DOMString::new()), //FIXME: truncate
incompleteValue: false, //FIXME: reflect truncation
}
}
@ -1676,7 +1676,7 @@ impl Node {
copy
}
pub fn collect_text_contents<T: Iterator<Item=Root<Node>>>(iterator: T) -> String {
pub fn collect_text_contents<T: Iterator<Item=Root<Node>>>(iterator: T) -> DOMString {
let mut content = String::new();
for node in iterator {
match node.downcast::<Text>() {
@ -1684,13 +1684,13 @@ impl Node {
None => (),
}
}
content
DOMString(content)
}
pub fn namespace_to_string(namespace: Namespace) -> Option<DOMString> {
match namespace {
ns!("") => None,
Namespace(ref ns) => Some((**ns).to_owned())
Namespace(ref ns) => Some(DOMString((**ns).to_owned()))
}
}
@ -1786,16 +1786,16 @@ impl NodeMethods for Node {
NodeTypeId::Element(..) => {
self.downcast::<Element>().unwrap().TagName()
}
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => "#text".to_owned(),
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => DOMString("#text".to_owned()),
NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
self.downcast::<ProcessingInstruction>().unwrap().Target()
}
NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => "#comment".to_owned(),
NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => DOMString("#comment".to_owned()),
NodeTypeId::DocumentType => {
self.downcast::<DocumentType>().unwrap().name().clone()
},
NodeTypeId::DocumentFragment => "#document-fragment".to_owned(),
NodeTypeId::Document => "#document".to_owned()
NodeTypeId::DocumentFragment => DOMString("#document-fragment".to_owned()),
NodeTypeId::Document => DOMString("#document".to_owned())
}
}
@ -1903,7 +1903,7 @@ impl NodeMethods for Node {
// https://dom.spec.whatwg.org/#dom-node-textcontent
fn SetTextContent(&self, value: Option<DOMString>) {
let value = value.unwrap_or(String::new());
let value = value.unwrap_or(DOMString::new());
match self.type_id() {
NodeTypeId::DocumentFragment |
NodeTypeId::Element(..) => {

View file

@ -23,6 +23,7 @@ use dom::node::Node;
use dom::text::Text;
use std::cell::Cell;
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd};
use util::str::DOMString;
#[dom_struct]
pub struct Range {
@ -524,7 +525,7 @@ impl RangeMethods for Range {
// Step 4.4.
try!(end_data.ReplaceData(start_offset,
end_offset - start_offset,
"".to_owned()));
DOMString::new()));
// Step 4.5.
return Ok(fragment);
}
@ -560,7 +561,7 @@ impl RangeMethods for Range {
// Step 15.4.
try!(start_data.ReplaceData(start_offset,
start_node.len() - start_offset,
"".to_owned()));
DOMString::new()));
} else {
// Step 16.1.
let clone = child.CloneNode(false);
@ -595,7 +596,7 @@ impl RangeMethods for Range {
// Step 18.3.
try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 18.4.
try!(end_data.ReplaceData(0, end_offset, "".to_owned()));
try!(end_data.ReplaceData(0, end_offset, DOMString::new()));
} else {
// Step 19.1.
let clone = child.CloneNode(false);

View file

@ -33,6 +33,7 @@ use script_task::{ScriptChan, ScriptTask};
use std::cell::Cell;
use std::default::Default;
use url::Url;
use util::str::DOMString;
#[must_root]
#[derive(JSTraceable, HeapSizeOf)]
@ -47,7 +48,7 @@ impl Sink {
match child {
NodeOrText::AppendNode(n) => Root::from_ref(&*n),
NodeOrText::AppendText(t) => {
let text = Text::new(t.into(), &self.document);
let text = Text::new(DOMString(t.into()), &self.document);
Root::upcast(text)
}
}

View file

@ -186,10 +186,10 @@ impl MainThreadRunnable for StorageEventRunnable {
let storage_event = StorageEvent::new(
global_ref,
"storage".to_owned(),
DOMString("storage".to_owned()),
EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
this.key, this.old_value, this.new_value,
ev_url.to_string(),
DOMString(ev_url.to_string()),
Some(storage)
);

View file

@ -62,7 +62,7 @@ impl TestBindingMethods for TestBinding {
fn SetUnrestrictedDoubleAttribute(&self, _: f64) {}
fn DoubleAttribute(&self) -> Finite<f64> { Finite::wrap(0.) }
fn SetDoubleAttribute(&self, _: Finite<f64>) {}
fn StringAttribute(&self) -> DOMString { "".to_owned() }
fn StringAttribute(&self) -> DOMString { DOMString::new() }
fn SetStringAttribute(&self, _: DOMString) {}
fn UsvstringAttribute(&self) -> USVString { USVString("".to_owned()) }
fn SetUsvstringAttribute(&self, _: USVString) {}
@ -77,7 +77,7 @@ impl TestBindingMethods for TestBinding {
fn SetInterfaceAttribute(&self, _: &Blob) {}
fn UnionAttribute(&self) -> HTMLElementOrLong { eLong(0) }
fn SetUnionAttribute(&self, _: HTMLElementOrLong) {}
fn Union2Attribute(&self) -> EventOrString { eString("".to_owned()) }
fn Union2Attribute(&self) -> EventOrString { eString(DOMString::new()) }
fn SetUnion2Attribute(&self, _: EventOrString) {}
fn Union3Attribute(&self) -> EventOrUSVString { eUSVString(USVString("".to_owned())) }
fn SetUnion3Attribute(&self, _: EventOrUSVString) {}
@ -115,16 +115,16 @@ impl TestBindingMethods for TestBinding {
fn SetDoubleAttributeNullable(&self, _: Option<Finite<f64>>) {}
fn GetByteStringAttributeNullable(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) }
fn SetByteStringAttributeNullable(&self, _: Option<ByteString>) {}
fn GetStringAttributeNullable(&self) -> Option<DOMString> { Some("".to_owned()) }
fn GetStringAttributeNullable(&self) -> Option<DOMString> { Some(DOMString::new()) }
fn SetStringAttributeNullable(&self, _: Option<DOMString>) {}
fn GetUsvstringAttributeNullable(&self) -> Option<USVString> { Some(USVString("".to_owned())) }
fn SetUsvstringAttributeNullable(&self, _: Option<USVString>) {}
fn SetBinaryRenamedAttribute(&self, _: DOMString) {}
fn ForwardedAttribute(&self) -> Root<TestBinding> { Root::from_ref(self) }
fn BinaryRenamedAttribute(&self) -> DOMString { "".to_owned() }
fn BinaryRenamedAttribute(&self) -> DOMString { DOMString::new() }
fn SetBinaryRenamedAttribute2(&self, _: DOMString) {}
fn BinaryRenamedAttribute2(&self) -> DOMString { "".to_owned() }
fn Attr_to_automatically_rename(&self) -> DOMString { "".to_owned() }
fn BinaryRenamedAttribute2(&self) -> DOMString { DOMString::new() }
fn Attr_to_automatically_rename(&self) -> DOMString { DOMString::new() }
fn SetAttr_to_automatically_rename(&self, _: DOMString) {}
fn GetEnumAttributeNullable(&self) -> Option<TestEnum> { Some(_empty) }
fn GetInterfaceAttributeNullable(&self) -> Option<Root<Blob>> {
@ -136,7 +136,7 @@ impl TestBindingMethods for TestBinding {
fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {}
fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> { Some(eLong(0)) }
fn SetUnionAttributeNullable(&self, _: Option<HTMLElementOrLong>) {}
fn GetUnion2AttributeNullable(&self) -> Option<EventOrString> { Some(eString("".to_owned())) }
fn GetUnion2AttributeNullable(&self) -> Option<EventOrString> { Some(eString(DOMString::new())) }
fn SetUnion2AttributeNullable(&self, _: Option<EventOrString>) {}
fn BinaryRenamedMethod(&self) -> () {}
fn ReceiveVoid(&self) -> () {}
@ -153,7 +153,7 @@ impl TestBindingMethods for TestBinding {
fn ReceiveFloat(&self) -> Finite<f32> { Finite::wrap(0.) }
fn ReceiveUnrestrictedDouble(&self) -> f64 { 0. }
fn ReceiveDouble(&self) -> Finite<f64> { Finite::wrap(0.) }
fn ReceiveString(&self) -> DOMString { "".to_owned() }
fn ReceiveString(&self) -> DOMString { DOMString::new() }
fn ReceiveUsvstring(&self) -> USVString { USVString("".to_owned()) }
fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) }
fn ReceiveEnum(&self) -> TestEnum { _empty }
@ -164,7 +164,7 @@ impl TestBindingMethods for TestBinding {
fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() }
fn ReceiveObject(&self, _: *mut JSContext) -> *mut JSObject { panic!() }
fn ReceiveUnion(&self) -> HTMLElementOrLong { eLong(0) }
fn ReceiveUnion2(&self) -> EventOrString { eString("".to_owned()) }
fn ReceiveUnion2(&self) -> EventOrString { eString(DOMString::new()) }
fn ReceiveNullableBoolean(&self) -> Option<bool> { Some(false) }
fn ReceiveNullableByte(&self) -> Option<i8> { Some(0) }
@ -179,7 +179,7 @@ impl TestBindingMethods for TestBinding {
fn ReceiveNullableFloat(&self) -> Option<Finite<f32>> { Some(Finite::wrap(0.)) }
fn ReceiveNullableUnrestrictedDouble(&self) -> Option<f64> { Some(0.) }
fn ReceiveNullableDouble(&self) -> Option<Finite<f64>> { Some(Finite::wrap(0.)) }
fn ReceiveNullableString(&self) -> Option<DOMString> { Some("".to_owned()) }
fn ReceiveNullableString(&self) -> Option<DOMString> { Some(DOMString::new()) }
fn ReceiveNullableUsvstring(&self) -> Option<USVString> { Some(USVString("".to_owned())) }
fn ReceiveNullableByteString(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) }
fn ReceiveNullableEnum(&self) -> Option<TestEnum> { Some(_empty) }
@ -189,7 +189,7 @@ impl TestBindingMethods for TestBinding {
}
fn ReceiveNullableObject(&self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() }
fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> { Some(eLong(0)) }
fn ReceiveNullableUnion2(&self) -> Option<EventOrString> { Some(eString("".to_owned())) }
fn ReceiveNullableUnion2(&self) -> Option<EventOrString> { Some(eString(DOMString::new())) }
fn PassBoolean(&self, _: bool) {}
fn PassByte(&self, _: i8) {}

View file

@ -17,16 +17,16 @@ pub struct TestBindingProxy {
impl TestBindingProxyMethods for TestBindingProxy {
fn Length(&self) -> u32 { 0 }
fn SupportedPropertyNames(&self) -> Vec<DOMString> { vec![] }
fn GetNamedItem(&self, _: DOMString) -> DOMString { "".to_owned() }
fn GetNamedItem(&self, _: DOMString) -> DOMString { DOMString::new() }
fn SetNamedItem(&self, _: DOMString, _: DOMString) -> () {}
fn GetItem(&self, _: u32) -> DOMString { "".to_owned() }
fn GetItem(&self, _: u32) -> DOMString { DOMString::new() }
fn SetItem(&self, _: u32, _: DOMString) -> () {}
fn RemoveItem(&self, _: DOMString) -> () {}
fn Stringifier(&self) -> DOMString { "".to_owned() }
fn IndexedGetter(&self, _: u32, _: &mut bool) -> DOMString { "".to_owned() }
fn Stringifier(&self) -> DOMString { DOMString::new() }
fn IndexedGetter(&self, _: u32, _: &mut bool) -> DOMString { DOMString::new() }
fn NamedDeleter(&self, _: DOMString) -> () {}
fn IndexedSetter(&self, _: u32, _: DOMString) -> () {}
fn NamedSetter(&self, _: DOMString, _: DOMString) -> () {}
fn NamedGetter(&self, _: DOMString, _: &mut bool) -> DOMString { "".to_owned() }
fn NamedGetter(&self, _: DOMString, _: &mut bool) -> DOMString { DOMString::new() }
}

View file

@ -86,7 +86,7 @@ impl TextMethods for Text {
let mut text = DOMString::new();
for ref node in nodes {
let cdata = node.downcast::<CharacterData>().unwrap();
text.push_str(&cdata.data());
text.0.push_str(&cdata.data());
}
text
}

View file

@ -72,7 +72,7 @@ impl TextDecoder {
impl TextDecoderMethods for TextDecoder {
// https://encoding.spec.whatwg.org/#dom-textdecoder-encoding
fn Encoding(&self) -> DOMString {
self.encoding.whatwg_name().unwrap().to_owned()
DOMString(self.encoding.whatwg_name().unwrap().to_owned())
}
// https://encoding.spec.whatwg.org/#dom-textdecoder-fatal

View file

@ -66,7 +66,7 @@ impl TextEncoder {
impl TextEncoderMethods for TextEncoder {
// https://encoding.spec.whatwg.org/#dom-textencoder-encoding
fn Encoding(&self) -> DOMString {
self.encoder.name().to_owned()
DOMString(self.encoder.name().to_owned())
}
#[allow(unsafe_code)]

View file

@ -188,7 +188,7 @@ impl URLMethods for URL {
// https://url.spec.whatwg.org/#dom-url-href
fn Stringifier(&self) -> DOMString {
self.Href().0
DOMString(self.Href().0)
}
// https://url.spec.whatwg.org/#dom-url-username

View file

@ -119,7 +119,7 @@ impl URLSearchParamsMethods for URLSearchParams {
// https://url.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
self.serialize(None)
DOMString(self.serialize(None))
}
}

View file

@ -13,6 +13,7 @@ use std::fs::read_dir;
use std::path::PathBuf;
use util::opts;
use util::resource_files::resources_dir_path;
use util::str::DOMString;
pub fn load_script(head: &HTMLHeadElement) {
@ -41,9 +42,9 @@ pub fn load_script(head: &HTMLHeadElement) {
Ok(ref s) if s.ends_with(".js") => "file://".to_owned() + &s[..],
_ => continue
};
let new_script = doc.CreateElement("script".to_owned()).unwrap();
let new_script = doc.CreateElement(DOMString("script".to_owned())).unwrap();
let new_script = new_script.r();
new_script.set_string_attribute(&atom!("src"), name);
new_script.set_string_attribute(&atom!("src"), DOMString(name));
node.InsertBefore(new_script.upcast(), first_child.r()).unwrap();
}
}

View file

@ -16,11 +16,11 @@ pub struct WebGLActiveInfo {
size: i32,
// NOTE: `ty` stands for `type`, which is a reserved keyword
ty: u32,
name: String,
name: DOMString,
}
impl WebGLActiveInfo {
fn new_inherited(size: i32, ty: u32, name: String) -> WebGLActiveInfo {
fn new_inherited(size: i32, ty: u32, name: DOMString) -> WebGLActiveInfo {
WebGLActiveInfo {
reflector_: Reflector::new(),
size: size,
@ -29,7 +29,7 @@ impl WebGLActiveInfo {
}
}
pub fn new(global: GlobalRef, size: i32, ty: u32, name: String) -> Root<WebGLActiveInfo> {
pub fn new(global: GlobalRef, size: i32, ty: u32, name: DOMString) -> Root<WebGLActiveInfo> {
reflect_dom_object(box WebGLActiveInfo::new_inherited(size, ty, name), global, WebGLActiveInfoBinding::Wrap)
}
}

View file

@ -58,7 +58,7 @@ impl WebGLContextEvent {
init: &WebGLContextEventInit) -> Fallible<Root<WebGLContextEvent>> {
let status_message = match init.statusMessage.as_ref() {
Some(message) => message.clone(),
None => "".to_owned(),
None => DOMString::new(),
};
let bubbles = if init.parent.bubbles {

View file

@ -14,6 +14,7 @@ use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN;
use dom::webglshader::WebGLShader;
use ipc_channel::ipc::{self, IpcSender};
use std::cell::Cell;
use util::str::DOMString;
#[dom_struct]
pub struct WebGLProgram {
@ -94,7 +95,7 @@ impl WebGLProgram {
}
/// glGetAttribLocation
pub fn get_attrib_location(&self, name: String) -> WebGLResult<Option<i32>> {
pub fn get_attrib_location(&self, name: DOMString) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
@ -105,12 +106,12 @@ impl WebGLProgram {
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name, sender))).unwrap();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name.0, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetUniformLocation
pub fn get_uniform_location(&self, name: String) -> WebGLResult<Option<i32>> {
pub fn get_uniform_location(&self, name: DOMString) -> WebGLResult<Option<i32>> {
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
@ -121,7 +122,7 @@ impl WebGLProgram {
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetUniformLocation(self.id, name, sender))).unwrap();
self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetUniformLocation(self.id, name.0, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
}

View file

@ -118,10 +118,11 @@ impl WebGLRenderingContext {
WebGLRenderingContextBinding::Wrap)),
Err(msg) => {
error!("Couldn't create WebGLRenderingContext: {}", msg);
let event = WebGLContextEvent::new(global, "webglcontextcreationerror".to_owned(),
let event = WebGLContextEvent::new(global,
DOMString("webglcontextcreationerror".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable,
msg);
DOMString(msg));
event.upcast::<Event>().fire(canvas.upcast());
None
}
@ -622,7 +623,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
fn GetShaderInfoLog(&self, shader: Option<&WebGLShader>) -> Option<DOMString> {
if let Some(shader) = shader {
shader.info_log()
shader.info_log().map(DOMString)
} else {
None
}

View file

@ -15,6 +15,7 @@ use dom::webglobject::WebGLObject;
use ipc_channel::ipc::{self, IpcSender};
use std::cell::Cell;
use std::sync::{ONCE_INIT, Once};
use util::str::DOMString;
#[derive(Clone, Copy, PartialEq, Debug, JSTraceable, HeapSizeOf)]
pub enum ShaderCompilationStatus {
@ -28,7 +29,7 @@ pub struct WebGLShader {
webgl_object: WebGLObject,
id: u32,
gl_type: u32,
source: DOMRefCell<Option<String>>,
source: DOMRefCell<Option<DOMString>>,
info_log: DOMRefCell<Option<String>>,
is_deleted: Cell<bool>,
compilation_status: Cell<ShaderCompilationStatus>,
@ -144,12 +145,12 @@ impl WebGLShader {
}
/// Get the shader source
pub fn source(&self) -> Option<String> {
pub fn source(&self) -> Option<DOMString> {
self.source.borrow().clone()
}
/// glShaderSource
pub fn set_source(&self, source: String) {
pub fn set_source(&self, source: DOMString) {
*self.source.borrow_mut() = Some(source);
}
}

View file

@ -139,7 +139,7 @@ pub struct WebSocket {
full: Cell<bool>, //Flag to tell if websocket queue is full
clean_close: Cell<bool>, //Flag to tell if the websocket closed cleanly (not due to full or fail)
code: Cell<u16>, //Closing code
reason: DOMRefCell<DOMString>, //Closing reason
reason: DOMRefCell<String>, //Closing reason
binary_type: Cell<BinaryType>,
}
@ -309,7 +309,7 @@ impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
self.url.serialize()
DOMString(self.url.serialize())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
@ -452,7 +452,7 @@ impl Runnable for ConnectionEstablishedTask {
// Step 6.
let global = ws.global.root();
let event = Event::new(global.r(), "open".to_owned(),
let event = Event::new(global.r(), DOMString("open".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(ws.upcast());
@ -494,23 +494,22 @@ impl Runnable for CloseTask {
//A Bad close
ws.clean_close.set(false);
let event = Event::new(global.r(),
"error".to_owned(),
DOMString("error".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable);
event.fire(ws.upcast());
}
let rsn = ws.reason.borrow();
let rsn_clone = rsn.clone();
let reason = ws.reason.borrow().clone();
/*In addition, we also have to fire a close even if error event fired
https://html.spec.whatwg.org/multipage/#closeWebSocket
*/
let close_event = CloseEvent::new(global.r(),
"close".to_owned(),
DOMString("close".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
ws.clean_close.get(),
ws.code.get(),
rsn_clone);
DOMString(reason));
close_event.upcast::<Event>().fire(ws.upcast());
}
}

View file

@ -300,7 +300,7 @@ pub fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
// "and then must apply the base64 algorithm to that sequence of
// octets, and return the result. [RFC4648]"
Ok(octets.to_base64(STANDARD))
Ok(DOMString(octets.to_base64(STANDARD)))
}
}
@ -347,7 +347,7 @@ pub fn base64_atob(input: DOMString) -> Fallible<DOMString> {
}
match input.from_base64() {
Ok(data) => Ok(data.iter().map(|&b| b as char).collect::<String>()),
Ok(data) => Ok(DOMString(data.iter().map(|&b| b as char).collect::<String>())),
Err(..) => Err(Error::InvalidCharacter)
}
}
@ -986,12 +986,12 @@ impl Window {
pub fn resolved_style_query(&self,
element: TrustedNodeAddress,
pseudo: Option<PseudoElement>,
property: &Atom) -> Option<String> {
property: &Atom) -> Option<DOMString> {
self.reflow(ReflowGoal::ForScriptQuery,
ReflowQueryType::ResolvedStyleQuery(element, pseudo, property.clone()),
ReflowReason::Query);
let ResolvedStyleResponse(resolved) = self.layout_rpc.resolved_style();
resolved
resolved.map(DOMString)
}
pub fn offset_parent_query(&self, node: TrustedNodeAddress) -> (Option<Root<Element>>, Rect<Au>) {

View file

@ -85,7 +85,7 @@ impl Worker {
let pipeline_id = global.pipeline();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
title: DOMString(title),
url: worker_url.clone(),
};
chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)),
@ -129,7 +129,7 @@ impl Worker {
let worker = address.root();
let global = worker.r().global.root();
let event = Event::new(global.r(),
"error".to_owned(),
DOMString("error".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.fire(worker.upcast());
@ -140,7 +140,7 @@ impl Worker {
let worker = address.root();
let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
let errorevent = ErrorEvent::new(global.r(), DOMString("error".to_owned()),
EventBubbles::Bubbles, EventCancelable::Cancelable,
message, filename, lineno, colno, error.handle());
errorevent.upcast::<Event>().fire(worker.upcast());

View file

@ -289,7 +289,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
impl WorkerGlobalScope {
pub fn execute_script(&self, source: DOMString) {
match self.runtime.evaluate_script(
self.reflector().get_jsobject(), source, self.worker_url.serialize(), 1) {
self.reflector().get_jsobject(), source.0, self.worker_url.serialize(), 1) {
Ok(_) => (),
Err(_) => {
// TODO: An error needs to be dispatched to the parent.

View file

@ -78,6 +78,6 @@ impl WorkerLocationMethods for WorkerLocation {
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Stringifier(&self) -> DOMString {
self.Href().0
DOMString(self.Href().0)
}
}

View file

@ -151,7 +151,7 @@ impl XMLHttpRequest {
timeout: Cell::new(0u32),
with_credentials: Cell::new(false),
upload: JS::from_rooted(&XMLHttpRequestUpload::new(global)),
response_url: "".to_owned(),
response_url: DOMString::new(),
status: Cell::new(0),
status_text: DOMRefCell::new(ByteString::new(vec!())),
response: DOMRefCell::new(ByteString::new(vec!())),
@ -707,10 +707,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
fn GetResponseText(&self) -> Fallible<DOMString> {
match self.response_type.get() {
_empty | Text => {
match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => Ok(self.text_response()),
_ => Ok("".to_owned())
}
Ok(DOMString(match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => self.text_response(),
_ => "".to_owned()
}))
},
_ => Err(Error::InvalidState)
}
@ -731,7 +731,7 @@ impl XMLHttpRequest {
self.ready_state.set(rs);
let global = self.global.root();
let event = Event::new(global.r(),
"readystatechange".to_owned(),
DOMString("readystatechange".to_owned()),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable);
event.fire(self.upcast());
@ -910,10 +910,12 @@ impl XMLHttpRequest {
self.request_headers.borrow_mut().set_raw(name, vec![value.into_bytes()]);
}
fn dispatch_progress_event(&self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>) {
fn dispatch_progress_event(&self, upload: bool, type_: String, loaded: u64, total: Option<u64>) {
let global = self.global.root();
let progressevent = ProgressEvent::new(global.r(),
type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
DOMString(type_),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
total.is_some(), loaded,
total.unwrap_or(0));
let target = if upload {
@ -924,14 +926,14 @@ impl XMLHttpRequest {
progressevent.upcast::<Event>().fire(target);
}
fn dispatch_upload_progress_event(&self, type_: DOMString, partial_load: Option<u64>) {
fn dispatch_upload_progress_event(&self, type_: String, partial_load: Option<u64>) {
// If partial_load is None, loading has completed and we can just use the value from the request body
let total = self.request_body_len.get() as u64;
self.dispatch_progress_event(true, type_, partial_load.unwrap_or(total), Some(total));
}
fn dispatch_response_progress_event(&self, type_: DOMString) {
fn dispatch_response_progress_event(&self, type_: String) {
let len = self.response.borrow().len() as u64;
let total = self.response_headers.borrow().get::<ContentLength>().map(|x| { **x as u64 });
self.dispatch_progress_event(false, type_, len, total);
@ -985,7 +987,7 @@ impl XMLHttpRequest {
}
}
fn text_response(&self) -> DOMString {
fn text_response(&self) -> String {
let mut encoding = UTF_8 as EncodingRef;
match self.response_headers.borrow().get() {
Some(&ContentType(mime::Mime(_, _, ref params))) => {

View file

@ -71,14 +71,14 @@ impl<'a> TreeSink for servohtmlparser::Sink {
ElementCreator::ParserCreated);
for attr in attrs {
elem.set_attribute_from_parser(attr.name, attr.value.into(), None);
elem.set_attribute_from_parser(attr.name, DOMString(attr.value.into()), None);
}
JS::from_ref(elem.upcast())
}
fn create_comment(&mut self, text: StrTendril) -> JS<Node> {
let comment = Comment::new(text.into(), &*self.document);
let comment = Comment::new(DOMString(text.into()), &*self.document);
JS::from_ref(comment.upcast())
}
@ -115,7 +115,8 @@ impl<'a> TreeSink for servohtmlparser::Sink {
system_id: StrTendril) {
let doc = &*self.document;
let doctype = DocumentType::new(
name.into(), Some(public_id.into()), Some(system_id.into()), doc);
DOMString(name.into()), Some(DOMString(public_id.into())),
Some(DOMString(system_id.into())), doc);
doc.upcast::<Node>().AppendChild(doctype.upcast()).expect("Appending failed");
}
@ -123,7 +124,7 @@ impl<'a> TreeSink for servohtmlparser::Sink {
let elem = target.downcast::<Element>()
.expect("tried to set attrs on non-Element in HTML parsing");
for attr in attrs {
elem.set_attribute_from_parser(attr.name, attr.value.into(), None);
elem.set_attribute_from_parser(attr.name, DOMString(attr.value.into()), None);
}
}
@ -237,7 +238,7 @@ pub enum ParseContext<'a> {
}
pub fn parse_html(document: &Document,
input: String,
input: DOMString,
url: Url,
context: ParseContext) {
let parser = match context {
@ -246,7 +247,7 @@ pub fn parse_html(document: &Document,
ParseContext::Fragment(fc) =>
ServoHTMLParser::new_for_fragment(Some(url), document, fc),
};
parser.parse_chunk(input.into());
parser.parse_chunk(input.0.into());
}
// https://html.spec.whatwg.org/multipage/#parsing-html-fragments

View file

@ -1603,13 +1603,13 @@ impl ScriptTask {
incomplete.parent_info,
incomplete.window_size);
let last_modified: Option<DOMString> = metadata.headers.as_ref().and_then(|headers| {
let last_modified = metadata.headers.as_ref().and_then(|headers| {
headers.get().map(|&LastModified(HttpDate(ref tm))| dom_last_modified(tm))
});
let content_type = match metadata.content_type {
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) => {
Some("text/plain".to_owned())
Some(DOMString("text/plain".to_owned()))
}
_ => None
};
@ -1640,11 +1640,11 @@ impl ScriptTask {
let evalstr = incomplete.url.non_relative_scheme_data().unwrap();
let mut jsval = RootedValue::new(self.get_cx(), UndefinedValue());
window.evaluate_js_on_global_with_result(evalstr, jsval.handle_mut());
let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval.handle(),
StringificationBehavior::Empty);
strval.unwrap_or("".to_owned())
let strval = DOMString::from_jsval(self.get_cx(), jsval.handle(),
StringificationBehavior::Empty);
strval.unwrap_or(DOMString::new())
} else {
"".to_owned()
DOMString::new()
};
parse_html(document.r(), parse_input, final_url,
@ -1877,7 +1877,7 @@ impl ScriptTask {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(window.r(),
"resize".to_owned(), EventBubbles::DoesNotBubble,
DOMString("resize".to_owned()), EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable, Some(window.r()),
0i32);
uievent.upcast::<Event>().fire(window.upcast());

View file

@ -124,7 +124,7 @@ impl<T: ClipboardProvider> TextInput<T> {
if self.selection_begin.is_none() {
self.adjust_horizontal_by_one(dir, Selection::Selected);
}
self.replace_selection("".to_owned());
self.replace_selection(DOMString::new());
}
/// Insert a character at the current editing point
@ -137,7 +137,7 @@ impl<T: ClipboardProvider> TextInput<T> {
if self.selection_begin.is_none() {
self.selection_begin = Some(self.edit_point);
}
self.replace_selection(s.into());
self.replace_selection(DOMString(s.into()));
}
pub fn get_sorted_selection(&self) -> Option<(TextPoint, TextPoint)> {
@ -170,7 +170,7 @@ impl<T: ClipboardProvider> TextInput<T> {
})
}
pub fn replace_selection(&mut self, insert: String) {
pub fn replace_selection(&mut self, insert: DOMString) {
if let Some((begin, end)) = self.get_sorted_selection() {
self.clear_selection();
@ -181,20 +181,20 @@ impl<T: ClipboardProvider> TextInput<T> {
let lines_suffix = &self.lines[end.line + 1..];
let mut insert_lines = if self.multiline {
insert.split('\n').map(|s| s.to_owned()).collect()
insert.split('\n').map(|s| DOMString(s.to_owned())).collect()
} else {
vec!(insert)
};
let mut new_line = prefix.to_owned();
new_line.push_str(&insert_lines[0]);
insert_lines[0] = new_line;
insert_lines[0] = DOMString(new_line);
let last_insert_lines_index = insert_lines.len() - 1;
self.edit_point.index = insert_lines[last_insert_lines_index].len();
self.edit_point.line = begin.line + last_insert_lines_index;
insert_lines[last_insert_lines_index].push_str(suffix);
insert_lines[last_insert_lines_index].0.push_str(suffix);
let mut new_lines = vec!();
new_lines.push_all(lines_prefix);
@ -441,14 +441,14 @@ impl<T: ClipboardProvider> TextInput<T> {
content.push('\n');
}
}
content
DOMString(content)
}
/// Set the current contents of the text input. If this is control supports multiple lines,
/// any \n encountered will be stripped and force a new logical line.
pub fn set_content(&mut self, content: DOMString) {
self.lines = if self.multiline {
content.split('\n').map(|s| s.to_owned()).collect()
content.split('\n').map(|s| DOMString(s.to_owned())).collect()
} else {
vec!(content)
};

View file

@ -24,6 +24,7 @@ use page::Page;
use script_task::get_page;
use std::rc::Rc;
use url::Url;
use util::str::DOMString;
fn find_node_by_unique_id(page: &Rc<Page>, pipeline: PipelineId, node_id: String) -> Option<Root<Node>> {
let page = get_page(&*page, pipeline);
@ -48,9 +49,8 @@ pub fn jsval_to_webdriver(cx: *mut JSContext, val: HandleValue) -> WebDriverJSRe
Ok(WebDriverJSValue::Number(FromJSValConvertible::from_jsval(cx, val, ()).unwrap()))
} else if val.get().is_string() {
//FIXME: use jsstring_to_str when jsval grows to_jsstring
Ok(
WebDriverJSValue::String(
FromJSValConvertible::from_jsval(cx, val, StringificationBehavior::Default).unwrap()))
let string: DOMString = FromJSValConvertible::from_jsval(cx, val, StringificationBehavior::Default).unwrap();
Ok(WebDriverJSValue::String(string.0))
} else if val.get().is_null() {
Ok(WebDriverJSValue::Null)
} else {
@ -115,7 +115,7 @@ pub fn handle_get_frame_id(page: &Rc<Page>,
pub fn handle_find_element_css(page: &Rc<Page>, _pipeline: PipelineId, selector: String,
reply: IpcSender<Result<Option<String>, ()>>) {
reply.send(match page.document().QuerySelector(selector) {
reply.send(match page.document().QuerySelector(DOMString(selector)) {
Ok(node) => {
Ok(node.map(|x| x.upcast::<Node>().get_unique_id()))
}
@ -127,7 +127,7 @@ pub fn handle_find_elements_css(page: &Rc<Page>,
_pipeline: PipelineId,
selector: String,
reply: IpcSender<Result<Vec<String>, ()>>) {
reply.send(match page.document().QuerySelectorAll(selector) {
reply.send(match page.document().QuerySelectorAll(DOMString(selector)) {
Ok(ref nodes) => {
let mut result = Vec::with_capacity(nodes.Length() as usize);
for i in 0..nodes.Length() {
@ -151,7 +151,7 @@ pub fn handle_get_active_element(page: &Rc<Page>,
}
pub fn handle_get_title(page: &Rc<Page>, _pipeline: PipelineId, reply: IpcSender<String>) {
reply.send(page.document().Title()).unwrap();
reply.send(page.document().Title().0).unwrap();
}
pub fn handle_get_text(page: &Rc<Page>,
@ -160,7 +160,7 @@ pub fn handle_get_text(page: &Rc<Page>,
reply: IpcSender<Result<String, ()>>) {
reply.send(match find_node_by_unique_id(&*page, pipeline, node_id) {
Some(ref node) => {
Ok(node.GetTextContent().unwrap_or("".to_owned()))
Ok(node.GetTextContent().map(|x| x.0).unwrap_or("".to_owned()))
},
None => Err(())
}).unwrap();
@ -172,7 +172,7 @@ pub fn handle_get_name(page: &Rc<Page>,
reply: IpcSender<Result<String, ()>>) {
reply.send(match find_node_by_unique_id(&*page, pipeline, node_id) {
Some(node) => {
Ok(node.downcast::<Element>().unwrap().TagName())
Ok(node.downcast::<Element>().unwrap().TagName().0)
},
None => Err(())
}).unwrap();

View file

@ -1546,6 +1546,7 @@ version = "0.0.1"
dependencies = [
"msg 0.0.1",
"script 0.0.1",
"util 0.0.1",
]
[[package]]

View file

@ -35,7 +35,7 @@ use std::mem::{size_of, transmute};
use std::rc::Rc;
use std::result::Result;
use std::sync::Arc;
use str::LengthOrPercentageOrAuto;
use str::{DOMString, LengthOrPercentageOrAuto};
use string_cache::atom::Atom;
use string_cache::namespace::Namespace;
use url;
@ -101,6 +101,12 @@ impl HeapSizeOf for String {
}
}
impl HeapSizeOf for DOMString {
fn heap_size_of_children(&self) -> usize {
self.0.heap_size_of_children()
}
}
impl<T: HeapSizeOf> HeapSizeOf for Option<T> {
fn heap_size_of_children(&self) -> usize {
match *self {

View file

@ -8,12 +8,69 @@ use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::convert::AsRef;
use std::ffi::CStr;
use std::fmt;
use std::iter::{Filter, Peekable};
use std::ops::Deref;
use std::ops::{Deref, DerefMut};
use std::str::{CharIndices, FromStr, Split, from_utf8};
pub type DOMString = String;
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Deserialize, Serialize, Hash, Debug)]
pub struct DOMString(pub String);
impl DOMString {
pub fn new() -> DOMString {
DOMString(String::new())
}
}
impl Deref for DOMString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&self.0
}
}
impl DerefMut for DOMString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
&mut self.0
}
}
impl AsRef<str> for DOMString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for DOMString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl PartialEq<str> for DOMString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
impl<'a> PartialEq<&'a str> for DOMString {
fn eq(&self, other: &&'a str) -> bool {
&**self == *other
}
}
impl Into<Vec<u8>> for DOMString {
fn into(self) -> Vec<u8> {
self.0.into()
}
}
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];

View file

@ -13,3 +13,6 @@ path = "../../../components/msg"
[dependencies.script]
path = "../../../components/script"
[dependencies.util]
path = "../../../components/util"

View file

@ -4,6 +4,7 @@
extern crate script;
extern crate msg;
extern crate util;
#[cfg(all(test, target_pointer_width = "64"))] mod size_of;
#[cfg(test)] mod textinput;

View file

@ -15,10 +15,15 @@ use msg::constellation_msg::{Key, KeyModifiers};
use script::clipboard_provider::DummyClipboardContext;
use script::textinput::{TextInput, Selection, Lines, Direction};
use std::borrow::ToOwned;
use util::str::DOMString;
fn text_input(lines: Lines, s: &str) -> TextInput<DummyClipboardContext> {
TextInput::new(lines, DOMString(s.to_owned()), DummyClipboardContext::new(""))
}
#[test]
fn test_textinput_delete_char() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "abcdefg");
textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.delete_char(Direction::Backward);
assert_eq!(textinput.get_content(), "acdefg");
@ -30,7 +35,7 @@ fn test_textinput_delete_char() {
textinput.delete_char(Direction::Forward);
assert_eq!(textinput.get_content(), "afg");
let mut textinput = TextInput::new(Lines::Single, "a🌠b".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "a🌠b");
// Same as "Right" key
textinput.adjust_horizontal_by_one(Direction::Forward, Selection::NotSelected);
textinput.delete_char(Direction::Forward);
@ -40,7 +45,7 @@ fn test_textinput_delete_char() {
#[test]
fn test_textinput_insert_char() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "abcdefg");
textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.insert_char('a');
assert_eq!(textinput.get_content(), "abacdefg");
@ -49,7 +54,7 @@ fn test_textinput_insert_char() {
textinput.insert_char('b');
assert_eq!(textinput.get_content(), "ababefg");
let mut textinput = TextInput::new(Lines::Single, "a🌠c".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "a🌠c");
// Same as "Right" key
textinput.adjust_horizontal_by_one(Direction::Forward, Selection::NotSelected);
textinput.adjust_horizontal_by_one(Direction::Forward, Selection::NotSelected);
@ -60,7 +65,7 @@ fn test_textinput_insert_char() {
#[test]
fn test_textinput_get_sorted_selection() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "abcdefg");
textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.adjust_horizontal(2, Selection::Selected);
let (begin, end) = textinput.get_sorted_selection().unwrap();
@ -77,17 +82,17 @@ fn test_textinput_get_sorted_selection() {
#[test]
fn test_textinput_replace_selection() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "abcdefg");
textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.adjust_horizontal(2, Selection::Selected);
textinput.replace_selection("xyz".to_owned());
textinput.replace_selection(DOMString("xyz".to_owned()));
assert_eq!(textinput.get_content(), "abxyzefg");
}
#[test]
fn test_textinput_current_line_length() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
assert_eq!(textinput.current_line_length(), 3);
textinput.adjust_vertical(1, Selection::NotSelected);
@ -99,7 +104,7 @@ fn test_textinput_current_line_length() {
#[test]
fn test_textinput_adjust_vertical() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
textinput.adjust_horizontal(3, Selection::NotSelected);
textinput.adjust_vertical(1, Selection::NotSelected);
assert_eq!(textinput.edit_point.line, 1);
@ -116,7 +121,7 @@ fn test_textinput_adjust_vertical() {
#[test]
fn test_textinput_adjust_horizontal() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
textinput.adjust_horizontal(4, Selection::NotSelected);
assert_eq!(textinput.edit_point.line, 1);
assert_eq!(textinput.edit_point.index, 0);
@ -136,14 +141,12 @@ fn test_textinput_adjust_horizontal() {
#[test]
fn test_textinput_handle_return() {
let mut single_line_textinput = TextInput::new(
Lines::Single, "abcdef".to_owned(), DummyClipboardContext::new(""));
let mut single_line_textinput = text_input(Lines::Single, "abcdef");
single_line_textinput.adjust_horizontal(3, Selection::NotSelected);
single_line_textinput.handle_return();
assert_eq!(single_line_textinput.get_content(), "abcdef");
let mut multi_line_textinput = TextInput::new(
Lines::Multiple, "abcdef".to_owned(), DummyClipboardContext::new(""));
let mut multi_line_textinput = text_input(Lines::Multiple, "abcdef");
multi_line_textinput.adjust_horizontal(3, Selection::NotSelected);
multi_line_textinput.handle_return();
assert_eq!(multi_line_textinput.get_content(), "abc\ndef");
@ -151,8 +154,7 @@ fn test_textinput_handle_return() {
#[test]
fn test_textinput_select_all() {
let mut textinput = TextInput::new(
Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
assert_eq!(textinput.edit_point.line, 0);
assert_eq!(textinput.edit_point.index, 0);
@ -163,20 +165,19 @@ fn test_textinput_select_all() {
#[test]
fn test_textinput_get_content() {
let single_line_textinput = TextInput::new(Lines::Single, "abcdefg".to_owned(), DummyClipboardContext::new(""));
let single_line_textinput = text_input(Lines::Single, "abcdefg");
assert_eq!(single_line_textinput.get_content(), "abcdefg");
let multi_line_textinput = TextInput::new(
Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let multi_line_textinput = text_input(Lines::Multiple, "abc\nde\nf");
assert_eq!(multi_line_textinput.get_content(), "abc\nde\nf");
}
#[test]
fn test_textinput_set_content() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
assert_eq!(textinput.get_content(), "abc\nde\nf");
textinput.set_content("abc\nf".to_owned());
textinput.set_content(DOMString("abc\nf".to_owned()));
assert_eq!(textinput.get_content(), "abc\nf");
assert_eq!(textinput.edit_point.line, 0);
@ -184,7 +185,7 @@ fn test_textinput_set_content() {
textinput.adjust_horizontal(3, Selection::Selected);
assert_eq!(textinput.edit_point.line, 0);
assert_eq!(textinput.edit_point.index, 3);
textinput.set_content("de".to_owned());
textinput.set_content(DOMString("de".to_owned()));
assert_eq!(textinput.get_content(), "de");
assert_eq!(textinput.edit_point.line, 0);
assert_eq!(textinput.edit_point.index, 2);
@ -197,7 +198,9 @@ fn test_clipboard_paste() {
#[cfg(not(target_os = "macos"))]
const MODIFIERS: KeyModifiers = CONTROL;
let mut textinput = TextInput::new(Lines::Single, "defg".to_owned(), DummyClipboardContext::new("abc"));
let mut textinput = TextInput::new(Lines::Single,
DOMString("defg".to_owned()),
DummyClipboardContext::new("abc"));
assert_eq!(textinput.get_content(), "defg");
assert_eq!(textinput.edit_point.index, 0);
textinput.handle_keydown_aux(Key::V, MODIFIERS);
@ -206,7 +209,7 @@ fn test_clipboard_paste() {
#[test]
fn test_textinput_cursor_position_correct_after_clearing_selection() {
let mut textinput = TextInput::new(Lines::Single, "abcdef".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Single, "abcdef");
// Single line - Forward
textinput.adjust_horizontal(3, Selection::Selected);
@ -230,7 +233,7 @@ fn test_textinput_cursor_position_correct_after_clearing_selection() {
assert_eq!(textinput.edit_point.index, 0);
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned(), DummyClipboardContext::new(""));
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
// Multiline - Forward
textinput.adjust_horizontal(4, Selection::Selected);