Urlmageddon: Use refcounted urls more often.

This commit is contained in:
Emilio Cobos Álvarez 2016-11-16 11:57:39 +01:00
parent f14e7339b5
commit 913c874cb5
No known key found for this signature in database
GPG key ID: 056B727BB9C1027C
161 changed files with 1044 additions and 718 deletions

View file

@ -23,9 +23,9 @@ profile_traits = {path = "../profile_traits"}
script_traits = {path = "../script_traits"}
serde = "0.8"
serde_derive = "0.8"
servo_url = {path = "../url", features = ["servo"]}
style_traits = {path = "../style_traits"}
time = "0.1.17"
url = {version = "1.2", features = ["heap_size"]}
util = {path = "../util"}
[dependencies.webrender]

View file

@ -26,6 +26,7 @@ use script_traits::{ConstellationMsg, LayoutControlMsg, LoadData, MouseButton};
use script_traits::{MouseEventType, StackingContextScrollState};
use script_traits::{TouchpadPressurePhase, TouchEventType, TouchId, WindowSizeData, WindowSizeType};
use script_traits::CompositorEvent::{self, MouseMoveEvent, MouseButtonEvent, TouchEvent, TouchpadPressureEvent};
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fs::File;
use std::rc::Rc;
@ -34,7 +35,6 @@ use style_traits::{PagePx, ViewportPx};
use style_traits::viewport::ViewportConstraints;
use time::{precise_time_ns, precise_time_s};
use touch::{TouchHandler, TouchAction};
use url::Url;
use util::geometry::ScreenPx;
use util::opts;
use util::prefs::PREFS;
@ -697,7 +697,7 @@ impl<Window: WindowMethods> IOCompositor<Window> {
}
}
fn change_page_url(&mut self, _: PipelineId, url: Url) {
fn change_page_url(&mut self, _: PipelineId, url: ServoUrl) {
self.window.set_page_url(url);
}
@ -881,7 +881,7 @@ impl<Window: WindowMethods> IOCompositor<Window> {
fn on_load_url_window_event(&mut self, url_string: String) {
debug!("osmain: loading URL `{}`", url_string);
self.got_load_complete_message = false;
match Url::parse(&url_string) {
match ServoUrl::parse(&url_string) {
Ok(url) => {
self.window.set_page_url(url.clone());
let msg = match self.root_pipeline {

View file

@ -14,11 +14,11 @@ use net_traits::image::base::Image;
use profile_traits::mem;
use profile_traits::time;
use script_traits::{AnimationState, ConstellationMsg, EventResult};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::sync::mpsc::{Receiver, Sender};
use style_traits::cursor::Cursor;
use style_traits::viewport::ViewportConstraints;
use url::Url;
use webrender;
use webrender_traits;
@ -76,7 +76,7 @@ pub enum Msg {
/// Alerts the compositor that the current page has changed its title.
ChangePageTitle(PipelineId, Option<String>),
/// Alerts the compositor that the current page has changed its URL.
ChangePageUrl(PipelineId, Url),
ChangePageUrl(PipelineId, ServoUrl),
/// Alerts the compositor that the given pipeline has changed whether it is running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Replaces the current frame tree, typically called during main frame navigation.
@ -102,7 +102,7 @@ pub enum Msg {
/// A reply to the compositor asking if the output image is stable.
IsReadyToSaveImageReply(bool),
/// A favicon was detected
NewFavicon(Url),
NewFavicon(ServoUrl),
/// <head> tag finished parsing
HeadParsed,
/// A status message to be displayed by the browser chrome.

View file

@ -23,9 +23,9 @@ extern crate profile_traits;
extern crate script_traits;
#[macro_use]
extern crate serde_derive;
extern crate servo_url;
extern crate style_traits;
extern crate time;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender;

View file

@ -13,9 +13,9 @@ use gfx_traits::DevicePixel;
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use net_traits::net_error_list::NetError;
use script_traits::{MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use style_traits::cursor::Cursor;
use url::Url;
use util::geometry::ScreenPx;
#[derive(Clone)]
@ -123,7 +123,7 @@ pub trait WindowMethods {
/// Sets the page title for the current page.
fn set_page_title(&self, title: Option<String>);
/// Sets the load data for the current page.
fn set_page_url(&self, url: Url);
fn set_page_url(&self, url: ServoUrl);
/// Called when the browser chrome should display a status message.
fn status(&self, Option<String>);
/// Called when the browser has started loading a frame.
@ -160,5 +160,5 @@ pub trait WindowMethods {
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, url: Url);
fn set_favicon(&self, url: ServoUrl);
}

View file

@ -33,7 +33,7 @@ script_traits = {path = "../script_traits"}
serde = "0.8"
serde_derive = "0.8"
style_traits = {path = "../style_traits"}
url = {version = "1.2", features = ["heap_size"]}
servo_url = {path = "../url", features = ["servo"]}
util = {path = "../util"}
[dependencies.webrender_traits]

View file

@ -46,6 +46,7 @@ use script_traits::{LayoutMsg as FromLayoutMsg, ScriptMsg as FromScriptMsg, Scri
use script_traits::{LogEntry, ServiceWorkerMsg, webdriver_msg};
use script_traits::{MozBrowserErrorType, MozBrowserEvent, WebDriverCommandMsg, WindowSizeData};
use script_traits::{SWManagerMsg, ScopeThings, WindowSizeType};
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::{HashMap, VecDeque};
use std::io::Error as IOError;
@ -62,7 +63,6 @@ use style_traits::PagePx;
use style_traits::cursor::Cursor;
use style_traits::viewport::ViewportConstraints;
use timer_scheduler::TimerScheduler;
use url::Url;
use util::opts;
use util::prefs::PREFS;
use util::remutex::ReentrantMutex;
@ -1047,7 +1047,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
}
}
fn handle_register_serviceworker(&self, scope_things: ScopeThings, scope: Url) {
fn handle_register_serviceworker(&self, scope_things: ScopeThings, scope: ServoUrl) {
if let Some(ref mgr) = self.swmanager_chan {
let _ = mgr.send(ServiceWorkerMsg::RegisterServiceWorker(scope_things, scope));
} else {
@ -1055,7 +1055,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
}
}
fn handle_broadcast_storage_event(&self, pipeline_id: PipelineId, storage: StorageType, url: Url,
fn handle_broadcast_storage_event(&self, pipeline_id: PipelineId, storage: StorageType, url: ServoUrl,
key: Option<String>, old_value: Option<String>, new_value: Option<String>) {
let origin = url.origin();
for pipeline in self.pipelines.values() {
@ -1204,7 +1204,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
self.close_pipeline(pending_pipeline_id, ExitPipelineMode::Force);
}
let failure_url = Url::parse("about:failure").expect("infallible");
let failure_url = ServoUrl::parse("about:failure").expect("infallible");
if let Some(pipeline_url) = pipeline_url {
if pipeline_url == failure_url {
@ -1245,7 +1245,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
}
}
fn handle_init_load(&mut self, url: Url) {
fn handle_init_load(&mut self, url: ServoUrl) {
let window_size = self.window_size.visible_viewport;
let root_pipeline_id = PipelineId::new();
let root_frame_id = self.root_frame_id;
@ -1331,7 +1331,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
let load_data = load_info.load_data.unwrap_or_else(|| {
let url = match old_pipeline {
Some(old_pipeline) => old_pipeline.url.clone(),
None => Url::parse("about:blank").expect("infallible"),
None => ServoUrl::parse("about:blank").expect("infallible"),
};
// TODO - loaddata here should have referrer info (not None, None)

View file

@ -36,8 +36,8 @@ extern crate script_traits;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate servo_url;
extern crate style_traits;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender_traits;

View file

@ -26,6 +26,7 @@ use script_traits::{ConstellationControlMsg, InitialScriptState};
use script_traits::{LayoutControlMsg, LayoutMsg, LoadData, MozBrowserEvent};
use script_traits::{NewLayoutInfo, SWManagerMsg, SWManagerSenders, ScriptMsg};
use script_traits::{ScriptThreadFactory, TimerEventRequest, WindowSizeData};
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
@ -34,7 +35,6 @@ use std::process;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use style_traits::{PagePx, ViewportPx};
use url::Url;
use util::opts::{self, Opts};
use util::prefs::{PREFS, Pref};
use webrender_traits;
@ -58,7 +58,7 @@ pub struct Pipeline {
/// A channel to the compositor.
pub compositor_proxy: Box<CompositorProxy + 'static + Send>,
/// URL corresponding to the most recently-loaded page.
pub url: Url,
pub url: ServoUrl,
/// The title of the most recently-loaded page.
pub title: Option<String>,
pub size: Option<TypedSize2D<f32, PagePx>>,
@ -264,7 +264,7 @@ impl Pipeline {
layout_chan: IpcSender<LayoutControlMsg>,
compositor_proxy: Box<CompositorProxy + 'static + Send>,
is_private: bool,
url: Url,
url: ServoUrl,
size: Option<TypedSize2D<f32, PagePx>>,
visible: bool)
-> Pipeline {

View file

@ -19,5 +19,5 @@ ipc-channel = "0.5"
msg = {path = "../msg"}
serde = "0.8"
serde_derive = "0.8"
servo_url = {path = "../url"}
time = "0.1"
url = {version = "1.2", features = ["heap_size"]}

View file

@ -24,24 +24,24 @@ extern crate ipc_channel;
extern crate msg;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate servo_url;
extern crate time;
extern crate url;
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use servo_url::ServoUrl;
use std::net::TcpStream;
use time::Duration;
use time::Tm;
use url::Url;
// Information would be attached to NewGlobal to be received and show in devtools.
// Extend these fields if we need more information.
#[derive(Debug, Deserialize, Serialize)]
pub struct DevtoolsPageInfo {
pub title: String,
pub url: Url
pub url: ServoUrl,
}
#[derive(Debug, Deserialize, HeapSizeOf, Serialize, Clone)]
@ -292,7 +292,7 @@ pub enum CachedConsoleMessage {
#[derive(Debug, PartialEq)]
pub struct HttpRequest {
pub url: Url,
pub url: ServoUrl,
pub method: Method,
pub headers: Headers,
pub body: Option<Vec<u8>>,

View file

@ -32,13 +32,13 @@ range = {path = "../range"}
rustc-serialize = "0.3"
serde = "0.8"
servo_atoms = {path = "../atoms"}
servo_url = {path = "../url"}
serde_derive = "0.8"
smallvec = "0.1"
style = {path = "../style"}
style_traits = {path = "../style_traits"}
time = "0.1.12"
unicode-script = {version = "0.1", features = ["harfbuzz"]}
url = {version = "1.2", features = ["heap_size"]}
util = {path = "../util"}
xi-unicode = "0.0.1"

View file

@ -15,6 +15,7 @@ use platform::font_list::last_resort_font_families;
use platform::font_list::system_default_family;
use platform::font_template::FontTemplateData;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::mem;
@ -23,7 +24,6 @@ use std::sync::{Arc, Mutex};
use std::u32;
use style::font_face::{EffectiveSources, Source};
use style::properties::longhands::font_family::computed_value::FontFamily;
use url::Url;
use util::thread::spawn_named;
use webrender_traits;
@ -106,7 +106,7 @@ pub enum Command {
GetFontTemplate(FontFamily, FontTemplateDescriptor, IpcSender<Reply>),
GetLastResortFontTemplate(FontTemplateDescriptor, IpcSender<Reply>),
AddWebFont(LowercaseString, EffectiveSources, IpcSender<()>),
AddDownloadedWebFont(LowercaseString, Url, Vec<u8>, IpcSender<()>),
AddDownloadedWebFont(LowercaseString, ServoUrl, Vec<u8>, IpcSender<()>),
Exit(IpcSender<()>),
}
@ -206,7 +206,11 @@ impl FontCache {
match src {
Source::Url(url_source) => {
// https://drafts.csswg.org/css-fonts/#font-fetching-requirements
let url = url_source.url;
let url = match url_source.url.url() {
Some(url) => url.clone(),
None => return,
};
let request = RequestInit {
url: url.clone(),
type_: RequestType::Font,
@ -242,7 +246,7 @@ impl FontCache {
Err(_) => {
// FIXME(servo/fontsan#1): get an error message
debug!("Sanitiser rejected web font: \
family={:?} url={}", family_name, url);
family={:?} url={:?}", family_name, url);
let msg = Command::AddWebFont(family_name.clone(), sources.clone(), sender.clone());
channel_to_self.send(msg).unwrap();
return;

View file

@ -63,17 +63,15 @@ extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate servo_url;
#[macro_use] extern crate servo_atoms;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
extern crate simd;
#[macro_use] extern crate servo_atoms;
extern crate smallvec;
extern crate style;
extern crate style_traits;
extern crate time;
extern crate unicode_script;
extern crate url;
extern crate util;
extern crate webrender_traits;
extern crate xi_unicode;

View file

@ -10,13 +10,13 @@ use core_text::font::CTFont;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de::{Error, Visitor};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Error as IoError};
use std::ops::Deref;
use std::sync::Mutex;
use url::Url;
/// Platform specific font representation for mac.
/// The identifier is a PostScript font name. The
@ -86,13 +86,13 @@ impl FontTemplateData {
None => {}
}
let path = Url::parse(&*self.ctfont(0.0)
let path = ServoUrl::parse(&*self.ctfont(0.0)
.expect("No Core Text font available!")
.url()
.expect("No URL for Core Text font!")
.get_string()
.to_string()).expect("Couldn't parse Core Text font URL!")
.to_file_path()
.as_url().unwrap().to_file_path()
.expect("Core Text font didn't name a path!");
let mut bytes = Vec::new();
File::open(path).expect("Couldn't open font file!").read_to_end(&mut bytes).unwrap();

View file

@ -39,12 +39,12 @@ serde = "0.8"
serde_derive = "0.8"
serde_json = "0.8"
servo_atoms = {path = "../atoms"}
servo_url = {path = "../url"}
smallvec = "0.1"
style = {path = "../style"}
style_traits = {path = "../style_traits"}
unicode-bidi = "0.2"
unicode-script = {version = "0.1", features = ["harfbuzz"]}
url = {version = "1.2", features = ["heap_size"]}
util = {path = "../util"}
[dependencies.webrender_traits]

View file

@ -38,6 +38,7 @@ use multicol::{MulticolColumnFlow, MulticolFlow};
use parallel;
use script_layout_interface::{LayoutElementType, LayoutNodeType, is_image_data};
use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::LinkedList;
use std::marker::PhantomData;
@ -62,7 +63,6 @@ use table_rowgroup::TableRowGroupFlow;
use table_wrapper::TableWrapperFlow;
use text::TextRunScanner;
use traversal::PostorderNodeMutTraversal;
use url::Url;
use util::opts;
use wrapper::{LayoutNodeLayoutData, TextContent, ThreadSafeLayoutNodeHelpers};
@ -1207,7 +1207,7 @@ impl<'a, ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode>
let marker_fragments = match node.style(self.style_context()).get_list().list_style_image {
list_style_image::T::Url(ref url_value) => {
let image_info = box ImageFragmentInfo::new(node,
url_value.url().map(|u| (**u).clone()),
url_value.url().map(|u| u.clone()),
&self.layout_context.shared);
vec![Fragment::new(node, SpecificFragmentInfo::Image(image_info), self.layout_context)]
}
@ -1675,7 +1675,7 @@ trait ObjectElement {
fn has_object_data(&self) -> bool;
/// Returns the "data" attribute value parsed as a URL
fn object_data(&self) -> Option<Url>;
fn object_data(&self) -> Option<ServoUrl>;
}
impl<N> ObjectElement for N where N: ThreadSafeLayoutNode {
@ -1691,14 +1691,14 @@ impl<N> ObjectElement for N where N: ThreadSafeLayoutNode {
}
}
fn object_data(&self) -> Option<Url> {
fn object_data(&self) -> Option<ServoUrl> {
let elem = self.as_element().unwrap();
let type_and_data = (
elem.get_attr(&ns!(), &local_name!("type")),
elem.get_attr(&ns!(), &local_name!("data")),
);
match type_and_data {
(None, Some(uri)) if is_image_data(uri) => Url::parse(uri).ok(),
(None, Some(uri)) if is_image_data(uri) => ServoUrl::parse(uri).ok(),
_ => None
}
}

View file

@ -17,13 +17,13 @@ use net_traits::image::base::Image;
use net_traits::image_cache_thread::{ImageCacheChan, ImageCacheThread, ImageResponse, ImageState};
use net_traits::image_cache_thread::{ImageOrMetadataAvailable, UsePlaceholder};
use parking_lot::RwLock;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use style::context::{LocalStyleContext, StyleContext, SharedStyleContext};
use url::Url;
use util::opts;
struct LocalLayoutContext {
@ -83,7 +83,7 @@ pub struct SharedLayoutContext {
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(Url, UsePlaceholder),
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
}
@ -125,7 +125,7 @@ impl<'a> LayoutContext<'a> {
}
impl SharedLayoutContext {
fn get_or_request_image_synchronously(&self, url: Url, use_placeholder: UsePlaceholder)
fn get_or_request_image_synchronously(&self, url: ServoUrl, use_placeholder: UsePlaceholder)
-> Option<Arc<Image>> {
debug_assert!(opts::get().output_file.is_some() || opts::get().exit_after_load);
@ -161,7 +161,7 @@ impl SharedLayoutContext {
}
}
pub fn get_or_request_image_or_meta(&self, url: Url, use_placeholder: UsePlaceholder)
pub fn get_or_request_image_or_meta(&self, url: ServoUrl, use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
// If we are emitting an output file, load the image synchronously.
if opts::get().output_file.is_some() || opts::get().exit_after_load {
@ -190,23 +190,23 @@ impl SharedLayoutContext {
}
pub fn get_webrender_image_for_url(&self,
url: &Url,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&((*url).clone(), use_placeholder)) {
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta((*url).clone(), use_placeholder) {
match self.get_or_request_image_or_meta(url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert(((*url).clone(), use_placeholder),
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}

View file

@ -36,6 +36,7 @@ use model::{self, MaybeAuto, ToGfxMatrix};
use net_traits::image::base::PixelFormat;
use net_traits::image_cache_thread::UsePlaceholder;
use range::Range;
use servo_url::ServoUrl;
use std::{cmp, f32};
use std::collections::HashMap;
use std::default::Default;
@ -57,7 +58,6 @@ use style::values::computed::{Gradient, GradientKind, LengthOrPercentage, Length
use style::values::specified::{AngleOrCorner, HorizontalDirection, VerticalDirection};
use style_traits::cursor::Cursor;
use table_cell::CollapsedBordersForCell;
use url::Url;
use util::opts;
use webrender_traits::{ColorF, GradientStop};
@ -360,7 +360,7 @@ pub trait FragmentDisplayListBuilding {
display_list_section: DisplayListSection,
absolute_bounds: &Rect<Au>,
clip: &ClippingRegion,
image_url: &Url,
image_url: &ServoUrl,
background_index: usize);
/// Adds the display items necessary to paint the background linear gradient of this fragment
@ -692,11 +692,11 @@ impl FragmentDisplayListBuilding for Fragment {
display_list_section: DisplayListSection,
absolute_bounds: &Rect<Au>,
clip: &ClippingRegion,
image_url: &Url,
image_url: &ServoUrl,
index: usize) {
let background = style.get_background();
let webrender_image = state.shared_layout_context
.get_webrender_image_for_url(image_url,
.get_webrender_image_for_url(image_url.clone(),
UsePlaceholder::No);
if let Some(webrender_image) = webrender_image {

View file

@ -32,6 +32,7 @@ use script_layout_interface::HTMLCanvasData;
use script_layout_interface::SVGSVGData;
use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
use serde::{Serialize, Serializer};
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::cmp::{max, min};
use std::collections::LinkedList;
@ -54,7 +55,6 @@ use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto};
use style::values::computed::LengthOrPercentageOrNone;
use text;
use text::TextRunScanner;
use url::Url;
// From gfxFontConstants.h in Firefox.
static FONT_SUBSCRIPT_OFFSET_RATIO: f32 = 0.20;
@ -419,7 +419,7 @@ impl ImageFragmentInfo {
///
/// FIXME(pcwalton): The fact that image fragments store the cache in the fragment makes little
/// sense to me.
pub fn new<N: ThreadSafeLayoutNode>(node: &N, url: Option<Url>,
pub fn new<N: ThreadSafeLayoutNode>(node: &N, url: Option<ServoUrl>,
shared_layout_context: &SharedLayoutContext)
-> ImageFragmentInfo {
let image_or_metadata = url.and_then(|url| {

View file

@ -52,12 +52,12 @@ extern crate serde;
extern crate serde_derive;
extern crate serde_json;
#[macro_use] extern crate servo_atoms;
extern crate servo_url;
extern crate smallvec;
extern crate style;
extern crate style_traits;
extern crate unicode_bidi;
extern crate unicode_script;
extern crate url;
extern crate util;
extern crate webrender_traits;

View file

@ -24,6 +24,7 @@ lazy_static = "0.2"
log = "0.3.5"
msg = {path = "../msg"}
net_traits = {path = "../net_traits"}
style_traits = {path = "../style_traits"}
parking_lot = {version = "0.3.3", features = ["nightly"]}
plugins = {path = "../plugins"}
profile_traits = {path = "../profile_traits"}
@ -34,8 +35,8 @@ script_traits = {path = "../script_traits"}
selectors = "0.14"
serde_derive = "0.8"
serde_json = "0.8"
servo_url = {path = "../url"}
style = {path = "../style"}
url = {version = "1.2", features = ["heap_size"]}
util = {path = "../util"}
[dependencies.webrender_traits]

View file

@ -40,8 +40,9 @@ extern crate script_layout_interface;
extern crate script_traits;
extern crate selectors;
extern crate serde_json;
extern crate servo_url;
extern crate style;
extern crate url;
extern crate style_traits;
extern crate util;
extern crate webrender_traits;
@ -94,6 +95,7 @@ use script_layout_interface::wrapper_traits::LayoutNode;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{StackingContextScrollState, UntrustedNodeAddress};
use selectors::Element;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
@ -114,7 +116,6 @@ use style::servo::restyle_damage::{REFLOW, REFLOW_OUT_OF_FLOW, REPAINT, REPOSITI
use style::stylesheets::{Origin, Stylesheet, UserAgentStylesheets};
use style::thread_state;
use style::timer::Timer;
use url::Url;
use util::geometry::max_rect;
use util::opts;
use util::prefs::PREFS;
@ -127,7 +128,7 @@ pub struct LayoutThread {
id: PipelineId,
/// The URL of the pipeline that we belong to.
url: Url,
url: ServoUrl,
/// Is the current reflow of an iframe, as opposed to a root window?
is_iframe: bool,
@ -213,7 +214,7 @@ pub struct LayoutThread {
/// The CSS error reporter for all CSS loaded in this layout thread
error_reporter: CSSErrorReporter,
webrender_image_cache: Arc<RwLock<HashMap<(Url, UsePlaceholder),
webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
@ -234,7 +235,7 @@ impl LayoutThreadFactory for LayoutThread {
/// Spawns a new layout thread.
fn create(id: PipelineId,
url: Url,
url: ServoUrl,
is_iframe: bool,
chan: (Sender<Msg>, Receiver<Msg>),
pipeline_port: IpcReceiver<LayoutControlMsg>,
@ -365,7 +366,7 @@ fn add_font_face_rules(stylesheet: &Stylesheet,
impl LayoutThread {
/// Creates a new `LayoutThread` structure.
fn new(id: PipelineId,
url: Url,
url: ServoUrl,
is_iframe: bool,
port: Receiver<Msg>,
pipeline_port: IpcReceiver<LayoutControlMsg>,
@ -1500,7 +1501,7 @@ fn get_ua_stylesheets() -> Result<UserAgentStylesheets, &'static str> {
let res = try!(read_resource_file(filename).map_err(|_| filename));
Ok(Stylesheet::from_bytes(
&res,
Url::parse(&format!("chrome://resources/{:?}", filename)).unwrap(),
ServoUrl::parse(&format!("chrome://resources/{:?}", filename)).unwrap(),
None,
None,
Origin::UserAgent,

View file

@ -16,7 +16,7 @@ msg = {path = "../msg"}
net_traits = {path = "../net_traits"}
profile_traits = {path = "../profile_traits"}
ipc-channel = "0.5"
url = {version = "1.2", features = ["heap_size"]}
servo_url = {path = "../url"}
[dependencies.webrender_traits]
git = "https://github.com/servo/webrender"

View file

@ -10,7 +10,7 @@ extern crate msg;
extern crate net_traits;
extern crate profile_traits;
extern crate script_traits;
extern crate url;
extern crate servo_url;
extern crate webrender_traits;
// This module contains traits in layout used generically
@ -25,15 +25,15 @@ use net_traits::image_cache_thread::ImageCacheThread;
use profile_traits::{mem, time};
use script_traits::{ConstellationControlMsg, LayoutControlMsg};
use script_traits::LayoutMsg as ConstellationMsg;
use servo_url::ServoUrl;
use std::sync::mpsc::{Receiver, Sender};
use url::Url;
// A static method creating a layout thread
// Here to remove the compositor -> layout dependency
pub trait LayoutThreadFactory {
type Message;
fn create(id: PipelineId,
url: Url,
url: ServoUrl,
is_iframe: bool,
chan: (Sender<Self::Message>, Receiver<Self::Message>),
pipeline_port: IpcReceiver<LayoutControlMsg>,

View file

@ -34,6 +34,7 @@ profile_traits = {path = "../profile_traits"}
rustc-serialize = "0.3"
serde = "0.8"
serde_derive = "0.8"
servo_url = {path = "../url"}
threadpool = "1.0"
time = "0.1.17"
unicase = "1.4.0"

View file

@ -11,6 +11,7 @@ use net_traits::{LoadConsumer, LoadData, Metadata, NetworkError};
use net_traits::ProgressMsg::Done;
use net_traits::response::HttpsState;
use resource_thread::{CancellationListener, send_error, start_sending_sniffed_opt};
use servo_url::ServoUrl;
use std::io;
use std::sync::Arc;
use url::Url;
@ -20,7 +21,7 @@ fn url_from_non_relative_scheme(load_data: &mut LoadData, filename: &str) -> io:
let mut path = try!(resources_dir_path());
path.push(filename);
assert!(path.exists());
load_data.url = Url::from_file_path(&*path).unwrap();
load_data.url = ServoUrl::from_url(Url::from_file_path(&*path).unwrap());
Ok(())
}

View file

@ -16,9 +16,9 @@ use net_traits::filemanager_thread::{FileManagerThreadMsg, ReadFileProgress};
use net_traits::response::HttpsState;
use resource_thread::{send_error, start_sending_sniffed_opt};
use resource_thread::CancellationListener;
use servo_url::ServoUrl;
use std::boxed::FnBox;
use std::sync::Arc;
use url::Url;
use util::thread::spawn_named;
// TODO: Check on GET
@ -124,7 +124,7 @@ fn load_blob<UI: 'static + UIProvider>
/// https://fetch.spec.whatwg.org/#concept-basic-fetch (partial)
// TODO: make async.
pub fn load_blob_sync<UI: 'static + UIProvider>
(url: Url,
(url: ServoUrl,
filemanager: FileManager<UI>)
-> Result<(Headers, Vec<u8>), NetworkError> {
let (id, origin) = match parse_blob_url(&url) {

View file

@ -6,13 +6,13 @@ use file_loader;
use mime_classifier::MimeClassifier;
use net_traits::{LoadConsumer, LoadData, NetworkError};
use resource_thread::{CancellationListener, send_error};
use servo_url::ServoUrl;
use std::fs::canonicalize;
use std::sync::Arc;
use url::Url;
use url::percent_encoding::percent_decode;
use util::resource_files::resources_dir_path;
pub fn resolve_chrome_url(url: &Url) -> Result<Url, ()> {
pub fn resolve_chrome_url(url: &ServoUrl) -> Result<ServoUrl, ()> {
assert_eq!(url.scheme(), "chrome");
if url.host_str() != Some("resources") {
return Err(())
@ -29,7 +29,7 @@ pub fn resolve_chrome_url(url: &Url) -> Result<Url, ()> {
}
match canonicalize(path) {
Ok(ref path) if path.starts_with(&resources) && path.exists() => {
Ok(Url::from_file_path(path).unwrap())
Ok(ServoUrl::from_file_path(path).unwrap())
}
_ => Err(())
}

View file

@ -8,10 +8,10 @@
use cookie_rs;
use net_traits::CookieSource;
use net_traits::pub_domains::is_pub_domain;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::net::{Ipv4Addr, Ipv6Addr};
use time::{Tm, now, at, Duration};
use url::Url;
/// A stored cookie that wraps the definition in cookie-rs. This is used to implement
/// various behaviours defined in the spec that rely on an associated request URL,
@ -28,7 +28,7 @@ pub struct Cookie {
impl Cookie {
/// http://tools.ietf.org/html/rfc6265#section-5.3
pub fn new_wrapped(mut cookie: cookie_rs::Cookie, request: &Url, source: CookieSource)
pub fn new_wrapped(mut cookie: cookie_rs::Cookie, request: &ServoUrl, source: CookieSource)
-> Option<Cookie> {
// Step 3
let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) {
@ -145,7 +145,7 @@ impl Cookie {
}
// http://tools.ietf.org/html/rfc6265#section-5.4 step 1
pub fn appropriate_for_url(&self, url: &Url, source: CookieSource) -> bool {
pub fn appropriate_for_url(&self, url: &ServoUrl, source: CookieSource) -> bool {
let domain = url.host_str();
if self.host_only {
if self.cookie.domain.as_ref().map(String::as_str) != domain {

View file

@ -8,8 +8,8 @@
use cookie::Cookie;
use cookie_rs;
use net_traits::CookieSource;
use servo_url::ServoUrl;
use std::cmp::Ordering;
use url::Url;
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct CookieStorage {
@ -84,7 +84,7 @@ impl CookieStorage {
}
// http://tools.ietf.org/html/rfc6265#section-5.4
pub fn cookies_for_url(&mut self, url: &Url, source: CookieSource) -> Option<String> {
pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option<String> {
let filterer = |c: &&mut Cookie| -> bool {
info!(" === SENT COOKIE : {} {} {:?} {:?}",
c.cookie.name, c.cookie.value, c.cookie.domain, c.cookie.path);
@ -116,7 +116,7 @@ impl CookieStorage {
}
}
pub fn cookies_data_for_url<'a>(&'a mut self, url: &'a Url,
pub fn cookies_data_for_url<'a>(&'a mut self, url: &'a ServoUrl,
source: CookieSource) -> Box<Iterator<Item=cookie_rs::Cookie> + 'a> {
Box::new(self.cookies.iter_mut().filter(move |c| { c.appropriate_for_url(url, source) }).map(|c| {
c.touch();

View file

@ -9,8 +9,9 @@ use net_traits::LoadConsumer;
use net_traits::ProgressMsg::{Done, Payload};
use resource_thread::{CancellationListener, send_error, start_sending_sniffed_opt};
use rustc_serialize::base64::FromBase64;
use servo_url::ServoUrl;
use std::sync::Arc;
use url::{Position, Url};
use url::Position;
use url::percent_encoding::percent_decode;
pub fn factory(load_data: LoadData,
@ -31,10 +32,10 @@ pub enum DecodeError {
pub type DecodeData = (Mime, Vec<u8>);
pub fn decode(url: &Url) -> Result<DecodeData, DecodeError> {
assert!(url.scheme() == "data");
pub fn decode(url: &ServoUrl) -> Result<DecodeData, DecodeError> {
assert_eq!(url.scheme(), "data");
// Split out content type and data.
let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery].splitn(2, ',').collect();
let parts: Vec<&str> = url.as_url().unwrap()[Position::BeforePath..Position::AfterQuery].splitn(2, ',').collect();
if parts.len() != 2 {
return Err(DecodeError::InvalidDataUri);
}
@ -61,7 +62,7 @@ pub fn decode(url: &Url) -> Result<DecodeData, DecodeError> {
if is_base64 {
// FIXME(#2909): Its unclear what to do with non-alphabet characters,
// but Acid 3 apparently depends on spaces being ignored.
bytes = bytes.into_iter().filter(|&b| b != ' ' as u8).collect::<Vec<u8>>();
bytes = bytes.into_iter().filter(|&b| b != b' ').collect::<Vec<u8>>();
match bytes.from_base64() {
Err(..) => return Err(DecodeError::NonBase64DataUri),
Ok(data) => bytes = data,

View file

@ -11,9 +11,9 @@
use hyper::method::Method;
use net_traits::request::{CredentialsMode, Origin, Request};
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use time::{self, Timespec};
use url::Url;
/// Union type for CORS cache entries
///
@ -44,7 +44,7 @@ impl HeaderOrMethod {
#[derive(Clone, Debug)]
pub struct CorsCacheEntry {
pub origin: Origin,
pub url: Url,
pub url: ServoUrl,
pub max_age: u32,
pub credentials: bool,
pub header_or_method: HeaderOrMethod,
@ -52,7 +52,7 @@ pub struct CorsCacheEntry {
}
impl CorsCacheEntry {
fn new(origin: Origin, url: Url, max_age: u32, credentials: bool,
fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool,
header_or_method: HeaderOrMethod) -> CorsCacheEntry {
CorsCacheEntry {
origin: origin,

View file

@ -29,6 +29,7 @@ use net_traits::request::{RedirectMode, Referrer, Request, RequestMode, Response
use net_traits::request::{Type, Origin, Window};
use net_traits::response::{HttpsState, Response, ResponseBody, ResponseType};
use resource_thread::CancellationListener;
use servo_url::ServoUrl;
use std::borrow::Cow;
use std::collections::HashSet;
use std::error::Error;
@ -40,7 +41,7 @@ use std::ops::Deref;
use std::rc::Rc;
use std::sync::mpsc::{channel, Sender, Receiver};
use unicase::UniCase;
use url::{Origin as UrlOrigin, Url};
use url::{Origin as UrlOrigin};
use util::thread::spawn_named;
use uuid;
@ -1305,7 +1306,7 @@ fn cors_check(request: Rc<Request>, response: &Response) -> Result<(), ()> {
Err(())
}
fn has_credentials(url: &Url) -> bool {
fn has_credentials(url: &ServoUrl) -> bool {
!url.username().is_empty() || url.password().is_some()
}

View file

@ -10,13 +10,13 @@ use net_traits::{LoadConsumer, LoadData, LoadOrigin, Metadata, NetworkError, Ref
use net_traits::ProgressMsg::{Done, Payload};
use resource_thread::{CancellationListener, ProgressSender};
use resource_thread::{send_error, start_sending_sniffed_opt};
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use url::Url;
use util::thread::spawn_named;
static READ_SIZE: usize = 8192;
@ -33,7 +33,7 @@ enum LoadResult {
struct FileLoadOrigin;
impl LoadOrigin for FileLoadOrigin {
fn referrer_url(&self) -> Option<Url> {
fn referrer_url(&self) -> Option<ServoUrl> {
None
}
fn referrer_policy(&self) -> Option<ReferrerPolicy> {
@ -97,7 +97,7 @@ pub fn factory(load_data: LoadData,
// this should be one of the three errors listed in
// http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open
// but, we'll go for a "file not found!"
let url = Url::parse("about:not-found").unwrap();
let url = ServoUrl::parse("about:not-found").unwrap();
let load_data_404 = LoadData::new(load_data.context, url, &FileLoadOrigin);
about_loader::factory(load_data_404, senders, classifier, cancel_listener);
return;

View file

@ -39,6 +39,7 @@ use openssl::ssl::error::{OpensslError, SslError};
use profile_traits::time::{ProfilerCategory, ProfilerChan, TimerMetadata, profile};
use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType};
use resource_thread::{AuthCache, AuthCacheEntry, CancellationListener, send_error, start_sending_sniffed_opt};
use servo_url::ServoUrl;
use std::borrow::{Cow, ToOwned};
use std::boxed::FnBox;
use std::collections::HashSet;
@ -52,7 +53,7 @@ use time;
use time::Tm;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
use tinyfiledialogs;
use url::{Position, Url, Origin};
use url::{Position, Origin};
use util::thread::spawn_named;
use uuid;
@ -246,7 +247,7 @@ impl Read for ReadableCustomResponse {
pub trait HttpRequestFactory {
type R: HttpRequest;
fn create(&self, url: Url, method: Method, headers: Headers) -> Result<Self::R, LoadError>;
fn create(&self, url: ServoUrl, method: Method, headers: Headers) -> Result<Self::R, LoadError>;
}
pub struct NetworkHttpRequestFactory {
@ -256,9 +257,11 @@ pub struct NetworkHttpRequestFactory {
impl HttpRequestFactory for NetworkHttpRequestFactory {
type R = WrappedHttpRequest;
fn create(&self, url: Url, method: Method, headers: Headers)
fn create(&self, url: ServoUrl, method: Method, headers: Headers)
-> Result<WrappedHttpRequest, LoadError> {
let connection = Request::with_connector(method, url.clone(), &*self.connector);
let connection = Request::with_connector(method,
url.clone().into_url().unwrap(),
&*self.connector);
if let Err(HttpError::Ssl(ref error)) = connection {
let error: &(Error + Send + 'static) = &**error;
@ -308,7 +311,7 @@ impl HttpRequest for WrappedHttpRequest {
type R = WrappedHttpResponse;
fn send(self, body: &Option<Vec<u8>>) -> Result<WrappedHttpResponse, LoadError> {
let url = self.request.url.clone();
let url = ServoUrl::from_url(self.request.url.clone());
let mut request_writer = match self.request.start() {
Ok(streaming) => streaming,
Err(e) => return Err(LoadError::new(url, LoadErrorType::Connection { reason: e.description().to_owned() })),
@ -335,12 +338,12 @@ impl HttpRequest for WrappedHttpRequest {
#[derive(Debug)]
pub struct LoadError {
pub url: Url,
pub url: ServoUrl,
pub error: LoadErrorType,
}
impl LoadError {
pub fn new(url: Url, error: LoadErrorType) -> LoadError {
pub fn new(url: ServoUrl, error: LoadErrorType) -> LoadError {
LoadError {
url: url,
error: error,
@ -429,7 +432,7 @@ pub fn set_default_accept_language(headers: &mut Headers) {
}
/// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-state-no-referrer-when-downgrade
fn no_referrer_when_downgrade_header(referrer_url: Url, url: Url) -> Option<Url> {
fn no_referrer_when_downgrade_header(referrer_url: ServoUrl, url: ServoUrl) -> Option<ServoUrl> {
if referrer_url.scheme() == "https" && url.scheme() != "https" {
return None;
}
@ -437,7 +440,7 @@ fn no_referrer_when_downgrade_header(referrer_url: Url, url: Url) -> Option<Url>
}
/// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin
fn strict_origin(referrer_url: Url, url: Url) -> Option<Url> {
fn strict_origin(referrer_url: ServoUrl, url: ServoUrl) -> Option<ServoUrl> {
if referrer_url.scheme() == "https" && url.scheme() != "https" {
return None;
}
@ -445,7 +448,7 @@ fn strict_origin(referrer_url: Url, url: Url) -> Option<Url> {
}
/// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin
fn strict_origin_when_cross_origin(referrer_url: Url, url: Url) -> Option<Url> {
fn strict_origin_when_cross_origin(referrer_url: ServoUrl, url: ServoUrl) -> Option<ServoUrl> {
if referrer_url.scheme() == "https" && url.scheme() != "https" {
return None;
}
@ -454,14 +457,17 @@ fn strict_origin_when_cross_origin(referrer_url: Url, url: Url) -> Option<Url> {
}
/// https://w3c.github.io/webappsec-referrer-policy/#strip-url
fn strip_url(mut referrer_url: Url, origin_only: bool) -> Option<Url> {
fn strip_url(mut referrer_url: ServoUrl, origin_only: bool) -> Option<ServoUrl> {
if referrer_url.scheme() == "https" || referrer_url.scheme() == "http" {
referrer_url.set_username("").unwrap();
referrer_url.set_password(None).unwrap();
referrer_url.set_fragment(None);
{
let referrer = referrer_url.as_mut_url().unwrap();
referrer.set_username("").unwrap();
referrer.set_password(None).unwrap();
referrer.set_fragment(None);
if origin_only {
referrer_url.set_path("");
referrer_url.set_query(None);
referrer.set_path("");
referrer.set_query(None);
}
}
return Some(referrer_url);
}
@ -471,8 +477,8 @@ fn strip_url(mut referrer_url: Url, origin_only: bool) -> Option<Url> {
/// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
pub fn determine_request_referrer(headers: &mut Headers,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<Url>,
url: Url) -> Option<Url> {
referrer_url: Option<ServoUrl>,
url: ServoUrl) -> Option<ServoUrl> {
//TODO - algorithm step 2 not addressed
assert!(!headers.has::<Referer>());
if let Some(ref_url) = referrer_url {
@ -492,7 +498,7 @@ pub fn determine_request_referrer(headers: &mut Headers,
return None;
}
pub fn set_request_cookies(url: &Url, headers: &mut Headers, cookie_jar: &Arc<RwLock<CookieStorage>>) {
pub fn set_request_cookies(url: &ServoUrl, headers: &mut Headers, cookie_jar: &Arc<RwLock<CookieStorage>>) {
let mut cookie_jar = cookie_jar.write().unwrap();
if let Some(cookie_list) = cookie_jar.cookies_for_url(url, CookieSource::HTTP) {
let mut v = Vec::new();
@ -502,7 +508,7 @@ pub fn set_request_cookies(url: &Url, headers: &mut Headers, cookie_jar: &Arc<Rw
}
fn set_cookie_for_url(cookie_jar: &Arc<RwLock<CookieStorage>>,
request: &Url,
request: &ServoUrl,
cookie_val: String) {
let mut cookie_jar = cookie_jar.write().unwrap();
let source = CookieSource::HTTP;
@ -517,7 +523,7 @@ fn set_cookie_for_url(cookie_jar: &Arc<RwLock<CookieStorage>>,
}
}
pub fn set_cookies_from_headers(url: &Url, headers: &Headers, cookie_jar: &Arc<RwLock<CookieStorage>>) {
pub fn set_cookies_from_headers(url: &ServoUrl, headers: &Headers, cookie_jar: &Arc<RwLock<CookieStorage>>) {
if let Some(cookies) = headers.get_raw("set-cookie") {
for cookie in cookies.iter() {
if let Ok(cookie_value) = String::from_utf8(cookie.clone()) {
@ -529,7 +535,7 @@ pub fn set_cookies_from_headers(url: &Url, headers: &Headers, cookie_jar: &Arc<R
}
}
fn update_sts_list_from_response(url: &Url, response: &HttpResponse, hsts_list: &Arc<RwLock<HstsList>>) {
fn update_sts_list_from_response(url: &ServoUrl, response: &HttpResponse, hsts_list: &Arc<RwLock<HstsList>>) {
if url.scheme() != "https" {
return;
}
@ -613,7 +619,7 @@ enum Decoder {
}
fn prepare_devtools_request(request_id: String,
url: Url,
url: ServoUrl,
method: Method,
headers: Headers,
body: Option<Vec<u8>>,
@ -656,7 +662,7 @@ pub fn send_response_to_devtools(devtools_chan: &Sender<DevtoolsControlMsg>,
let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg));
}
fn request_must_be_secured(url: &Url, hsts_list: &Arc<RwLock<HstsList>>) -> bool {
fn request_must_be_secured(url: &ServoUrl, hsts_list: &Arc<RwLock<HstsList>>) -> bool {
match url.domain() {
Some(domain) => hsts_list.read().unwrap().is_host_secure(domain),
None => false
@ -664,10 +670,10 @@ fn request_must_be_secured(url: &Url, hsts_list: &Arc<RwLock<HstsList>>) -> bool
}
pub fn modify_request_headers(headers: &mut Headers,
url: &Url,
url: &ServoUrl,
user_agent: &str,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: &mut Option<Url>) {
referrer_url: &mut Option<ServoUrl>) {
// Ensure that the host header is set from the original url
let host = Host {
hostname: url.host_str().unwrap().to_owned(),
@ -700,7 +706,7 @@ pub fn modify_request_headers(headers: &mut Headers,
}
fn set_auth_header(headers: &mut Headers,
url: &Url,
url: &ServoUrl,
auth_cache: &Arc<RwLock<AuthCache>>) {
if !headers.has::<Authorization<Basic>>() {
if let Some(auth) = auth_from_url(url) {
@ -723,7 +729,7 @@ pub fn auth_from_cache(auth_cache: &Arc<RwLock<AuthCache>>, origin: &Origin) ->
}
}
fn auth_from_url(doc_url: &Url) -> Option<Authorization<Basic>> {
fn auth_from_url(doc_url: &ServoUrl) -> Option<Authorization<Basic>> {
let username = doc_url.username();
if username != "" {
Some(Authorization(Basic {
@ -736,7 +742,7 @@ fn auth_from_url(doc_url: &Url) -> Option<Authorization<Basic>> {
}
pub fn process_response_headers(response: &HttpResponse,
url: &Url,
url: &ServoUrl,
cookie_jar: &Arc<RwLock<CookieStorage>>,
hsts_list: &Arc<RwLock<HstsList>>,
load_data: &LoadData) {
@ -755,7 +761,7 @@ pub fn process_response_headers(response: &HttpResponse,
}
pub fn obtain_response<A>(request_factory: &HttpRequestFactory<R=A>,
url: &Url,
url: &ServoUrl,
method: &Method,
request_headers: &Headers,
cancel_listener: &CancellationListener,
@ -925,7 +931,7 @@ pub fn load<A, B>(load_data: &LoadData,
// the source rather than rendering the contents of the URL.
let viewing_source = doc_url.scheme() == "view-source";
if viewing_source {
doc_url = Url::parse(&load_data.url[Position::BeforeUsername..]).unwrap();
doc_url = ServoUrl::parse(&load_data.url.as_url().unwrap()[Position::BeforeUsername..]).unwrap();
}
// Loop to handle redirects.
@ -934,7 +940,7 @@ pub fn load<A, B>(load_data: &LoadData,
if doc_url.scheme() == "http" && request_must_be_secured(&doc_url, &http_state.hsts_list) {
info!("{} is in the strict transport security list, requesting secure host", doc_url);
doc_url = secure_url(&doc_url);
doc_url = ServoUrl::from_url(secure_url(&doc_url.as_url().unwrap()));
}
if iters > 20 {
@ -958,7 +964,7 @@ pub fn load<A, B>(load_data: &LoadData,
.unwrap_or(false);
let load_type = if same_origin { LoadType::FirstParty } else { LoadType::ThirdParty };
let actions = process_rules_for_request(rules, &CBRequest {
url: &doc_url,
url: doc_url.as_url().unwrap(),
resource_type: to_resource_type(&load_data.context),
load_type: load_type,
});

View file

@ -11,6 +11,7 @@ use net_traits::image_cache_thread::{ImageCacheChan, ImageCacheCommand, ImageCac
use net_traits::image_cache_thread::{ImageCacheResult, ImageOrMetadataAvailable, ImageResponse, UsePlaceholder};
use net_traits::image_cache_thread::ImageResponder;
use net_traits::request::{Destination, RequestInit, Type as RequestType};
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
@ -20,7 +21,6 @@ use std::mem;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};
use threadpool::ThreadPool;
use url::Url;
use util::resource_files::resources_dir_path;
use util::thread::spawn_named;
use webrender_traits;
@ -49,7 +49,7 @@ struct PendingLoad {
// The url being loaded. Do not forget that this may be several Mb
// if we are loading a data: url.
url: Arc<Url>
url: ServoUrl,
}
enum LoadResult {
@ -59,7 +59,7 @@ enum LoadResult {
}
impl PendingLoad {
fn new(url: Arc<Url>) -> PendingLoad {
fn new(url: ServoUrl) -> PendingLoad {
PendingLoad {
bytes: vec!(),
metadata: None,
@ -83,7 +83,7 @@ struct AllPendingLoads {
// Get a load key from its url. Used ony when starting and
// finishing a load or when adding a new listener.
url_to_load_key: HashMap<Arc<Url>, LoadKey>,
url_to_load_key: HashMap<ServoUrl, LoadKey>,
// A counter used to generate instances of LoadKey
keygen: LoadKeyGenerator,
@ -118,7 +118,7 @@ impl AllPendingLoads {
}
// get a PendingLoad from its url. When possible, prefer `get_by_key_mut`.
fn get_by_url(&self, url: &Url) -> Option<&PendingLoad> {
fn get_by_url(&self, url: &ServoUrl) -> Option<&PendingLoad> {
self.url_to_load_key.get(url).
and_then(|load_key|
self.loads.get(load_key)
@ -133,7 +133,7 @@ impl AllPendingLoads {
})
}
fn get_cached(&mut self, url: Arc<Url>) -> (CacheResult, LoadKey, &mut PendingLoad) {
fn get_cached(&mut self, url: ServoUrl) -> (CacheResult, LoadKey, &mut PendingLoad) {
match self.url_to_load_key.entry(url.clone()) {
Occupied(url_entry) => {
let load_key = url_entry.get();
@ -255,7 +255,7 @@ struct ImageCache {
pending_loads: AllPendingLoads,
// Images that have finished loading (successful or not)
completed_loads: HashMap<Arc<Url>, CompletedLoad>,
completed_loads: HashMap<ServoUrl, CompletedLoad>,
// The placeholder image used when an image fails to load
placeholder_image: Option<Arc<Image>>,
@ -498,7 +498,7 @@ impl ImageCache {
};
let completed_load = CompletedLoad::new(image_response.clone());
self.completed_loads.insert(pending_load.url, completed_load);
self.completed_loads.insert(pending_load.url.into(), completed_load);
for listener in pending_load.listeners {
listener.notify(image_response.clone());
@ -511,23 +511,21 @@ impl ImageCache {
// that image metadata is available, possibly before the image has finished
// loading.
fn request_image(&mut self,
url: Url,
url: ServoUrl,
result_chan: ImageCacheChan,
responder: Option<ImageResponder>,
send_metadata_msg: bool) {
let image_listener = ImageListener::new(result_chan, responder, send_metadata_msg);
// Let's avoid copying url everywhere.
let ref_url = Arc::new(url);
// Check if already completed
match self.completed_loads.get(&ref_url) {
match self.completed_loads.get(&url) {
Some(completed_load) => {
// It's already completed, return a notify straight away
image_listener.notify(completed_load.image_response.clone());
}
None => {
// Check if the load is already pending
let (cache_result, load_key, mut pending_load) = self.pending_loads.get_cached(ref_url.clone());
let (cache_result, load_key, mut pending_load) = self.pending_loads.get_cached(url.clone());
pending_load.add_listener(image_listener);
match cache_result {
CacheResult::Miss => {
@ -535,11 +533,13 @@ impl ImageCache {
// the resource thread.
// https://html.spec.whatwg.org/multipage/#update-the-image-data
// step 12.
//
// TODO(emilio): ServoUrl in more places please!
let request = RequestInit {
url: (*ref_url).clone(),
url: url.clone(),
type_: RequestType::Image,
destination: Destination::Image,
origin: (*ref_url).clone(),
origin: url.clone(),
.. RequestInit::default()
};
@ -578,7 +578,7 @@ impl ImageCache {
}
fn get_image_if_available(&mut self,
url: Url,
url: ServoUrl,
placeholder: UsePlaceholder, )
-> Result<Arc<Image>, ImageState> {
let img_or_metadata = self.get_image_or_meta_if_available(url, placeholder);
@ -590,7 +590,7 @@ impl ImageCache {
}
fn get_image_or_meta_if_available(&mut self,
url: Url,
url: ServoUrl,
placeholder: UsePlaceholder)
-> Result<ImageOrMetadataAvailable, ImageState> {
match self.completed_loads.get(&url) {
@ -624,9 +624,9 @@ impl ImageCache {
}
fn store_decode_image(&mut self,
ref_url: Url,
ref_url: ServoUrl,
loaded_bytes: Vec<u8>) {
let (cache_result, load_key, _) = self.pending_loads.get_cached(Arc::new(ref_url));
let (cache_result, load_key, _) = self.pending_loads.get_cached(ref_url.clone());
assert!(cache_result == CacheResult::Miss);
let action = ResponseAction::DataAvailable(loaded_bytes);
let _ = self.progress_sender.send(ResourceLoadInfo {

View file

@ -36,6 +36,7 @@ extern crate profile_traits;
extern crate rustc_serialize;
#[macro_use]
extern crate serde_derive;
extern crate servo_url;
extern crate threadpool;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]

View file

@ -35,6 +35,7 @@ use net_traits::storage_thread::StorageThreadMsg;
use profile_traits::time::ProfilerChan;
use rustc_serialize::{Decodable, Encodable};
use rustc_serialize::json;
use servo_url::ServoUrl;
use std::borrow::{Cow, ToOwned};
use std::boxed::FnBox;
use std::cell::Cell;
@ -48,7 +49,6 @@ use std::rc::Rc;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::{Receiver, Sender, channel};
use storage_thread::StorageThreadFactory;
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
use websocket_loader;
@ -76,7 +76,7 @@ impl ProgressSender {
}
}
pub fn send_error(url: Url, err: NetworkError, start_chan: LoadConsumer) {
pub fn send_error(url: ServoUrl, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
@ -477,7 +477,7 @@ impl CoreResourceManager {
}
fn set_cookies_for_url(&mut self,
request: Url,
request: ServoUrl,
cookie_list: String,
source: CookieSource,
resource_group: &ResourceGroup) {
@ -492,7 +492,7 @@ impl CoreResourceManager {
}
}
fn set_cookies_for_url_with_data(&mut self, request: Url, cookie: cookie_rs::Cookie, source: CookieSource,
fn set_cookies_for_url_with_data(&mut self, request: ServoUrl, cookie: cookie_rs::Cookie, source: CookieSource,
resource_group: &ResourceGroup) {
if let Some(cookie) = cookie::Cookie::new_wrapped(cookie, &request, source) {
let mut cookie_jar = resource_group.cookie_jar.write().unwrap();

View file

@ -5,11 +5,11 @@
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use net_traits::storage_thread::{StorageThreadMsg, StorageType};
use resource_thread;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::PathBuf;
use url::Url;
use util::thread::spawn_named;
const QUOTA_SIZE_LIMIT: usize = 5 * 1024 * 1024;
@ -105,7 +105,7 @@ impl StorageManager {
}
}
fn length(&self, sender: IpcSender<usize>, url: Url, storage_type: StorageType) {
fn length(&self, sender: IpcSender<usize>, url: ServoUrl, storage_type: StorageType) {
let origin = self.origin_as_string(url);
let data = self.select_data(storage_type);
sender.send(data.get(&origin).map_or(0, |&(_, ref entry)| entry.len())).unwrap();
@ -113,7 +113,7 @@ impl StorageManager {
fn key(&self,
sender: IpcSender<Option<String>>,
url: Url,
url: ServoUrl,
storage_type: StorageType,
index: u32) {
let origin = self.origin_as_string(url);
@ -126,7 +126,7 @@ impl StorageManager {
fn keys(&self,
sender: IpcSender<Vec<String>>,
url: Url,
url: ServoUrl,
storage_type: StorageType) {
let origin = self.origin_as_string(url);
let data = self.select_data(storage_type);
@ -142,7 +142,7 @@ impl StorageManager {
/// exceeding the quota limit
fn set_item(&mut self,
sender: IpcSender<Result<(bool, Option<String>), ()>>,
url: Url,
url: ServoUrl,
storage_type: StorageType,
name: String,
value: String) {
@ -191,7 +191,7 @@ impl StorageManager {
fn request_item(&self,
sender: IpcSender<Option<String>>,
url: Url,
url: ServoUrl,
storage_type: StorageType,
name: String) {
let origin = self.origin_as_string(url);
@ -204,7 +204,7 @@ impl StorageManager {
/// Sends Some(old_value) in case there was a previous value with the key name, otherwise sends None
fn remove_item(&mut self,
sender: IpcSender<Option<String>>,
url: Url,
url: ServoUrl,
storage_type: StorageType,
name: String) {
let origin = self.origin_as_string(url);
@ -218,7 +218,7 @@ impl StorageManager {
sender.send(old_value).unwrap();
}
fn clear(&mut self, sender: IpcSender<bool>, url: Url, storage_type: StorageType) {
fn clear(&mut self, sender: IpcSender<bool>, url: ServoUrl, storage_type: StorageType) {
let origin = self.origin_as_string(url);
let data = self.select_data_mut(storage_type);
sender.send(data.get_mut(&origin)
@ -232,7 +232,7 @@ impl StorageManager {
}})).unwrap();
}
fn origin_as_string(&self, url: Url) -> String {
fn origin_as_string(&self, url: ServoUrl) -> String {
url.origin().ascii_serialization()
}
}

View file

@ -9,13 +9,13 @@ use net_traits::{WebSocketCommunicate, WebSocketConnectData, WebSocketDomAction,
use net_traits::MessageData;
use net_traits::hosts::replace_hosts;
use net_traits::unwrap_websocket_protocol;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::sync::{Arc, Mutex, RwLock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use util::thread::spawn_named;
use websocket::{Client, Message};
use websocket::client::request::Url;
use websocket::header::{Headers, Origin, WebSocketProtocol};
use websocket::message::Type;
use websocket::receiver::Receiver;
@ -27,7 +27,7 @@ use websocket::ws::sender::Sender as Sender_Object;
use websocket::ws::util::url::parse_url;
/// *Establish a WebSocket Connection* as defined in RFC 6455.
fn establish_a_websocket_connection(resource_url: &Url, net_url: (Host, String, bool),
fn establish_a_websocket_connection(resource_url: &ServoUrl, net_url: (Host, String, bool),
origin: String, protocols: Vec<String>,
cookie_jar: Arc<RwLock<CookieStorage>>)
-> WebSocketResult<(Headers, Sender<WebSocketStream>, Receiver<WebSocketStream>)> {
@ -71,7 +71,7 @@ pub fn init(connect: WebSocketCommunicate, connect_data: WebSocketConnectData, c
// URL that we actually fetch from the network, after applying the replacements
// specified in the hosts file.
let net_url_result = parse_url(&replace_hosts(&connect_data.resource_url));
let net_url_result = parse_url(replace_hosts(&connect_data.resource_url).as_url().unwrap());
let net_url = match net_url_result {
Ok(net_url) => net_url,
Err(e) => {

View file

@ -24,6 +24,7 @@ log = "0.3.5"
num-traits = "0.1.32"
serde = "0.8"
serde_derive = "0.8"
servo_url = {path = "../url", features = ["servo"]}
url = {version = "1.2", features = ["heap_size"]}
websocket = "0.17"
uuid = { version = "0.3.1", features = ["v4", "serde"] }

View file

@ -3,6 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use filemanager_thread::FileOrigin;
use servo_url::ServoUrl;
use std::str::FromStr;
use url::Url;
use uuid::Uuid;
@ -34,13 +35,15 @@ pub struct BlobBuf {
/// Parse URL as Blob URL scheme's definition
/// https://w3c.github.io/FileAPI/#DefinitionOfScheme
pub fn parse_blob_url(url: &Url) -> Result<(Uuid, FileOrigin, Option<String>), ()> {
pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin, Option<String>), ()> {
let url_inner = try!(Url::parse(url.path()).map_err(|_| ()));
let fragment = url_inner.fragment().map(|s| s.to_string());
let id = {
let mut segs = try!(url_inner.path_segments().ok_or(()));
let id = try!(segs.nth(0).ok_or(()));
let id = try!(Uuid::from_str(id).map_err(|_| ()));
Ok((id, get_blob_origin(&url_inner), fragment))
try!(Uuid::from_str(id).map_err(|_| ()))
};
Ok((id, get_blob_origin(&ServoUrl::from_url(url_inner)), fragment))
}
/// Given an URL, returning the Origin that a Blob created under this
@ -48,7 +51,7 @@ pub fn parse_blob_url(url: &Url) -> Result<(Uuid, FileOrigin, Option<String>), (
/// HACK(izgzhen): Not well-specified on spec, and it is a bit a hack
/// both due to ambiguity of spec and that we have to serialization the
/// Origin here.
pub fn get_blob_origin(url: &Url) -> FileOrigin {
pub fn get_blob_origin(url: &ServoUrl) -> FileOrigin {
if url.scheme() == "file" {
// NOTE: by default this is "null" (Opaque), which is not ideal
"file://".to_string()

View file

@ -2,12 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufReader, Read};
use std::net::IpAddr;
use url::Url;
lazy_static! {
static ref HOST_TABLE: Option<HashMap<String, IpAddr>> = create_host_table();
@ -52,14 +52,14 @@ pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
host_table
}
pub fn replace_hosts(url: &Url) -> Url {
pub fn replace_hosts(url: &ServoUrl) -> ServoUrl {
HOST_TABLE.as_ref().map_or_else(|| url.clone(), |host_table| {
host_replacement(host_table, url)
})
}
pub fn host_replacement(host_table: &HashMap<String, IpAddr>,
url: &Url) -> Url {
url: &ServoUrl) -> ServoUrl {
url.domain().and_then(|domain| host_table.get(domain).map(|ip| {
let mut new_url = url.clone();
new_url.set_ip_host(*ip).unwrap();

View file

@ -4,8 +4,8 @@
use image::base::{Image, ImageMetadata};
use ipc_channel::ipc::{self, IpcSender};
use servo_url::ServoUrl;
use std::sync::Arc;
use url::Url;
/// This is optionally passed to the image cache when requesting
/// and image, and returned to the specified event loop when the
@ -74,27 +74,27 @@ pub enum ImageCacheCommand {
/// Request an image asynchronously from the cache. Supply a channel
/// to receive the result, and optionally an image responder
/// that is passed to the result channel.
RequestImage(Url, ImageCacheChan, Option<ImageResponder>),
RequestImage(ServoUrl, ImageCacheChan, Option<ImageResponder>),
/// Requests an image and a "metadata-ready" notification message asynchronously from the
/// cache. The cache will make an effort to send metadata before the image is completely
/// loaded. Supply a channel to receive the results, and optionally an image responder
/// that is passed to the result channel.
RequestImageAndMetadata(Url, ImageCacheChan, Option<ImageResponder>),
RequestImageAndMetadata(ServoUrl, ImageCacheChan, Option<ImageResponder>),
/// Synchronously check the state of an image in the cache.
/// TODO(gw): Profile this on some real world sites and see
/// if it's worth caching the results of this locally in each
/// layout / paint thread.
GetImageIfAvailable(Url, UsePlaceholder, IpcSender<Result<Arc<Image>, ImageState>>),
GetImageIfAvailable(ServoUrl, UsePlaceholder, IpcSender<Result<Arc<Image>, ImageState>>),
/// Synchronously check the state of an image in the cache. If the image is in a loading
/// state and but its metadata has been made available, it will be sent as a response.
GetImageOrMetadataIfAvailable(Url, UsePlaceholder, IpcSender<Result<ImageOrMetadataAvailable, ImageState>>),
GetImageOrMetadataIfAvailable(ServoUrl, UsePlaceholder, IpcSender<Result<ImageOrMetadataAvailable, ImageState>>),
/// Instruct the cache to store this data as a newly-complete network request and continue
/// decoding the result into pixel data
StoreDecodeImage(Url, Vec<u8>),
StoreDecodeImage(ServoUrl, Vec<u8>),
/// Clients must wait for a response before shutting down the ResourceThread
Exit(IpcSender<()>),
@ -124,7 +124,7 @@ impl ImageCacheThread {
/// Asynchronously request an image. See ImageCacheCommand::RequestImage.
pub fn request_image(&self,
url: Url,
url: ServoUrl,
result_chan: ImageCacheChan,
responder: Option<ImageResponder>) {
let msg = ImageCacheCommand::RequestImage(url, result_chan, responder);
@ -134,7 +134,7 @@ impl ImageCacheThread {
/// Asynchronously request an image and metadata.
/// See ImageCacheCommand::RequestImageAndMetadata
pub fn request_image_and_metadata(&self,
url: Url,
url: ServoUrl,
result_chan: ImageCacheChan,
responder: Option<ImageResponder>) {
let msg = ImageCacheCommand::RequestImageAndMetadata(url, result_chan, responder);
@ -142,7 +142,7 @@ impl ImageCacheThread {
}
/// Get the current state of an image. See ImageCacheCommand::GetImageIfAvailable.
pub fn find_image(&self, url: Url, use_placeholder: UsePlaceholder)
pub fn find_image(&self, url: ServoUrl, use_placeholder: UsePlaceholder)
-> Result<Arc<Image>, ImageState> {
let (sender, receiver) = ipc::channel().unwrap();
let msg = ImageCacheCommand::GetImageIfAvailable(url, use_placeholder, sender);
@ -152,7 +152,9 @@ impl ImageCacheThread {
/// Get the current state of an image, returning its metadata if available.
/// See ImageCacheCommand::GetImageOrMetadataIfAvailable.
pub fn find_image_or_metadata(&self, url: Url, use_placeholder: UsePlaceholder)
///
/// FIXME: We shouldn't do IPC for data uris!
pub fn find_image_or_metadata(&self, url: ServoUrl, use_placeholder: UsePlaceholder)
-> Result<ImageOrMetadataAvailable, ImageState> {
let (sender, receiver) = ipc::channel().unwrap();
let msg = ImageCacheCommand::GetImageOrMetadataIfAvailable(url, use_placeholder, sender);
@ -162,7 +164,7 @@ impl ImageCacheThread {
/// Decode the given image bytes and cache the result for the given URL.
pub fn store_complete_image_bytes(&self,
url: Url,
url: ServoUrl,
image_data: Vec<u8>) {
let msg = ImageCacheCommand::StoreDecodeImage(url, image_data);
let _ = self.chan.send(msg);

View file

@ -27,6 +27,7 @@ extern crate num_traits;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate servo_url;
extern crate url;
extern crate util;
extern crate uuid;
@ -47,9 +48,9 @@ use ipc_channel::router::ROUTER;
use msg::constellation_msg::PipelineId;
use request::{Request, RequestInit};
use response::{HttpsState, Response};
use servo_url::ServoUrl;
use std::io::Error as IOError;
use storage_thread::StorageThreadMsg;
use url::Url;
use websocket::header;
pub mod blob_url_store;
@ -108,7 +109,7 @@ impl CustomResponse {
#[derive(Clone, Deserialize, Serialize)]
pub struct CustomResponseMediator {
pub response_chan: IpcSender<Option<CustomResponse>>,
pub load_url: Url
pub load_url: ServoUrl,
}
/// [Policies](https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-states)
@ -135,7 +136,7 @@ pub enum ReferrerPolicy {
#[derive(Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct LoadData {
pub url: Url,
pub url: ServoUrl,
#[ignore_heap_size_of = "Defined in hyper"]
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
@ -159,12 +160,12 @@ pub struct LoadData {
pub context: LoadContext,
/// The policy and referring URL for the originator of this request
pub referrer_policy: Option<ReferrerPolicy>,
pub referrer_url: Option<Url>
pub referrer_url: Option<ServoUrl>
}
impl LoadData {
pub fn new(context: LoadContext,
url: Url,
url: ServoUrl,
load_origin: &LoadOrigin) -> LoadData {
LoadData {
url: url,
@ -183,7 +184,7 @@ impl LoadData {
}
pub trait LoadOrigin {
fn referrer_url(&self) -> Option<Url>;
fn referrer_url(&self) -> Option<ServoUrl>;
fn referrer_policy(&self) -> Option<ReferrerPolicy>;
fn pipeline_id(&self) -> Option<PipelineId>;
}
@ -406,7 +407,7 @@ pub struct WebSocketCommunicate {
#[derive(Deserialize, Serialize)]
pub struct WebSocketConnectData {
pub resource_url: Url,
pub resource_url: ServoUrl,
pub origin: String,
pub protocols: Vec<String>,
}
@ -419,19 +420,19 @@ pub enum CoreResourceMsg {
/// Try to make a websocket connection to a URL.
WebsocketConnect(WebSocketCommunicate, WebSocketConnectData),
/// Store a set of cookies for a given originating URL
SetCookiesForUrl(Url, String, CookieSource),
SetCookiesForUrl(ServoUrl, String, CookieSource),
/// Store a set of cookies for a given originating URL
SetCookiesForUrlWithData(
Url,
ServoUrl,
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
Cookie,
CookieSource
),
/// Retrieve the stored cookies for a given URL
GetCookiesForUrl(Url, IpcSender<Option<String>>, CookieSource),
GetCookiesForUrl(ServoUrl, IpcSender<Option<String>>, CookieSource),
/// Get a cookie by name for a given originating URL
GetCookiesDataForUrl(Url, IpcSender<Vec<Serde<Cookie>>>, CookieSource),
GetCookiesDataForUrl(ServoUrl, IpcSender<Vec<Serde<Cookie>>>, CookieSource),
/// Cancel a network request corresponding to a given `ResourceId`
Cancel(ResourceId),
/// Synchronization message solely for knowing the state of the ResourceChannelManager loop
@ -476,14 +477,14 @@ pub struct ResourceCorsData {
/// CORS Preflight flag
pub preflight: bool,
/// Origin of CORS Request
pub origin: Url,
pub origin: ServoUrl,
}
/// Metadata about a loaded resource, such as is obtained from HTTP headers.
#[derive(Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct Metadata {
/// Final URL after redirects.
pub final_url: Url,
pub final_url: ServoUrl,
#[ignore_heap_size_of = "Defined in hyper"]
/// MIME type / subtype.
@ -503,12 +504,12 @@ pub struct Metadata {
pub https_state: HttpsState,
/// Referrer Url
pub referrer: Option<Url>,
pub referrer: Option<ServoUrl>,
}
impl Metadata {
/// Metadata with defaults for everything optional.
pub fn default(url: Url) -> Self {
pub fn default(url: ServoUrl) -> Self {
Metadata {
final_url: url,
content_type: None,
@ -614,7 +615,7 @@ pub enum NetworkError {
Internal(String),
LoadCancelled,
/// SSL validation error that has to be handled in the HTML parser
SslValidation(Url, String),
SslValidation(ServoUrl, String),
}
/// Normalize `slice`, as defined by

View file

@ -6,10 +6,11 @@ use ReferrerPolicy;
use hyper::header::Headers;
use hyper::method::Method;
use msg::constellation_msg::PipelineId;
use servo_url::ServoUrl;
use std::cell::{Cell, RefCell};
use std::default::Default;
use std::mem::swap;
use url::{Origin as UrlOrigin, Url};
use url::{Origin as UrlOrigin};
/// An [initiator](https://fetch.spec.whatwg.org/#concept-request-initiator)
#[derive(Copy, Clone, PartialEq, HeapSizeOf)]
@ -49,7 +50,7 @@ pub enum Referrer {
NoReferrer,
/// Default referrer if nothing is specified
Client,
ReferrerUrl(Url)
ReferrerUrl(ServoUrl)
}
/// A [request mode](https://fetch.spec.whatwg.org/#concept-request-mode)
@ -117,7 +118,7 @@ pub struct RequestInit {
serialize_with = "::hyper_serde::serialize")]
#[ignore_heap_size_of = "Defined in hyper"]
pub method: Method,
pub url: Url,
pub url: ServoUrl,
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
#[ignore_heap_size_of = "Defined in hyper"]
@ -135,9 +136,9 @@ pub struct RequestInit {
pub use_url_credentials: bool,
// this should actually be set by fetch, but fetch
// doesn't have info about the client right now
pub origin: Url,
pub origin: ServoUrl,
// XXXManishearth these should be part of the client object
pub referrer_url: Option<Url>,
pub referrer_url: Option<ServoUrl>,
pub referrer_policy: Option<ReferrerPolicy>,
pub pipeline_id: Option<PipelineId>,
pub redirect_mode: RedirectMode,
@ -147,7 +148,7 @@ impl Default for RequestInit {
fn default() -> RequestInit {
RequestInit {
method: Method::Get,
url: Url::parse("about:blank").unwrap(),
url: ServoUrl::parse("about:blank").unwrap(),
headers: Headers::new(),
unsafe_request: false,
body: None,
@ -159,7 +160,7 @@ impl Default for RequestInit {
use_cors_preflight: false,
credentials_mode: CredentialsMode::Omit,
use_url_credentials: false,
origin: Url::parse("about:blank").unwrap(),
origin: ServoUrl::parse("about:blank").unwrap(),
referrer_url: None,
referrer_policy: None,
pipeline_id: None,
@ -205,14 +206,14 @@ pub struct Request {
pub integrity_metadata: RefCell<String>,
// Use the last method on url_list to act as spec current url field, and
// first method to act as spec url field
pub url_list: RefCell<Vec<Url>>,
pub url_list: RefCell<Vec<ServoUrl>>,
pub redirect_count: Cell<u32>,
pub response_tainting: Cell<ResponseTainting>,
pub done: Cell<bool>,
}
impl Request {
pub fn new(url: Url,
pub fn new(url: ServoUrl,
origin: Option<Origin>,
is_service_worker_global_scope: bool,
pipeline_id: Option<PipelineId>) -> Request {
@ -277,11 +278,11 @@ impl Request {
req
}
pub fn url(&self) -> Url {
pub fn url(&self) -> ServoUrl {
self.url_list.borrow().first().unwrap().clone()
}
pub fn current_url(&self) -> Url {
pub fn current_url(&self) -> ServoUrl {
self.url_list.borrow().last().unwrap().clone()
}
@ -301,20 +302,20 @@ impl Request {
}
impl Referrer {
pub fn to_url(&self) -> Option<&Url> {
pub fn to_url(&self) -> Option<&ServoUrl> {
match *self {
Referrer::NoReferrer | Referrer::Client => None,
Referrer::ReferrerUrl(ref url) => Some(url)
}
}
pub fn from_url(url: Option<Url>) -> Self {
pub fn from_url(url: Option<ServoUrl>) -> Self {
if let Some(url) = url {
Referrer::ReferrerUrl(url)
} else {
Referrer::NoReferrer
}
}
pub fn take(&mut self) -> Option<Url> {
pub fn take(&mut self) -> Option<ServoUrl> {
let mut new = Referrer::Client;
swap(self, &mut new);
match new {

View file

@ -8,10 +8,10 @@ use {FetchMetadata, FilteredMetadata, Metadata, NetworkError};
use hyper::header::{AccessControlExposeHeaders, ContentType, Headers};
use hyper::status::StatusCode;
use hyper_serde::Serde;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::cell::{Cell, RefCell};
use std::sync::{Arc, Mutex};
use url::Url;
/// [Response type](https://fetch.spec.whatwg.org/#concept-response-type)
#[derive(Clone, PartialEq, Debug, Deserialize, Serialize, HeapSizeOf)]
@ -79,8 +79,8 @@ pub enum ResponseMsg {
pub struct Response {
pub response_type: ResponseType,
pub termination_reason: Option<TerminationReason>,
url: Option<Url>,
pub url_list: RefCell<Vec<Url>>,
url: Option<ServoUrl>,
pub url_list: RefCell<Vec<ServoUrl>>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
pub status: Option<StatusCode>,
@ -91,7 +91,7 @@ pub struct Response {
pub body: Arc<Mutex<ResponseBody>>,
pub cache_state: CacheState,
pub https_state: HttpsState,
pub referrer: Option<Url>,
pub referrer: Option<ServoUrl>,
/// [Internal response](https://fetch.spec.whatwg.org/#concept-internal-response), only used if the Response
/// is a filtered response
pub internal_response: Option<Box<Response>>,
@ -100,7 +100,7 @@ pub struct Response {
}
impl Response {
pub fn new(url: Url) -> Response {
pub fn new(url: ServoUrl) -> Response {
Response {
response_type: ResponseType::Default,
termination_reason: None,
@ -136,7 +136,7 @@ impl Response {
}
}
pub fn url(&self) -> Option<&Url> {
pub fn url(&self) -> Option<&ServoUrl> {
self.url.as_ref()
}
@ -242,7 +242,7 @@ impl Response {
}
pub fn metadata(&self) -> Result<FetchMetadata, NetworkError> {
fn init_metadata(response: &Response, url: &Url) -> Metadata {
fn init_metadata(response: &Response, url: &ServoUrl) -> Metadata {
let mut metadata = Metadata::default(url.clone());
metadata.set_content_type(match response.headers.get() {
Some(&ContentType(ref mime)) => Some(mime),

View file

@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ipc_channel::ipc::IpcSender;
use url::Url;
use servo_url::ServoUrl;
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum StorageType {
@ -15,25 +15,25 @@ pub enum StorageType {
#[derive(Deserialize, Serialize)]
pub enum StorageThreadMsg {
/// gets the number of key/value pairs present in the associated storage data
Length(IpcSender<usize>, Url, StorageType),
Length(IpcSender<usize>, ServoUrl, StorageType),
/// gets the name of the key at the specified index in the associated storage data
Key(IpcSender<Option<String>>, Url, StorageType, u32),
Key(IpcSender<Option<String>>, ServoUrl, StorageType, u32),
/// Gets the available keys in the associated storage data
Keys(IpcSender<Vec<String>>, Url, StorageType),
Keys(IpcSender<Vec<String>>, ServoUrl, StorageType),
/// gets the value associated with the given key in the associated storage data
GetItem(IpcSender<Option<String>>, Url, StorageType, String),
GetItem(IpcSender<Option<String>>, ServoUrl, StorageType, String),
/// sets the value of the given key in the associated storage data
SetItem(IpcSender<Result<(bool, Option<String>), ()>>, Url, StorageType, String, String),
SetItem(IpcSender<Result<(bool, Option<String>), ()>>, ServoUrl, StorageType, String, String),
/// removes the key/value pair for the given key in the associated storage data
RemoveItem(IpcSender<Option<String>>, Url, StorageType, String),
RemoveItem(IpcSender<Option<String>>, ServoUrl, StorageType, String),
/// clears the associated storage data by removing all the key/value pairs
Clear(IpcSender<bool>, Url, StorageType),
Clear(IpcSender<bool>, ServoUrl, StorageType),
/// send a reply when done cleaning up thread resources and then shut it down
Exit(IpcSender<()>)

View file

@ -69,6 +69,7 @@ script_traits = {path = "../script_traits"}
selectors = "0.14"
serde = "0.8"
servo_atoms = {path = "../atoms"}
servo_url = {path = "../url", features = ["servo"] }
smallvec = "0.1"
style = {path = "../style"}
style_traits = {path = "../style_traits"}

View file

@ -10,21 +10,21 @@ use dom::document::Document;
use ipc_channel::ipc::IpcSender;
use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend};
use net_traits::request::RequestInit;
use servo_url::ServoUrl;
use std::thread;
use url::Url;
#[derive(JSTraceable, PartialEq, Clone, Debug, HeapSizeOf)]
pub enum LoadType {
Image(Url),
Script(Url),
Subframe(Url),
Stylesheet(Url),
PageSource(Url),
Media(Url),
Image(ServoUrl),
Script(ServoUrl),
Subframe(ServoUrl),
Stylesheet(ServoUrl),
PageSource(ServoUrl),
Media(ServoUrl),
}
impl LoadType {
fn url(&self) -> &Url {
fn url(&self) -> &ServoUrl {
match *self {
LoadType::Image(ref url) |
LoadType::Script(ref url) |
@ -67,7 +67,7 @@ impl LoadBlocker {
}
/// Return the url associated with this load.
pub fn url(&self) -> Option<&Url> {
pub fn url(&self) -> Option<&ServoUrl> {
self.load.as_ref().map(LoadType::url)
}
}
@ -93,7 +93,7 @@ impl DocumentLoader {
}
pub fn new_with_threads(resource_threads: ResourceThreads,
initial_load: Option<Url>) -> DocumentLoader {
initial_load: Option<ServoUrl>) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();

View file

@ -79,6 +79,7 @@ use script_traits::{TimerEventId, TimerSource, TouchpadPressurePhase};
use script_traits::{UntrustedNodeAddress, WindowSizeData, WindowSizeType};
use serde::{Deserialize, Serialize};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use smallvec::SmallVec;
use std::boxed::FnBox;
use std::cell::{Cell, UnsafeCell};
@ -99,7 +100,6 @@ use style::selector_impl::{PseudoElement, Snapshot};
use style::values::specified::Length;
use time::Duration;
use url::Origin as UrlOrigin;
use url::Url;
use uuid::Uuid;
use webrender_traits::{WebGLBufferId, WebGLError, WebGLFramebufferId, WebGLProgramId};
use webrender_traits::{WebGLRenderbufferId, WebGLShaderId, WebGLTextureId};
@ -301,7 +301,7 @@ impl<A: JSTraceable, B: JSTraceable, C: JSTraceable> JSTraceable for (A, B, C) {
}
}
no_jsmanaged_fields!(bool, f32, f64, String, Url, AtomicBool, AtomicUsize, UrlOrigin, Uuid, char);
no_jsmanaged_fields!(bool, f32, f64, String, ServoUrl, AtomicBool, AtomicUsize, UrlOrigin, Uuid, char);
no_jsmanaged_fields!(usize, u8, u16, u32, u64);
no_jsmanaged_fields!(isize, i8, i16, i32, i64);
no_jsmanaged_fields!(Sender<T>);

View file

@ -42,11 +42,11 @@ use net_traits::image::base::PixelFormat;
use net_traits::image_cache_thread::ImageResponse;
use num_traits::ToPrimitive;
use script_traits::ScriptMsg as ConstellationMsg;
use servo_url::ServoUrl;
use std::{cmp, fmt};
use std::cell::Cell;
use std::str::FromStr;
use unpremultiplytable::UNPREMULTIPLY_TABLE;
use url::Url;
#[must_root]
#[derive(JSTraceable, Clone, HeapSizeOf)]
@ -451,7 +451,7 @@ impl CanvasRenderingContext2D {
}
#[inline]
fn request_image_from_cache(&self, url: Url) -> ImageResponse {
fn request_image_from_cache(&self, url: ServoUrl) -> ImageResponse {
let window = window_from_node(&*self.canvas);
canvas_utils::request_image_from_cache(&window, url)
}

View file

@ -10,7 +10,7 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::serviceworker::ServiceWorker;
use dom::window::Window;
use url::Url;
use servo_url::ServoUrl;
use uuid::Uuid;
#[dom_struct]
@ -24,7 +24,7 @@ pub struct Client {
}
impl Client {
fn new_inherited(url: Url) -> Client {
fn new_inherited(url: ServoUrl) -> Client {
Client {
reflector_: Reflector::new(),
active_worker: None,

View file

@ -33,12 +33,12 @@ use rand::random;
use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, StackRootTLS, get_reports, new_rt_and_cx};
use script_runtime::ScriptThreadEventCategory::WorkerEvent;
use script_traits::{TimerEvent, TimerSource, WorkerGlobalScopeInit, WorkerScriptLoadOrigin};
use servo_url::ServoUrl;
use std::mem::replace;
use std::sync::{Arc, Mutex};
use std::sync::atomic::AtomicBool;
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use style::thread_state;
use url::Url;
use util::thread::spawn_named;
/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
@ -92,7 +92,7 @@ pub struct DedicatedWorkerGlobalScope {
impl DedicatedWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
parent_sender: Box<ScriptChan + Send>,
@ -118,7 +118,7 @@ impl DedicatedWorkerGlobalScope {
}
pub fn new(init: WorkerGlobalScopeInit,
worker_url: Url,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
parent_sender: Box<ScriptChan + Send>,
@ -144,7 +144,7 @@ impl DedicatedWorkerGlobalScope {
#[allow(unsafe_code)]
pub fn run_worker_scope(init: WorkerGlobalScopeInit,
worker_url: Url,
worker_url: ServoUrl,
from_devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
worker_rt_for_mainthread: Arc<Mutex<Option<SharedRt>>>,
worker: TrustedWorkerAddress,

View file

@ -108,6 +108,7 @@ use script_traits::{ScriptMsg as ConstellationMsg, TouchpadPressurePhase};
use script_traits::{TouchEventType, TouchId};
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::boxed::FnBox;
@ -126,7 +127,6 @@ use style::selector_impl::Snapshot;
use style::str::{split_html_space_chars, str_join};
use style::stylesheets::Stylesheet;
use time;
use url::Url;
use url::percent_encoding::percent_decode;
use util::prefs::PREFS;
@ -168,7 +168,7 @@ pub struct Document {
last_modified: Option<String>,
encoding: Cell<EncodingRef>,
is_html_document: bool,
url: Url,
url: ServoUrl,
quirks_mode: Cell<QuirksMode>,
/// Caches for the getElement methods
id_map: DOMRefCell<HashMap<Atom, Vec<JS<Element>>>>,
@ -374,12 +374,12 @@ impl Document {
}
// https://dom.spec.whatwg.org/#concept-document-url
pub fn url(&self) -> &Url {
pub fn url(&self) -> &ServoUrl {
&self.url
}
// https://html.spec.whatwg.org/multipage/#fallback-base-url
pub fn fallback_base_url(&self) -> Url {
pub fn fallback_base_url(&self) -> ServoUrl {
// Step 1: iframe srcdoc (#4767).
// Step 2: about:blank with a creator browsing context.
// Step 3.
@ -387,7 +387,7 @@ impl Document {
}
// https://html.spec.whatwg.org/multipage/#document-base-url
pub fn base_url(&self) -> Url {
pub fn base_url(&self) -> ServoUrl {
match self.base_element() {
// Step 1.
None => self.fallback_base_url(),
@ -1738,7 +1738,7 @@ impl LayoutDocumentHelpers for LayoutJS<Document> {
}
/// https://url.spec.whatwg.org/#network-scheme
fn url_has_network_scheme(url: &Url) -> bool {
fn url_has_network_scheme(url: &ServoUrl) -> bool {
match url.scheme() {
"ftp" | "http" | "https" => true,
_ => false,
@ -1748,7 +1748,7 @@ fn url_has_network_scheme(url: &Url) -> bool {
impl Document {
pub fn new_inherited(window: &Window,
browsing_context: Option<&BrowsingContext>,
url: Option<Url>,
url: Option<ServoUrl>,
is_html_document: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<String>,
@ -1757,7 +1757,7 @@ impl Document {
referrer: Option<String>,
referrer_policy: Option<ReferrerPolicy>)
-> Document {
let url = url.unwrap_or_else(|| Url::parse("about:blank").unwrap());
let url = url.unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap());
let (ready_state, domcontentloaded_dispatched) = if source == DocumentSource::FromParser {
(DocumentReadyState::Loading, false)
@ -1868,7 +1868,7 @@ impl Document {
pub fn new(window: &Window,
browsing_context: Option<&BrowsingContext>,
url: Option<Url>,
url: Option<ServoUrl>,
doctype: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<String>,

View file

@ -368,7 +368,7 @@ impl LayoutElementHelpers for LayoutJS<Element> {
PropertyDeclaration::BackgroundImage(DeclaredValue::Value(
background_image::SpecifiedValue(vec![
background_image::single_value::SpecifiedValue(Some(
specified::Image::for_cascade(Some(Arc::new(url)), specified::url::UrlExtraData { })
specified::Image::for_cascade(Some(url.into()), specified::url::UrlExtraData { })
))
])))));
}

View file

@ -31,13 +31,13 @@ use net_traits::request::{RequestInit, RequestMode};
use network_listener::{NetworkListener, PreInvoke};
use script_thread::Runnable;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::mem;
use std::str::{Chars, FromStr};
use std::sync::{Arc, Mutex};
use task_source::TaskSource;
use timers::OneshotTimerCallback;
use url::Url;
header! { (LastEventId, "Last-Event-ID") => [String] }
@ -57,7 +57,7 @@ enum ReadyState {
#[dom_struct]
pub struct EventSource {
eventtarget: EventTarget,
url: Url,
url: ServoUrl,
request: DOMRefCell<Option<RequestInit>>,
last_event_id: DOMRefCell<DOMString>,
reconnection_time: Cell<u64>,
@ -309,7 +309,7 @@ impl PreInvoke for EventSourceContext {
}
impl EventSource {
fn new_inherited(url: Url, with_credentials: bool) -> EventSource {
fn new_inherited(url: ServoUrl, with_credentials: bool) -> EventSource {
EventSource {
eventtarget: EventTarget::new_inherited(),
url: url,
@ -323,7 +323,7 @@ impl EventSource {
}
}
fn new(global: &GlobalScope, url: Url, with_credentials: bool) -> Root<EventSource> {
fn new(global: &GlobalScope, url: ServoUrl, with_credentials: bool) -> Root<EventSource> {
reflect_dom_object(box EventSource::new_inherited(url, with_credentials),
global,
Wrap)

View file

@ -33,6 +33,7 @@ use js::jsapi::{CompileFunction, JS_GetFunctionObject, JSAutoCompartment};
use js::rust::{AutoObjectVectorWrapper, CompileOptionsWrapper};
use libc::{c_char, size_t};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::default::Default;
@ -42,7 +43,6 @@ use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::rc::Rc;
use url::Url;
#[derive(PartialEq, Clone, JSTraceable)]
pub enum CommonEventHandler {
@ -71,7 +71,7 @@ pub enum ListenerPhase {
#[derive(JSTraceable, Clone, PartialEq)]
pub struct InternalRawUncompiledHandler {
source: DOMString,
url: Url,
url: ServoUrl,
line: usize,
}
@ -347,7 +347,7 @@ impl EventTarget {
/// Store the raw uncompiled event handler for on-demand compilation later.
/// https://html.spec.whatwg.org/multipage/#event-handler-attributes:event-handler-content-attributes-3
pub fn set_event_handler_uncompiled(&self,
url: Url,
url: ServoUrl,
line: usize,
ty: &str,
source: DOMString) {

View file

@ -36,6 +36,7 @@ use script_runtime::{ScriptPort, maybe_take_panic_result};
use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread};
use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent};
use script_traits::{TimerEventId, TimerEventRequest, TimerSource};
use servo_url::ServoUrl;
use std::cell::Cell;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
@ -46,7 +47,6 @@ use task_source::networking::NetworkingTaskSource;
use time::{Timespec, get_time};
use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle};
use timers::{OneshotTimers, TimerCallback};
use url::Url;
#[dom_struct]
pub struct GlobalScope {
@ -239,7 +239,7 @@ impl GlobalScope {
/// Get the [base url](https://html.spec.whatwg.org/multipage/#api-base-url)
/// for this global scope.
pub fn api_base_url(&self) -> Url {
pub fn api_base_url(&self) -> ServoUrl {
if let Some(window) = self.downcast::<Window>() {
// https://html.spec.whatwg.org/multipage/#script-settings-for-browsing-contexts:api-base-url
return window.Document().base_url();
@ -252,7 +252,7 @@ impl GlobalScope {
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
pub fn get_url(&self) -> ServoUrl {
if let Some(window) = self.downcast::<Window>() {
return window.get_url();
}

View file

@ -28,16 +28,16 @@ use html5ever_atoms::LocalName;
use net_traits::ReferrerPolicy;
use num_traits::ToPrimitive;
use script_traits::MozBrowserEvent;
use servo_url::ServoUrl;
use std::default::Default;
use style::attr::AttrValue;
use url::Url;
use util::prefs::PREFS;
#[dom_struct]
pub struct HTMLAnchorElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
url: DOMRefCell<Option<Url>>,
url: DOMRefCell<Option<ServoUrl>>,
}
impl HTMLAnchorElement {

View file

@ -14,8 +14,8 @@ use dom::htmlelement::HTMLElement;
use dom::node::{Node, UnbindContext, document_from_node};
use dom::virtualmethods::VirtualMethods;
use html5ever_atoms::LocalName;
use servo_url::ServoUrl;
use style::attr::AttrValue;
use url::Url;
#[dom_struct]
pub struct HTMLBaseElement {
@ -39,7 +39,7 @@ impl HTMLBaseElement {
}
/// https://html.spec.whatwg.org/multipage/#frozen-base-url
pub fn frozen_base_url(&self) -> Url {
pub fn frozen_base_url(&self) -> ServoUrl {
let href = self.upcast::<Element>().get_attribute(&ns!(), &local_name!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");

View file

@ -19,9 +19,9 @@ use dom::node::{Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use html5ever_atoms::LocalName;
use script_traits::ScriptMsg as ConstellationMsg;
use servo_url::ServoUrl;
use style::attr::AttrValue;
use time;
use url::Url;
/// How long we should wait before performing the initial reflow after `<body>` is parsed, in
/// nanoseconds.
@ -85,7 +85,7 @@ impl HTMLBodyElementMethods for HTMLBodyElement {
pub trait HTMLBodyElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_color(&self) -> Option<RGBA>;
fn get_background(&self) -> Option<Url>;
fn get_background(&self) -> Option<ServoUrl>;
}
impl HTMLBodyElementLayoutHelpers for LayoutJS<HTMLBodyElement> {
@ -110,7 +110,7 @@ impl HTMLBodyElementLayoutHelpers for LayoutJS<HTMLBodyElement> {
}
#[allow(unsafe_code)]
fn get_background(&self) -> Option<Url> {
fn get_background(&self) -> Option<ServoUrl> {
unsafe {
(*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("background"))

View file

@ -339,12 +339,12 @@ pub mod utils {
use dom::window::Window;
use ipc_channel::ipc;
use net_traits::image_cache_thread::{ImageCacheChan, ImageResponse};
use url::Url;
use servo_url::ServoUrl;
pub fn request_image_from_cache(window: &Window, url: Url) -> ImageResponse {
pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse {
let image_cache = window.image_cache_thread();
let (response_chan, response_port) = ipc::channel().unwrap();
image_cache.request_image(url, ImageCacheChan(response_chan), None);
image_cache.request_image(url.into(), ImageCacheChan(response_chan), None);
let result = response_port.recv().unwrap();
result.image_response
}

View file

@ -380,10 +380,12 @@ impl HTMLFormElement {
fn mutate_action_url(&self, form_data: &mut Vec<FormDatum>, mut load_data: LoadData, encoding: EncodingRef) {
let charset = &*encoding.whatwg_name().unwrap();
load_data.url.query_pairs_mut().clear()
if let Some(ref mut url) = load_data.url.as_mut_url() {
url.query_pairs_mut().clear()
.encoding_override(Some(self.pick_encoding()))
.extend_pairs(form_data.into_iter()
.map(|field| (field.name.clone(), field.replace_value(charset))));
}
self.plan_to_navigate(load_data);
}
@ -394,16 +396,18 @@ impl HTMLFormElement {
let boundary = generate_boundary();
let bytes = match enctype {
FormEncType::UrlEncoded => {
let mut url = load_data.url.clone();
let charset = &*encoding.whatwg_name().unwrap();
load_data.headers.set(ContentType::form_url_encoded());
if let Some(ref mut url) = load_data.url.as_mut_url() {
url.query_pairs_mut().clear()
.encoding_override(Some(self.pick_encoding()))
.extend_pairs(form_data.into_iter()
.map(|field| (field.name.clone(), field.replace_value(charset))));
}
url.query().unwrap_or("").to_string().into_bytes()
load_data.url.query().unwrap_or("").to_string().into_bytes()
}
FormEncType::FormDataEncoded => {
let mime = mime!(Multipart / FormData; Boundary =(&boundary));

View file

@ -46,10 +46,10 @@ use script_thread::ScriptThread;
use script_traits::{IFrameLoadInfo, LoadData, MozBrowserEvent, ScriptMsg as ConstellationMsg};
use script_traits::IFrameSandboxState::{IFrameSandboxed, IFrameUnsandboxed};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::Cell;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
use style::context::ReflowGoal;
use url::Url;
use util::prefs::PREFS;
use util::servo_version;
@ -84,7 +84,7 @@ impl HTMLIFrameElement {
/// <https://html.spec.whatwg.org/multipage/#otherwise-steps-for-iframe-or-frame-elements>,
/// step 1.
fn get_url(&self) -> Url {
fn get_url(&self) -> ServoUrl {
let element = self.upcast::<Element>();
element.get_attribute(&ns!(), &local_name!("src")).and_then(|src| {
let url = src.value();
@ -93,7 +93,7 @@ impl HTMLIFrameElement {
} else {
document_from_node(self).base_url().join(&url).ok()
}
}).unwrap_or_else(|| Url::parse("about:blank").unwrap())
}).unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap())
}
pub fn generate_new_pipeline_id(&self) -> (Option<PipelineId>, PipelineId) {

View file

@ -27,11 +27,11 @@ use ipc_channel::router::ROUTER;
use net_traits::image::base::{Image, ImageMetadata};
use net_traits::image_cache_thread::{ImageResponder, ImageResponse};
use script_thread::Runnable;
use servo_url::ServoUrl;
use std::i32;
use std::sync::Arc;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
use task_source::TaskSource;
use url::Url;
#[derive(JSTraceable, HeapSizeOf)]
#[allow(dead_code)]
@ -44,7 +44,7 @@ enum State {
#[derive(JSTraceable, HeapSizeOf)]
struct ImageRequest {
state: State,
parsed_url: Option<Url>,
parsed_url: Option<ServoUrl>,
source_url: Option<DOMString>,
#[ignore_heap_size_of = "Arc"]
image: Option<Arc<Image>>,
@ -58,7 +58,7 @@ pub struct HTMLImageElement {
}
impl HTMLImageElement {
pub fn get_url(&self) -> Option<Url> {
pub fn get_url(&self) -> Option<ServoUrl> {
self.current_request.borrow().parsed_url.clone()
}
}
@ -120,7 +120,7 @@ impl Runnable for ImageResponseHandlerRunnable {
impl HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(&self, value: Option<(DOMString, Url)>) {
fn update_image(&self, value: Option<(DOMString, ServoUrl)>) {
let document = document_from_node(self);
let window = document.window();
let image_cache = window.image_cache_thread();
@ -149,7 +149,7 @@ impl HTMLImageElement {
let _ = task_source.queue_with_wrapper(runnable, &wrapper);
});
image_cache.request_image_and_metadata(img_url,
image_cache.request_image_and_metadata(img_url.into(),
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
} else {
@ -241,7 +241,7 @@ pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
unsafe fn image_url(&self) -> Option<ServoUrl>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
fn get_height(&self) -> LengthOrPercentageOrAuto;
@ -254,7 +254,7 @@ impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
unsafe fn image_url(&self) -> Option<ServoUrl> {
(*self.unsafe_get()).current_request.borrow_for_layout().parsed_url.clone()
}

View file

@ -36,6 +36,7 @@ use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as Req
use network_listener::{NetworkListener, PreInvoke};
use script_layout_interface::message::Msg;
use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg};
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
@ -47,7 +48,6 @@ use style::media_queries::{MediaList, parse_media_query_list};
use style::parser::ParserContextExtraData;
use style::str::HTML_SPACE_CHARACTERS;
use style::stylesheets::{Stylesheet, Origin};
use url::Url;
no_jsmanaged_fields!(Stylesheet);
@ -318,7 +318,7 @@ struct StylesheetContext {
/// The response metadata received to date.
metadata: Option<Metadata>,
/// The initial URL requested.
url: Url,
url: ServoUrl,
}
impl PreInvoke for StylesheetContext {}

View file

@ -35,11 +35,11 @@ use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as Req
use network_listener::{NetworkListener, PreInvoke};
use script_thread::{Runnable, ScriptThread};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use task_source::TaskSource;
use time::{self, Timespec, Duration};
use url::Url;
struct HTMLMediaElementContext {
/// The element that initiated the request.
@ -53,7 +53,7 @@ struct HTMLMediaElementContext {
/// Time of last progress notification.
next_progress_event: Timespec,
/// Url of resource requested.
url: Url,
url: ServoUrl,
/// Whether the media metadata has been completely received.
have_metadata: bool,
/// True if this response is invalid and should be ignored.
@ -164,7 +164,7 @@ impl PreInvoke for HTMLMediaElementContext {
}
impl HTMLMediaElementContext {
fn new(elem: &HTMLMediaElement, url: Url) -> HTMLMediaElementContext {
fn new(elem: &HTMLMediaElement, url: ServoUrl) -> HTMLMediaElementContext {
HTMLMediaElementContext {
elem: Trusted::new(elem),
data: vec![],
@ -437,7 +437,7 @@ impl HTMLMediaElement {
}
// https://html.spec.whatwg.org/multipage/#concept-media-load-algorithm
fn resource_selection_algorithm_sync(&self, base_url: Url) {
fn resource_selection_algorithm_sync(&self, base_url: ServoUrl) {
// TODO step 5 (populate pending text tracks)
// Step 6
@ -814,11 +814,11 @@ impl Runnable for FireSimpleEventTask {
struct ResourceSelectionTask {
elem: Trusted<HTMLMediaElement>,
base_url: Url,
base_url: ServoUrl,
}
impl ResourceSelectionTask {
fn new(elem: &HTMLMediaElement, url: Url) -> ResourceSelectionTask {
fn new(elem: &HTMLMediaElement, url: ServoUrl) -> ResourceSelectionTask {
ResourceSelectionTask {
elem: Trusted::new(elem),
base_url: url,
@ -885,5 +885,5 @@ enum ResourceSelectionMode {
enum Resource {
Object,
Url(Url),
Url(ServoUrl),
}

View file

@ -35,11 +35,11 @@ use net_traits::{FetchMetadata, FetchResponseListener, Metadata, NetworkError};
use net_traits::request::{CorsSettings, CredentialsMode, Destination, RequestInit, RequestMode, Type as RequestType};
use network_listener::{NetworkListener, PreInvoke};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use style::str::{HTML_SPACE_CHARACTERS, StaticStringVec};
use url::Url;
#[dom_struct]
pub struct HTMLScriptElement {
@ -115,12 +115,12 @@ static SCRIPT_JS_MIMES: StaticStringVec = &[
#[derive(HeapSizeOf, JSTraceable)]
pub struct ScriptOrigin {
text: DOMString,
url: Url,
url: ServoUrl,
external: bool,
}
impl ScriptOrigin {
fn internal(text: DOMString, url: Url) -> ScriptOrigin {
fn internal(text: DOMString, url: ServoUrl) -> ScriptOrigin {
ScriptOrigin {
text: text,
url: url,
@ -128,7 +128,7 @@ impl ScriptOrigin {
}
}
fn external(text: DOMString, url: Url) -> ScriptOrigin {
fn external(text: DOMString, url: ServoUrl) -> ScriptOrigin {
ScriptOrigin {
text: text,
url: url,
@ -149,7 +149,7 @@ struct ScriptContext {
/// The response metadata received to date.
metadata: Option<Metadata>,
/// The initial URL requested.
url: Url,
url: ServoUrl,
/// Indicates whether the request failed, and why
status: Result<(), NetworkError>
}
@ -219,7 +219,7 @@ impl PreInvoke for ScriptContext {}
/// https://html.spec.whatwg.org/multipage/#fetch-a-classic-script
fn fetch_a_classic_script(script: &HTMLScriptElement,
url: Url,
url: ServoUrl,
cors_setting: Option<CorsSettings>,
character_encoding: EncodingRef) {
let doc = document_from_node(script);

View file

@ -10,7 +10,7 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::urlhelper::UrlHelper;
use dom::window::Window;
use url::Url;
use servo_url::ServoUrl;
#[dom_struct]
pub struct Location {
@ -32,12 +32,12 @@ impl Location {
LocationBinding::Wrap)
}
fn get_url(&self) -> Url {
fn get_url(&self) -> ServoUrl {
self.window.get_url()
}
fn set_url_component(&self, value: USVString,
setter: fn(&mut Url, USVString)) {
setter: fn(&mut ServoUrl, USVString)) {
let mut url = self.window.get_url();
setter(&mut url, value);
self.window.load_url(url, false, None);

View file

@ -73,6 +73,7 @@ use script_traits::UntrustedNodeAddress;
use selectors::matching::{MatchingReason, matches};
use selectors::parser::Selector;
use selectors::parser::parse_author_origin_selector_list_from_str;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::cell::{Cell, UnsafeCell};
use std::cmp::max;
@ -85,7 +86,6 @@ use style::dom::OpaqueNode;
use style::selector_impl::ServoSelectorImpl;
use style::stylesheets::Stylesheet;
use style::thread_state;
use url::Url;
use uuid::Uuid;
//
@ -991,7 +991,7 @@ pub trait LayoutNodeHelpers {
fn text_content(&self) -> String;
fn selection(&self) -> Option<Range<usize>>;
fn image_url(&self) -> Option<Url>;
fn image_url(&self) -> Option<ServoUrl>;
fn canvas_data(&self) -> Option<HTMLCanvasData>;
fn svg_data(&self) -> Option<SVGSVGData>;
fn iframe_pipeline_id(&self) -> PipelineId;
@ -1126,7 +1126,7 @@ impl LayoutNodeHelpers for LayoutJS<Node> {
}
#[allow(unsafe_code)]
fn image_url(&self) -> Option<Url> {
fn image_url(&self) -> Option<ServoUrl> {
unsafe {
self.downcast::<HTMLImageElement>()
.expect("not an image!")

View file

@ -35,10 +35,10 @@ use net_traits::request::Referrer as NetTraitsRequestReferrer;
use net_traits::request::Request as NetTraitsRequest;
use net_traits::request::RequestMode as NetTraitsRequestMode;
use net_traits::request::Type as NetTraitsRequestType;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::cell::{Cell, Ref};
use std::rc::Rc;
use url::Url;
#[dom_struct]
pub struct Request {
@ -53,7 +53,7 @@ pub struct Request {
impl Request {
fn new_inherited(global: &GlobalScope,
url: Url,
url: ServoUrl,
is_service_worker_global_scope: bool) -> Request {
Request {
reflector_: Reflector::new(),
@ -69,7 +69,7 @@ impl Request {
}
pub fn new(global: &GlobalScope,
url: Url,
url: ServoUrl,
is_service_worker_global_scope: bool) -> Root<Request> {
reflect_dom_object(box Request::new_inherited(global,
url,
@ -468,7 +468,7 @@ impl Request {
}
fn net_request_from_global(global: &GlobalScope,
url: Url,
url: ServoUrl,
is_service_worker_global_scope: bool) -> NetTraitsRequest {
let origin = Origin::Origin(global.get_url().origin());
let pipeline_id = global.pipeline_id();
@ -524,7 +524,7 @@ fn is_cors_safelisted_method(m: &HttpMethod) -> bool {
}
// https://url.spec.whatwg.org/#include-credentials
fn includes_credentials(input: &Url) -> bool {
fn includes_credentials(input: &ServoUrl) -> bool {
!input.username().is_empty() || input.password().is_some()
}

View file

@ -22,12 +22,12 @@ use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
use url::Url;
#[dom_struct]
pub struct Response {
@ -40,8 +40,8 @@ pub struct Response {
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<Url>>,
url_list: DOMRefCell<Vec<Url>>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
@ -156,7 +156,7 @@ impl Response {
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("Url could not be parsed".to_string())),
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
@ -357,8 +357,8 @@ impl ResponseMethods for Response {
}
}
fn serialize_without_fragment(url: &Url) -> &str {
&url[..Position::AfterQuery]
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url.as_url().unwrap()[..Position::AfterQuery]
}
impl Response {
@ -377,7 +377,7 @@ impl Response {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: Url) {
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}

View file

@ -18,8 +18,8 @@ use dom::globalscope::GlobalScope;
use js::jsapi::{HandleValue, JSContext};
use script_thread::Runnable;
use script_traits::{ScriptMsg, DOMMessage};
use servo_url::ServoUrl;
use std::cell::Cell;
use url::Url;
pub type TrustedServiceWorkerAddress = Trusted<ServiceWorker>;
@ -27,7 +27,7 @@ pub type TrustedServiceWorkerAddress = Trusted<ServiceWorker>;
pub struct ServiceWorker {
eventtarget: EventTarget,
script_url: DOMRefCell<String>,
scope_url: Url,
scope_url: ServoUrl,
state: Cell<ServiceWorkerState>,
skip_waiting: Cell<bool>
}
@ -35,7 +35,7 @@ pub struct ServiceWorker {
impl ServiceWorker {
fn new_inherited(script_url: &str,
skip_waiting: bool,
scope_url: Url) -> ServiceWorker {
scope_url: ServoUrl) -> ServiceWorker {
ServiceWorker {
eventtarget: EventTarget::new_inherited(),
script_url: DOMRefCell::new(String::from(script_url)),
@ -46,8 +46,8 @@ impl ServiceWorker {
}
pub fn install_serviceworker(global: &GlobalScope,
script_url: Url,
scope_url: Url,
script_url: ServoUrl,
scope_url: ServoUrl,
skip_waiting: bool) -> Root<ServiceWorker> {
reflect_dom_object(box ServiceWorker::new_inherited(script_url.as_str(),
skip_waiting,
@ -64,8 +64,8 @@ impl ServiceWorker {
self.upcast::<EventTarget>().fire_event(atom!("statechange"));
}
pub fn get_script_url(&self) -> Url {
Url::parse(&self.script_url.borrow().clone()).unwrap()
pub fn get_script_url(&self) -> ServoUrl {
ServoUrl::parse(&self.script_url.borrow().clone()).unwrap()
}
}

View file

@ -28,11 +28,11 @@ use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as Req
use rand::random;
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx, ScriptChan};
use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg, WorkerScriptLoadOrigin};
use servo_url::ServoUrl;
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::thread;
use std::time::Duration;
use style::thread_state::{self, IN_WORKER, SCRIPT};
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
@ -80,12 +80,12 @@ pub struct ServiceWorkerGlobalScope {
timer_event_port: Receiver<()>,
#[ignore_heap_size_of = "Defined in std"]
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url,
scope_url: ServoUrl,
}
impl ServiceWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
@ -93,7 +93,7 @@ impl ServiceWorkerGlobalScope {
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
scope_url: ServoUrl)
-> ServiceWorkerGlobalScope {
ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(init,
@ -111,7 +111,7 @@ impl ServiceWorkerGlobalScope {
}
pub fn new(init: WorkerGlobalScopeInit,
worker_url: Url,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
@ -119,7 +119,7 @@ impl ServiceWorkerGlobalScope {
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
scope_url: ServoUrl)
-> Root<ServiceWorkerGlobalScope> {
let cx = runtime.cx();
let scope = box ServiceWorkerGlobalScope::new_inherited(init,
@ -141,7 +141,7 @@ impl ServiceWorkerGlobalScope {
receiver: Receiver<ServiceWorkerScriptMsg>,
devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url) {
scope_url: ServoUrl) {
let ScopeThings { script_url,
init,
worker_load_origin,

View file

@ -13,7 +13,7 @@ use dom::serviceworker::ServiceWorker;
use dom::serviceworkercontainer::Controllable;
use dom::workerglobalscope::prepare_workerscope_init;
use script_traits::{WorkerScriptLoadOrigin, ScopeThings};
use url::Url;
use servo_url::ServoUrl;
#[dom_struct]
pub struct ServiceWorkerRegistration {
@ -25,7 +25,7 @@ pub struct ServiceWorkerRegistration {
}
impl ServiceWorkerRegistration {
fn new_inherited(active_sw: &ServiceWorker, scope: Url) -> ServiceWorkerRegistration {
fn new_inherited(active_sw: &ServiceWorker, scope: ServoUrl) -> ServiceWorkerRegistration {
ServiceWorkerRegistration {
eventtarget: EventTarget::new_inherited(),
active: Some(JS::from_ref(active_sw)),
@ -36,8 +36,8 @@ impl ServiceWorkerRegistration {
}
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope,
script_url: Url,
scope: Url,
script_url: ServoUrl,
scope: ServoUrl,
container: &Controllable) -> Root<ServiceWorkerRegistration> {
let active_worker = ServiceWorker::install_serviceworker(global, script_url.clone(), scope.clone(), true);
active_worker.set_transition_state(ServiceWorkerState::Installed);
@ -49,7 +49,7 @@ impl ServiceWorkerRegistration {
self.active.as_ref().unwrap()
}
pub fn create_scope_things(global: &GlobalScope, script_url: Url) -> ScopeThings {
pub fn create_scope_things(global: &GlobalScope, script_url: ServoUrl) -> ScopeThings {
let worker_load_origin = WorkerScriptLoadOrigin {
referrer_url: None,
referrer_policy: None,
@ -69,7 +69,7 @@ impl ServiceWorkerRegistration {
}
}
pub fn longest_prefix_match(stored_scope: &Url, potential_match: &Url) -> bool {
pub fn longest_prefix_match(stored_scope: &ServoUrl, potential_match: &ServoUrl) -> bool {
if stored_scope.origin() != potential_match.origin() {
return false;
}

View file

@ -31,10 +31,10 @@ use html5ever::tree_builder::{NodeOrText, QuirksMode};
use html5ever::tree_builder::{Tracer as HtmlTracer, TreeBuilder, TreeBuilderOpts, TreeSink};
use html5ever_atoms::QualName;
use js::jsapi::JSTracer;
use servo_url::ServoUrl;
use std::borrow::Cow;
use std::io::{self, Write};
use super::{FragmentContext, Sink};
use url::Url;
#[derive(HeapSizeOf, JSTraceable)]
#[must_root]
@ -48,7 +48,7 @@ pub struct Tokenizer {
impl Tokenizer {
pub fn new(
document: &Document,
url: Url,
url: ServoUrl,
fragment_context: Option<FragmentContext>)
-> Self {
let sink = Sink {

View file

@ -29,9 +29,9 @@ use network_listener::PreInvoke;
use profile_traits::time::{TimerMetadata, TimerMetadataFrameType};
use profile_traits::time::{TimerMetadataReflowType, ProfilerCategory, profile};
use script_thread::ScriptThread;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::collections::VecDeque;
use url::Url;
use util::resource_files::read_resource_file;
mod html;
@ -65,7 +65,7 @@ impl ServoParser {
pub fn parse_html_document(
document: &Document,
input: DOMString,
url: Url,
url: ServoUrl,
owner: Option<PipelineId>) {
let parser = ServoParser::new(
document,
@ -122,7 +122,7 @@ impl ServoParser {
pub fn parse_xml_document(
document: &Document,
input: DOMString,
url: Url,
url: ServoUrl,
owner: Option<PipelineId>) {
let parser = ServoParser::new(
document,
@ -287,7 +287,7 @@ enum Tokenizer {
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
struct Sink {
pub base_url: Url,
pub base_url: ServoUrl,
pub document: JS<Document>,
}
@ -338,11 +338,11 @@ pub struct ParserContext {
/// The pipeline associated with this document.
id: PipelineId,
/// The URL for this document.
url: Url,
url: ServoUrl,
}
impl ParserContext {
pub fn new(id: PipelineId, url: Url) -> ParserContext {
pub fn new(id: PipelineId, url: ServoUrl) -> ParserContext {
ParserContext {
parser: None,
is_synthesized_document: false,

View file

@ -19,9 +19,9 @@ use dom::processinginstruction::ProcessingInstruction;
use dom::text::Text;
use html5ever_atoms::{Prefix, QualName};
use js::jsapi::JSTracer;
use servo_url::ServoUrl;
use std::borrow::Cow;
use super::Sink;
use url::Url;
use xml5ever::tendril::StrTendril;
use xml5ever::tokenizer::{Attribute, QName, XmlTokenizer};
use xml5ever::tree_builder::{NextParserState, NodeOrText};
@ -35,7 +35,7 @@ pub struct Tokenizer {
}
impl Tokenizer {
pub fn new(document: &Document, url: Url) -> Self {
pub fn new(document: &Document, url: ServoUrl) -> Self {
let sink = Sink {
base_url: url,
document: JS::from_ref(document),

View file

@ -18,8 +18,8 @@ use net_traits::IpcSend;
use net_traits::storage_thread::{StorageThreadMsg, StorageType};
use script_thread::{Runnable, ScriptThread};
use script_traits::ScriptMsg;
use servo_url::ServoUrl;
use task_source::TaskSource;
use url::Url;
#[dom_struct]
pub struct Storage {
@ -39,7 +39,7 @@ impl Storage {
reflect_dom_object(box Storage::new_inherited(storage_type), global, StorageBinding::Wrap)
}
fn get_url(&self) -> Url {
fn get_url(&self) -> ServoUrl {
self.global().get_url()
}
@ -158,7 +158,7 @@ impl Storage {
}
/// https://html.spec.whatwg.org/multipage/#send-a-storage-notification
pub fn queue_storage_event(&self, url: Url,
pub fn queue_storage_event(&self, url: ServoUrl,
key: Option<String>, old_value: Option<String>, new_value: Option<String>) {
let global = self.global();
let window = global.as_window();
@ -173,14 +173,14 @@ impl Storage {
pub struct StorageEventRunnable {
element: Trusted<Storage>,
url: Url,
url: ServoUrl,
key: Option<String>,
old_value: Option<String>,
new_value: Option<String>
}
impl StorageEventRunnable {
fn new(storage: Trusted<Storage>, url: Url,
fn new(storage: Trusted<Storage>, url: ServoUrl,
key: Option<String>, old_value: Option<String>, new_value: Option<String>) -> StorageEventRunnable {
StorageEventRunnable { element: storage, url: url, key: key, old_value: old_value, new_value: new_value }
}

View file

@ -17,8 +17,8 @@ use ipc_channel::ipc;
use net_traits::{CoreResourceMsg, IpcSend};
use net_traits::blob_url_store::{get_blob_origin, parse_blob_url};
use net_traits::filemanager_thread::FileManagerThreadMsg;
use servo_url::ServoUrl;
use std::default::Default;
use url::Url;
use uuid::Uuid;
// https://url.spec.whatwg.org/#url
@ -27,14 +27,14 @@ pub struct URL {
reflector_: Reflector,
// https://url.spec.whatwg.org/#concept-url-url
url: DOMRefCell<Url>,
url: DOMRefCell<ServoUrl>,
// https://url.spec.whatwg.org/#dom-url-searchparams
search_params: MutNullableHeap<JS<URLSearchParams>>,
}
impl URL {
fn new_inherited(url: Url) -> URL {
fn new_inherited(url: ServoUrl) -> URL {
URL {
reflector_: Reflector::new(),
url: DOMRefCell::new(url),
@ -42,19 +42,20 @@ impl URL {
}
}
pub fn new(global: &GlobalScope, url: Url) -> Root<URL> {
pub fn new(global: &GlobalScope, url: ServoUrl) -> Root<URL> {
reflect_dom_object(box URL::new_inherited(url),
global, URLBinding::Wrap)
}
pub fn query_pairs(&self) -> Vec<(String, String)> {
self.url.borrow().query_pairs().into_owned().collect()
self.url.borrow().as_url().unwrap().query_pairs().into_owned().collect()
}
pub fn set_query_pairs(&self, pairs: &[(String, String)]) {
let mut url = self.url.borrow_mut();
if let Some(ref mut url) = self.url.borrow_mut().as_mut_url() {
url.query_pairs_mut().clear().extend_pairs(pairs);
}
}
}
impl URL {
@ -69,7 +70,7 @@ impl URL {
},
Some(base) =>
// Step 2.1.
match Url::parse(&base.0) {
match ServoUrl::parse(&base.0) {
Ok(base) => Some(base),
Err(error) => {
// Step 2.2.
@ -78,7 +79,7 @@ impl URL {
}
};
// Step 3.
let parsed_url = match Url::options().base_url(parsed_base.as_ref()).parse(&url.0) {
let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) {
Ok(url) => url,
Err(error) => {
// Step 4.
@ -124,7 +125,7 @@ impl URL {
*/
let origin = get_blob_origin(&global.get_url());
if let Ok(url) = Url::parse(&url) {
if let Ok(url) = ServoUrl::parse(&url) {
if let Ok((id, _, _)) = parse_blob_url(&url) {
let resource_threads = global.resource_threads();
let (tx, rx) = ipc::channel().unwrap();
@ -192,7 +193,7 @@ impl URLMethods for URL {
// https://url.spec.whatwg.org/#dom-url-href
fn SetHref(&self, value: USVString) -> ErrorResult {
match Url::parse(&value.0) {
match ServoUrl::parse(&value.0) {
Ok(url) => {
*self.url.borrow_mut() = url;
self.search_params.set(None); // To be re-initialized in the SearchParams getter.
@ -258,7 +259,7 @@ impl URLMethods for URL {
fn SetSearch(&self, value: USVString) {
UrlHelper::SetSearch(&mut self.url.borrow_mut(), value);
if let Some(search_params) = self.search_params.get() {
search_params.set_list(self.url.borrow().query_pairs().into_owned().collect());
search_params.set_list(self.query_pairs());
}
}

View file

@ -3,32 +3,93 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::USVString;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use url::{Url, quirks};
use url::quirks;
#[derive(HeapSizeOf)]
pub struct UrlHelper;
impl UrlHelper {
pub fn SameOrigin(url_a: &Url, url_b: &Url) -> bool { url_a.origin() == url_b.origin() }
pub fn Origin(url: &Url) -> USVString { USVString(quirks::origin(url)) }
pub fn Href(url: &Url) -> USVString { USVString(quirks::href(url).to_owned()) }
pub fn Hash(url: &Url) -> USVString { USVString(quirks::hash(url).to_owned()) }
pub fn Host(url: &Url) -> USVString { USVString(quirks::host(url).to_owned()) }
pub fn Port(url: &Url) -> USVString { USVString(quirks::port(url).to_owned()) }
pub fn Search(url: &Url) -> USVString { USVString(quirks::search(url).to_owned()) }
pub fn Hostname(url: &Url) -> USVString { USVString(quirks::hostname(url).to_owned()) }
pub fn Password(url: &Url) -> USVString { USVString(quirks::password(url).to_owned()) }
pub fn Pathname(url: &Url) -> USVString { USVString(quirks::pathname(url).to_owned()) }
pub fn Protocol(url: &Url) -> USVString { USVString(quirks::protocol(url).to_owned()) }
pub fn Username(url: &Url) -> USVString { USVString(quirks::username(url).to_owned()) }
pub fn SetHash(url: &mut Url, value: USVString) { quirks::set_hash(url, &value.0) }
pub fn SetHost(url: &mut Url, value: USVString) { let _ = quirks::set_host(url, &value.0); }
pub fn SetPort(url: &mut Url, value: USVString) { let _ = quirks::set_port(url, &value.0); }
pub fn SetSearch(url: &mut Url, value: USVString) { quirks::set_search(url, &value.0) }
pub fn SetPathname(url: &mut Url, value: USVString) { quirks::set_pathname(url, &value.0) }
pub fn SetHostname(url: &mut Url, value: USVString) { let _ = quirks::set_hostname(url, &value.0); }
pub fn SetPassword(url: &mut Url, value: USVString) { let _ = quirks::set_password(url, &value.0); }
pub fn SetProtocol(url: &mut Url, value: USVString) { let _ = quirks::set_protocol(url, &value.0); }
pub fn SetUsername(url: &mut Url, value: USVString) { let _ = quirks::set_username(url, &value.0); }
pub fn SameOrigin(url_a: &ServoUrl, url_b: &ServoUrl) -> bool {
url_a.origin() == url_b.origin()
}
pub fn Origin(url: &ServoUrl) -> USVString {
USVString(quirks::origin(url.as_url().unwrap()).to_owned())
}
pub fn Href(url: &ServoUrl) -> USVString {
USVString(quirks::href(url.as_url().unwrap()).to_owned())
}
pub fn Hash(url: &ServoUrl) -> USVString {
USVString(quirks::hash(url.as_url().unwrap()).to_owned())
}
pub fn Host(url: &ServoUrl) -> USVString {
USVString(quirks::host(url.as_url().unwrap()).to_owned())
}
pub fn Port(url: &ServoUrl) -> USVString {
USVString(quirks::port(url.as_url().unwrap()).to_owned())
}
pub fn Search(url: &ServoUrl) -> USVString {
USVString(quirks::search(url.as_url().unwrap()).to_owned())
}
pub fn Hostname(url: &ServoUrl) -> USVString {
USVString(quirks::hostname(url.as_url().unwrap()).to_owned())
}
pub fn Password(url: &ServoUrl) -> USVString {
USVString(quirks::password(url.as_url().unwrap()).to_owned())
}
pub fn Pathname(url: &ServoUrl) -> USVString {
USVString(quirks::pathname(url.as_url().unwrap()).to_owned())
}
pub fn Protocol(url: &ServoUrl) -> USVString {
USVString(quirks::protocol(url.as_url().unwrap()).to_owned())
}
pub fn Username(url: &ServoUrl) -> USVString {
USVString(quirks::username(url.as_url().unwrap()).to_owned())
}
pub fn SetHash(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
quirks::set_hash(url, &value.0)
}
}
pub fn SetHost(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
let _ = quirks::set_host(url, &value.0);
}
}
pub fn SetPort(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
let _ = quirks::set_port(url, &value.0);
}
}
pub fn SetSearch(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
quirks::set_search(url, &value.0)
}
}
pub fn SetPathname(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
quirks::set_pathname(url, &value.0)
}
}
pub fn SetHostname(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
let _ = quirks::set_hostname(url, &value.0);
}
}
pub fn SetPassword(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
let _ = quirks::set_password(url, &value.0);
}
}
pub fn SetProtocol(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
let _ = quirks::set_protocol(url, &value.0);
}
}
pub fn SetUsername(url: &mut ServoUrl, value: USVString) {
if let Some(ref mut url) = url.as_mut_url() {
let _ = quirks::set_username(url, &value.0);
}
}
}

View file

@ -36,6 +36,7 @@ use net_traits::unwrap_websocket_protocol;
use script_runtime::CommonScriptMsg;
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use script_thread::{Runnable, RunnableWrapper};
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
@ -43,7 +44,6 @@ use std::ptr;
use std::thread;
use task_source::TaskSource;
use task_source::networking::NetworkingTaskSource;
use websocket::client::request::Url;
use websocket::header::{Headers, WebSocketProtocol};
use websocket::ws::util::url::parse_url;
@ -171,7 +171,7 @@ pub fn fail_the_websocket_connection(address: Trusted<WebSocket>,
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
@ -182,7 +182,7 @@ pub struct WebSocket {
}
impl WebSocket {
fn new_inherited(url: Url) -> WebSocket {
fn new_inherited(url: ServoUrl) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
@ -195,7 +195,7 @@ impl WebSocket {
}
}
fn new(global: &GlobalScope, url: Url) -> Root<WebSocket> {
fn new(global: &GlobalScope, url: ServoUrl) -> Root<WebSocket> {
reflect_dom_object(box WebSocket::new_inherited(url),
global, WebSocketBinding::Wrap)
}
@ -205,10 +205,10 @@ impl WebSocket {
protocols: Option<StringOrStringSequence>)
-> Fallible<Root<WebSocket>> {
// Step 1.
let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax));
let resource_url = try!(ServoUrl::parse(&url).map_err(|_| Error::Syntax));
// Although we do this replace and parse operation again in the resource thread,
// we try here to be able to immediately throw a syntax error on failure.
let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax));
let _ = try!(parse_url(&replace_hosts(&resource_url).as_url().unwrap()).map_err(|_| Error::Syntax));
// Step 2: Disallow https -> ws connections.
// Step 3: Potentially block access to some ports.

View file

@ -76,6 +76,7 @@ use script_traits::{DocumentState, TimerEvent, TimerEventId};
use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest, WindowSizeData, WindowSizeType};
use script_traits::webdriver_msg::{WebDriverJSError, WebDriverJSResult};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
@ -102,7 +103,6 @@ use time;
use timers::{IsInterval, TimerCallback};
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
use tinyfiledialogs::{self, MessageBoxIcon};
use url::Url;
use util::geometry::{self, max_rect};
use util::opts;
use util::prefs::PREFS;
@ -624,7 +624,7 @@ impl WindowMethods for Window {
// object, not self's.
Some(self.Document().origin().copy())
},
url => match Url::parse(&url) {
url => match ServoUrl::parse(&url) {
Ok(url) => Some(Origin::new(&url)),
Err(_) => return Err(Error::Syntax),
}
@ -860,7 +860,7 @@ impl WindowMethods for Window {
// check-tidy: no specs after this line
fn OpenURLInDefaultBrowser(&self, href: DOMString) -> ErrorResult {
let url = try!(Url::parse(&href).map_err(|e| {
let url = try!(ServoUrl::parse(&href).map_err(|e| {
Error::Type(format!("Couldn't parse URL: {}", e))
}));
match open::that(url.as_str()) {
@ -1322,7 +1322,7 @@ impl Window {
}
/// Commence a new URL load which will either replace this window or scroll to a fragment.
pub fn load_url(&self, url: Url, replace: bool, referrer_policy: Option<ReferrerPolicy>) {
pub fn load_url(&self, url: ServoUrl, replace: bool, referrer_policy: Option<ReferrerPolicy>) {
let doc = self.Document();
let referrer_policy = referrer_policy.or(doc.get_referrer_policy());
@ -1355,7 +1355,7 @@ impl Window {
self.window_size.get()
}
pub fn get_url(&self) -> Url {
pub fn get_url(&self) -> ServoUrl {
(*self.Document().url()).clone()
}

View file

@ -34,6 +34,7 @@ use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromise
use script_thread::{Runnable, RunnableWrapper};
use script_traits::{TimerEvent, TimerEventId};
use script_traits::WorkerGlobalScopeInit;
use servo_url::ServoUrl;
use std::default::Default;
use std::panic;
use std::rc::Rc;
@ -43,7 +44,6 @@ use std::sync::mpsc::Receiver;
use task_source::file_reading::FileReadingTaskSource;
use task_source::networking::NetworkingTaskSource;
use timers::{IsInterval, TimerCallback};
use url::Url;
pub fn prepare_workerscope_init(global: &GlobalScope,
devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>) -> WorkerGlobalScopeInit {
@ -68,7 +68,7 @@ pub struct WorkerGlobalScope {
globalscope: GlobalScope,
worker_id: WorkerId,
worker_url: Url,
worker_url: ServoUrl,
#[ignore_heap_size_of = "Arc"]
closing: Option<Arc<AtomicBool>>,
#[ignore_heap_size_of = "Defined in js"]
@ -91,7 +91,7 @@ pub struct WorkerGlobalScope {
impl WorkerGlobalScope {
pub fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
worker_url: ServoUrl,
runtime: Runtime,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
timer_event_chan: IpcSender<TimerEvent>,
@ -144,7 +144,7 @@ impl WorkerGlobalScope {
}
}
pub fn get_url(&self) -> &Url {
pub fn get_url(&self) -> &ServoUrl {
&self.worker_url
}

View file

@ -9,24 +9,24 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::urlhelper::UrlHelper;
use dom::workerglobalscope::WorkerGlobalScope;
use url::Url;
use servo_url::ServoUrl;
// https://html.spec.whatwg.org/multipage/#worker-locations
#[dom_struct]
pub struct WorkerLocation {
reflector_: Reflector,
url: Url,
url: ServoUrl,
}
impl WorkerLocation {
fn new_inherited(url: Url) -> WorkerLocation {
fn new_inherited(url: ServoUrl) -> WorkerLocation {
WorkerLocation {
reflector_: Reflector::new(),
url: url,
}
}
pub fn new(global: &WorkerGlobalScope, url: Url) -> Root<WorkerLocation> {
pub fn new(global: &WorkerGlobalScope, url: ServoUrl) -> Root<WorkerLocation> {
reflect_dom_object(box WorkerLocation::new_inherited(url),
global,
WorkerLocationBinding::Wrap)

View file

@ -16,7 +16,7 @@ use dom::location::Location;
use dom::node::Node;
use dom::window::Window;
use js::jsapi::{JSContext, JSObject};
use url::Url;
use servo_url::ServoUrl;
// https://dom.spec.whatwg.org/#xmldocument
#[dom_struct]
@ -27,7 +27,7 @@ pub struct XMLDocument {
impl XMLDocument {
fn new_inherited(window: &Window,
browsing_context: Option<&BrowsingContext>,
url: Option<Url>,
url: Option<ServoUrl>,
is_html_document: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<String>,
@ -49,7 +49,7 @@ impl XMLDocument {
pub fn new(window: &Window,
browsing_context: Option<&BrowsingContext>,
url: Option<Url>,
url: Option<ServoUrl>,
doctype: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<String>,

View file

@ -55,6 +55,7 @@ use net_traits::request::{CredentialsMode, Destination, RequestInit, RequestMode
use net_traits::trim_http_whitespace;
use network_listener::{NetworkListener, PreInvoke};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
@ -64,7 +65,7 @@ use std::sync::{Arc, Mutex};
use task_source::networking::NetworkingTaskSource;
use time;
use timers::{OneshotTimerCallback, OneshotTimerHandle};
use url::{Position, Url};
use url::Position;
use util::prefs::PREFS;
#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf)]
@ -137,7 +138,7 @@ pub struct XMLHttpRequest {
// Associated concepts
#[ignore_heap_size_of = "Defined in hyper"]
request_method: DOMRefCell<Method>,
request_url: DOMRefCell<Option<Url>>,
request_url: DOMRefCell<Option<ServoUrl>>,
#[ignore_heap_size_of = "Defined in hyper"]
request_headers: DOMRefCell<Headers>,
request_body_len: Cell<usize>,
@ -149,7 +150,7 @@ pub struct XMLHttpRequest {
fetch_time: Cell<i64>,
generation_id: Cell<GenerationId>,
response_status: Cell<Result<(), ()>>,
referrer_url: Option<Url>,
referrer_url: Option<ServoUrl>,
referrer_policy: Option<ReferrerPolicy>,
}
@ -169,7 +170,7 @@ impl XMLHttpRequest {
timeout: Cell::new(0u32),
with_credentials: Cell::new(false),
upload: JS::from_ref(&*XMLHttpRequestUpload::new(global)),
response_url: DOMRefCell::new(String::from("")),
response_url: DOMRefCell::new(String::new()),
status: Cell::new(0),
status_text: DOMRefCell::new(ByteString::new(vec!())),
response: DOMRefCell::new(ByteString::new(vec!())),
@ -272,7 +273,7 @@ impl XMLHttpRequest {
}
impl LoadOrigin for XMLHttpRequest {
fn referrer_url(&self) -> Option<Url> {
fn referrer_url(&self) -> Option<ServoUrl> {
return self.referrer_url.clone();
}
@ -862,7 +863,8 @@ impl XMLHttpRequest {
}
fn process_headers_available(&self,
gen_id: GenerationId, metadata: Result<FetchMetadata, NetworkError>)
gen_id: GenerationId,
metadata: Result<FetchMetadata, NetworkError>)
-> Result<(), Error> {
let metadata = match metadata {
Ok(meta) => match meta {
@ -878,7 +880,7 @@ impl XMLHttpRequest {
},
};
*self.response_url.borrow_mut() = metadata.final_url[..Position::AfterQuery].to_owned();
*self.response_url.borrow_mut() = metadata.final_url.as_url().unwrap()[..Position::AfterQuery].to_owned();
// XXXManishearth Clear cache entries in case of a network error
self.process_partial_response(XHRProgress::HeadersReceived(

View file

@ -24,10 +24,10 @@ use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch;
use net_traits::request::Request as NetTraitsRequest;
use net_traits::request::RequestInit as NetTraitsRequestInit;
use network_listener::{NetworkListener, PreInvoke};
use servo_url::ServoUrl;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use url::Url;
struct FetchContext {
fetch_promise: Option<TrustedPromise>,
@ -35,7 +35,7 @@ struct FetchContext {
body: Vec<u8>,
}
fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<Url> {
fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> {
let referrer = request.referrer.borrow();
referrer.to_url().map(|url| url.clone())
}

View file

@ -51,6 +51,7 @@ use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayou
use selectors::matching::ElementFlags;
use selectors::parser::{AttrSelector, NamespaceConstraint};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::fmt;
use std::marker::PhantomData;
use std::mem::transmute;
@ -69,7 +70,6 @@ use style::selector_impl::{NonTSPseudoClass, PseudoElement, RestyleDamage, Servo
use style::selector_matching::ApplicableDeclarationBlock;
use style::sink::Push;
use style::str::is_whitespace;
use url::Url;
#[derive(Copy, Clone)]
pub struct ServoLayoutNode<'a> {
@ -895,7 +895,7 @@ impl<'ln> ThreadSafeLayoutNode for ServoThreadSafeLayoutNode<'ln> {
})
}
fn image_url(&self) -> Option<Url> {
fn image_url(&self) -> Option<ServoUrl> {
let this = unsafe { self.get_jsmanaged() };
this.image_url()
}

View file

@ -82,6 +82,7 @@ extern crate script_traits;
extern crate selectors;
extern crate serde;
#[macro_use] extern crate servo_atoms;
extern crate servo_url;
extern crate smallvec;
#[macro_use]
extern crate style;

View file

@ -2,8 +2,9 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use servo_url::ServoUrl;
use std::sync::Arc;
use url::{Host, Url};
use url::Host;
use url::Origin as UrlOrigin;
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
@ -22,7 +23,7 @@ impl Origin {
}
/// Create a new origin for the given URL.
pub fn new(url: &Url) -> Origin {
pub fn new(url: &ServoUrl) -> Origin {
Origin {
inner: Arc::new(url.origin()),
}

View file

@ -90,6 +90,7 @@ use script_traits::{TouchEventType, TouchId, UntrustedNodeAddress, WindowSizeDat
use script_traits::CompositorEvent::{KeyEvent, MouseButtonEvent, MouseMoveEvent, ResizeEvent};
use script_traits::CompositorEvent::{TouchEvent, TouchpadPressureEvent};
use script_traits::webdriver_msg::WebDriverScriptCommand;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::collections::{hash_map, HashMap, HashSet};
@ -110,7 +111,7 @@ use task_source::history_traversal::HistoryTraversalTaskSource;
use task_source::networking::NetworkingTaskSource;
use task_source::user_interaction::{UserInteractionTask, UserInteractionTaskSource};
use time::Tm;
use url::{Position, Url};
use url::Position;
use util::opts;
use util::thread;
use webdriver_handlers;
@ -150,7 +151,7 @@ struct InProgressLoad {
/// Window is visible.
is_visible: bool,
/// The requested URL of the load.
url: Url,
url: ServoUrl,
}
impl InProgressLoad {
@ -160,7 +161,7 @@ impl InProgressLoad {
parent_info: Option<(PipelineId, FrameType)>,
layout_chan: Sender<message::Msg>,
window_size: Option<WindowSizeData>,
url: Url) -> InProgressLoad {
url: ServoUrl) -> InProgressLoad {
InProgressLoad {
pipeline_id: id,
frame_id: frame_id,
@ -397,7 +398,7 @@ pub struct ScriptThread {
/// A list of data pertaining to loads that have not yet received a network response
incomplete_loads: DOMRefCell<Vec<InProgressLoad>>,
/// A map to store service worker registrations for a given origin
registration_map: DOMRefCell<HashMap<Url, JS<ServiceWorkerRegistration>>>,
registration_map: DOMRefCell<HashMap<ServoUrl, JS<ServiceWorkerRegistration>>>,
/// A handle to the image cache thread.
image_cache_thread: ImageCacheThread,
/// A handle to the resource thread. This is an `Arc` to avoid running out of file descriptors if
@ -563,7 +564,7 @@ impl ScriptThread {
}
// stores a service worker registration
pub fn set_registration(scope_url: Url, registration:&ServiceWorkerRegistration, pipeline_id: PipelineId) {
pub fn set_registration(scope_url: ServoUrl, registration:&ServiceWorkerRegistration, pipeline_id: PipelineId) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.handle_serviceworker_registration(scope_url, registration, pipeline_id);
@ -1448,7 +1449,7 @@ impl ScriptThread {
}
fn handle_serviceworker_registration(&self,
scope: Url,
scope: ServoUrl,
registration: &ServiceWorkerRegistration,
pipeline_id: PipelineId) {
{
@ -1580,7 +1581,7 @@ impl ScriptThread {
}
/// Notify a window of a storage event
fn handle_storage_event(&self, pipeline_id: PipelineId, storage_type: StorageType, url: Url,
fn handle_storage_event(&self, pipeline_id: PipelineId, storage_type: StorageType, url: ServoUrl,
key: Option<String>, old_value: Option<String>, new_value: Option<String>) {
let storage = match self.documents.borrow().find_window(pipeline_id) {
None => return warn!("Storage event sent to closed pipeline {}.", pipeline_id),
@ -1752,7 +1753,7 @@ impl ScriptThread {
// Start with the scheme data of the parsed URL;
// append question mark and query component, if any;
// append number sign and fragment component if any.
let encoded = &incomplete.url[Position::BeforePath..];
let encoded = &incomplete.url.as_url().unwrap()[Position::BeforePath..];
// Percent-decode (8.) and UTF-8 decode (9.)
let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
@ -1812,7 +1813,7 @@ impl ScriptThread {
document.get_current_parser().unwrap()
}
fn notify_devtools(&self, title: DOMString, url: Url, ids: (PipelineId, Option<WorkerId>)) {
fn notify_devtools(&self, title: DOMString, url: ServoUrl, ids: (PipelineId, Option<WorkerId>)) {
if let Some(ref chan) = self.devtools_chan {
let page_info = DevtoolsPageInfo {
title: String::from(title),
@ -1994,7 +1995,8 @@ impl ScriptThread {
Some(document) => document,
None => return warn!("Message sent to closed pipeline {}.", parent_pipeline_id),
};
let url = document.url();
let nurl = nurl.as_url().unwrap();
if let Some(url) = document.url().as_url() {
if &url[..Position::AfterQuery] == &nurl[..Position::AfterQuery] &&
load_data.method == Method::Get {
self.check_and_scroll_fragment(fragment, parent_pipeline_id, &document);
@ -2002,6 +2004,7 @@ impl ScriptThread {
}
}
}
}
match frame_id {
Some(frame_id) => {
@ -2068,7 +2071,7 @@ impl ScriptThread {
});
if load_data.url.scheme() == "javascript" {
load_data.url = Url::parse("about:blank").unwrap();
load_data.url = ServoUrl::parse("about:blank").unwrap();
}
let request = RequestInit {

View file

@ -16,9 +16,9 @@ use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use net_traits::{CustomResponseMediator, CoreResourceMsg};
use script_traits::{ServiceWorkerMsg, ScopeThings, SWManagerMsg, SWManagerSenders, DOMMessage};
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender, Receiver, RecvError};
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
@ -29,9 +29,9 @@ enum Message {
pub struct ServiceWorkerManager {
// map of registered service worker descriptors
registered_workers: HashMap<Url, ScopeThings>,
registered_workers: HashMap<ServoUrl, ScopeThings>,
// map of active service worker descriptors
active_workers: HashMap<Url, Sender<ServiceWorkerScriptMsg>>,
active_workers: HashMap<ServoUrl, Sender<ServiceWorkerScriptMsg>>,
// own sender to send messages here
own_sender: IpcSender<ServiceWorkerMsg>,
// receiver to receive messages from constellation
@ -67,7 +67,7 @@ impl ServiceWorkerManager {
});
}
pub fn get_matching_scope(&self, load_url: &Url) -> Option<Url> {
pub fn get_matching_scope(&self, load_url: &ServoUrl) -> Option<ServoUrl> {
for scope in self.registered_workers.keys() {
if longest_prefix_match(&scope, load_url) {
return Some(scope.clone());
@ -76,7 +76,7 @@ impl ServiceWorkerManager {
None
}
pub fn wakeup_serviceworker(&mut self, scope_url: Url) -> Option<Sender<ServiceWorkerScriptMsg>> {
pub fn wakeup_serviceworker(&mut self, scope_url: ServoUrl) -> Option<Sender<ServiceWorkerScriptMsg>> {
let scope_things = self.registered_workers.get(&scope_url);
if let Some(scope_things) = scope_things {
let (sender, receiver) = channel();

View file

@ -36,7 +36,7 @@ use net_traits::IpcSend;
use script_thread::Documents;
use script_traits::webdriver_msg::{WebDriverFrameId, WebDriverJSError, WebDriverJSResult, WebDriverJSValue};
use script_traits::webdriver_msg::WebDriverCookieError;
use url::Url;
use servo_url::ServoUrl;
fn find_node_by_unique_id(documents: &Documents,
pipeline: PipelineId,
@ -361,11 +361,11 @@ pub fn handle_get_css(documents: &Documents,
pub fn handle_get_url(documents: &Documents,
pipeline: PipelineId,
reply: IpcSender<Url>) {
reply: IpcSender<ServoUrl>) {
// TODO: Return an error if the pipeline doesn't exist.
let url = documents.find_document(pipeline)
.map(|document| document.url().clone())
.unwrap_or_else(|| Url::parse("about:blank").expect("infallible"));
.unwrap_or_else(|| ServoUrl::parse("about:blank").expect("infallible"));
reply.send(url).unwrap();
}

View file

@ -30,5 +30,5 @@ range = {path = "../range"}
script_traits = {path = "../script_traits"}
selectors = "0.14"
servo_atoms = {path = "../atoms"}
servo_url = {path = "../url"}
style = {path = "../style"}
url = {version = "1.2", features = ["heap_size"]}

View file

@ -36,8 +36,8 @@ extern crate range;
extern crate script_traits;
extern crate selectors;
#[macro_use] extern crate servo_atoms;
extern crate servo_url;
extern crate style;
extern crate url;
pub mod message;
pub mod reporter;

View file

@ -15,12 +15,12 @@ use rpc::LayoutRPC;
use script_traits::{ConstellationControlMsg, LayoutControlMsg};
use script_traits::{LayoutMsg as ConstellationMsg, StackingContextScrollState, WindowSizeData};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
use style::context::ReflowGoal;
use style::selector_impl::PseudoElement;
use style::stylesheets::Stylesheet;
use url::Url;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
@ -79,7 +79,7 @@ pub enum Msg {
CreateLayoutThread(NewLayoutThreadInfo),
/// Set the final Url.
SetFinalUrl(Url),
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetStackingContextScrollStates(Vec<StackingContextScrollState>),
@ -135,7 +135,7 @@ impl Drop for ScriptReflow {
pub struct NewLayoutThreadInfo {
pub id: PipelineId,
pub url: Url,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,

View file

@ -12,6 +12,7 @@ use gfx_traits::ByteIndex;
use html5ever_atoms::{Namespace, LocalName};
use msg::constellation_msg::PipelineId;
use range::Range;
use servo_url::ServoUrl;
use std::fmt::Debug;
use std::sync::Arc;
use style::atomic_refcell::AtomicRefCell;
@ -22,7 +23,6 @@ use style::dom::{LayoutIterator, NodeInfo, PresentationalHintsSynthetizer, TElem
use style::dom::OpaqueNode;
use style::properties::ServoComputedValues;
use style::selector_impl::{PseudoElement, PseudoElementCascadeType, RestyleDamage, ServoSelectorImpl};
use url::Url;
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum PseudoElementType<T> {
@ -251,9 +251,7 @@ pub trait ThreadSafeLayoutNode: Clone + Copy + GetLayoutData + NodeInfo + Partia
fn selection(&self) -> Option<Range<ByteIndex>>;
/// If this is an image element, returns its URL. If this is not an image element, fails.
///
/// FIXME(pcwalton): Don't copy URLs.
fn image_url(&self) -> Option<Url>;
fn image_url(&self) -> Option<ServoUrl>;
fn canvas_data(&self) -> Option<HTMLCanvasData>;

Some files were not shown because too many files have changed in this diff Show more