From 913c874cb55fd0fdc9e8f3a4c34624cd015fac8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Wed, 16 Nov 2016 11:57:39 +0100 Subject: [PATCH] Urlmageddon: Use refcounted urls more often. --- components/compositing/Cargo.toml | 2 +- components/compositing/compositor.rs | 6 +- components/compositing/compositor_thread.rs | 6 +- components/compositing/lib.rs | 2 +- components/compositing/windowing.rs | 6 +- components/constellation/Cargo.toml | 2 +- components/constellation/constellation.rs | 12 +- components/constellation/lib.rs | 2 +- components/constellation/pipeline.rs | 6 +- components/devtools_traits/Cargo.toml | 2 +- components/devtools_traits/lib.rs | 8 +- components/gfx/Cargo.toml | 2 +- components/gfx/font_cache_thread.rs | 12 +- components/gfx/lib.rs | 6 +- .../gfx/platform/macos/font_template.rs | 6 +- components/layout/Cargo.toml | 2 +- components/layout/construct.rs | 10 +- components/layout/context.rs | 16 +- components/layout/display_list_builder.rs | 8 +- components/layout/fragment.rs | 4 +- components/layout/lib.rs | 2 +- components/layout_thread/Cargo.toml | 3 +- components/layout_thread/lib.rs | 39 ++--- components/layout_traits/Cargo.toml | 2 +- components/layout_traits/lib.rs | 6 +- components/net/Cargo.toml | 1 + components/net/about_loader.rs | 3 +- components/net/blob_loader.rs | 4 +- components/net/chrome_loader.rs | 6 +- components/net/cookie.rs | 6 +- components/net/cookie_storage.rs | 6 +- components/net/data_loader.rs | 11 +- components/net/fetch/cors_cache.rs | 6 +- components/net/fetch/methods.rs | 5 +- components/net/file_loader.rs | 6 +- components/net/http_loader.rs | 74 +++++---- components/net/image_cache_thread.rs | 42 ++--- components/net/lib.rs | 1 + components/net/resource_thread.rs | 8 +- components/net/storage_thread.rs | 18 +-- components/net/websocket_loader.rs | 6 +- components/net_traits/Cargo.toml | 1 + components/net_traits/blob_url_store.rs | 15 +- components/net_traits/hosts.rs | 6 +- components/net_traits/image_cache_thread.rs | 26 +-- components/net_traits/lib.rs | 33 ++-- components/net_traits/request.rs | 29 ++-- components/net_traits/response.rs | 14 +- components/net_traits/storage_thread.rs | 16 +- components/script/Cargo.toml | 1 + components/script/document_loader.rs | 20 +-- components/script/dom/bindings/trace.rs | 4 +- .../script/dom/canvasrenderingcontext2d.rs | 4 +- components/script/dom/client.rs | 4 +- .../script/dom/dedicatedworkerglobalscope.rs | 8 +- components/script/dom/document.rs | 18 +-- components/script/dom/element.rs | 2 +- components/script/dom/eventsource.rs | 8 +- components/script/dom/eventtarget.rs | 6 +- components/script/dom/globalscope.rs | 6 +- components/script/dom/htmlanchorelement.rs | 4 +- components/script/dom/htmlbaseelement.rs | 4 +- components/script/dom/htmlbodyelement.rs | 6 +- components/script/dom/htmlcanvaselement.rs | 6 +- components/script/dom/htmlformelement.rs | 24 +-- components/script/dom/htmliframeelement.rs | 6 +- components/script/dom/htmlimageelement.rs | 14 +- components/script/dom/htmllinkelement.rs | 4 +- components/script/dom/htmlmediaelement.rs | 14 +- components/script/dom/htmlscriptelement.rs | 12 +- components/script/dom/location.rs | 6 +- components/script/dom/node.rs | 6 +- components/script/dom/request.rs | 10 +- components/script/dom/response.rs | 14 +- components/script/dom/serviceworker.rs | 14 +- .../script/dom/serviceworkerglobalscope.rs | 14 +- .../script/dom/serviceworkerregistration.rs | 12 +- components/script/dom/servoparser/html.rs | 4 +- components/script/dom/servoparser/mod.rs | 12 +- components/script/dom/servoparser/xml.rs | 4 +- components/script/dom/storage.rs | 10 +- components/script/dom/url.rs | 25 +-- components/script/dom/urlhelper.rs | 105 +++++++++--- components/script/dom/websocket.rs | 12 +- components/script/dom/window.rs | 10 +- components/script/dom/workerglobalscope.rs | 8 +- components/script/dom/workerlocation.rs | 8 +- components/script/dom/xmldocument.rs | 6 +- components/script/dom/xmlhttprequest.rs | 16 +- components/script/fetch.rs | 4 +- components/script/layout_wrapper.rs | 4 +- components/script/lib.rs | 1 + components/script/origin.rs | 5 +- components/script/script_thread.rs | 33 ++-- components/script/serviceworker_manager.rs | 10 +- components/script/webdriver_handlers.rs | 6 +- components/script_layout_interface/Cargo.toml | 2 +- components/script_layout_interface/lib.rs | 2 +- components/script_layout_interface/message.rs | 6 +- .../script_layout_interface/wrapper_traits.rs | 6 +- components/script_traits/Cargo.toml | 1 + components/script_traits/lib.rs | 16 +- components/script_traits/script_msg.rs | 20 +-- components/script_traits/webdriver_msg.rs | 4 +- components/servo/Cargo.toml | 1 + components/servo/lib.rs | 5 +- components/style/Cargo.toml | 4 +- components/style/attr.rs | 8 +- components/style/font_face.rs | 9 +- components/style/gecko/wrapper.rs | 6 +- components/style/lib.rs | 2 +- components/style/parser.rs | 8 +- .../style/properties/declaration_block.rs | 11 +- .../style/properties/properties.mako.rs | 6 +- components/style/stylesheets.rs | 8 +- components/style/values/specified/image.rs | 5 +- components/style/values/specified/url.rs | 19 +-- components/url/Cargo.toml | 22 +++ components/url/lib.rs | 150 ++++++++++++++++++ components/util/Cargo.toml | 3 +- components/util/lib.rs | 1 + components/util/opts.rs | 15 +- components/webdriver_server/Cargo.toml | 1 + components/webdriver_server/lib.rs | 6 +- ports/cef/Cargo.lock | 41 +++-- ports/cef/Cargo.toml | 4 +- ports/cef/lib.rs | 4 +- ports/cef/window.rs | 10 +- ports/geckolib/Cargo.lock | 14 +- ports/geckolib/Cargo.toml | 2 +- ports/geckolib/glue.rs | 8 +- ports/geckolib/lib.rs | 2 +- ports/glutin/Cargo.toml | 2 +- ports/glutin/lib.rs | 2 +- ports/glutin/window.rs | 8 +- ports/servo/Cargo.lock | 44 +++-- tests/unit/net/Cargo.toml | 1 + tests/unit/net/chrome_loader.rs | 6 +- tests/unit/net/cookie.rs | 10 +- tests/unit/net/cookie_http_state.rs | 6 +- tests/unit/net/data_loader.rs | 4 +- tests/unit/net/fetch.rs | 15 +- tests/unit/net/http_loader.rs | 78 ++++----- tests/unit/net/lib.rs | 7 +- tests/unit/net/resource_thread.rs | 14 +- tests/unit/script/Cargo.toml | 2 +- tests/unit/script/lib.rs | 2 +- tests/unit/script/origin.rs | 20 +-- tests/unit/style/Cargo.toml | 2 +- tests/unit/style/lib.rs | 2 +- tests/unit/style/media_queries.rs | 6 +- tests/unit/style/parsing/border.rs | 12 +- tests/unit/style/parsing/font.rs | 4 +- tests/unit/style/parsing/image.rs | 1 - tests/unit/style/parsing/inherited_text.rs | 1 - tests/unit/style/parsing/mask.rs | 12 +- tests/unit/style/parsing/mod.rs | 4 +- tests/unit/style/stylesheets.rs | 6 +- tests/unit/style/viewport.rs | 6 +- tests/unit/stylo/Cargo.toml | 2 +- tests/unit/stylo/lib.rs | 2 +- 161 files changed, 1044 insertions(+), 718 deletions(-) create mode 100644 components/url/Cargo.toml create mode 100644 components/url/lib.rs diff --git a/components/compositing/Cargo.toml b/components/compositing/Cargo.toml index 27124a4484f7..cd6d0e31f82e 100644 --- a/components/compositing/Cargo.toml +++ b/components/compositing/Cargo.toml @@ -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] diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index be827ff2ecf6..29f51edc0d80 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -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 IOCompositor { } } - 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 IOCompositor { 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 { diff --git a/components/compositing/compositor_thread.rs b/components/compositing/compositor_thread.rs index 0c4490188918..f8f35e995d7f 100644 --- a/components/compositing/compositor_thread.rs +++ b/components/compositing/compositor_thread.rs @@ -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), /// 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), /// tag finished parsing HeadParsed, /// A status message to be displayed by the browser chrome. diff --git a/components/compositing/lib.rs b/components/compositing/lib.rs index ee67e9591578..c5b98a6e679c 100644 --- a/components/compositing/lib.rs +++ b/components/compositing/lib.rs @@ -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; diff --git a/components/compositing/windowing.rs b/components/compositing/windowing.rs index 7ac9c999aa09..d905b53a39fb 100644 --- a/components/compositing/windowing.rs +++ b/components/compositing/windowing.rs @@ -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); /// 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); /// 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); } diff --git a/components/constellation/Cargo.toml b/components/constellation/Cargo.toml index 85785ffff609..53ed1b14ccf9 100644 --- a/components/constellation/Cargo.toml +++ b/components/constellation/Cargo.toml @@ -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] diff --git a/components/constellation/constellation.rs b/components/constellation/constellation.rs index c42bdf42799b..408d4df64634 100644 --- a/components/constellation/constellation.rs +++ b/components/constellation/constellation.rs @@ -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 Constellation } } - 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 Constellation } } - 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, old_value: Option, new_value: Option) { let origin = url.origin(); for pipeline in self.pipelines.values() { @@ -1204,7 +1204,7 @@ impl Constellation 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 Constellation } } - 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 Constellation 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) diff --git a/components/constellation/lib.rs b/components/constellation/lib.rs index dfb384ac58bc..7d455d954b2d 100644 --- a/components/constellation/lib.rs +++ b/components/constellation/lib.rs @@ -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; diff --git a/components/constellation/pipeline.rs b/components/constellation/pipeline.rs index e46baa81067d..0e76b4bcc88b 100644 --- a/components/constellation/pipeline.rs +++ b/components/constellation/pipeline.rs @@ -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, /// 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, pub size: Option>, @@ -264,7 +264,7 @@ impl Pipeline { layout_chan: IpcSender, compositor_proxy: Box, is_private: bool, - url: Url, + url: ServoUrl, size: Option>, visible: bool) -> Pipeline { diff --git a/components/devtools_traits/Cargo.toml b/components/devtools_traits/Cargo.toml index ef37e153e447..55e28ade5513 100644 --- a/components/devtools_traits/Cargo.toml +++ b/components/devtools_traits/Cargo.toml @@ -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"]} diff --git a/components/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index 3155835fefe2..962388360178 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -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>, diff --git a/components/gfx/Cargo.toml b/components/gfx/Cargo.toml index 2a706c4b9c0d..66b87a4177be 100644 --- a/components/gfx/Cargo.toml +++ b/components/gfx/Cargo.toml @@ -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" diff --git a/components/gfx/font_cache_thread.rs b/components/gfx/font_cache_thread.rs index 77a539ea851e..edad5aa56d16 100644 --- a/components/gfx/font_cache_thread.rs +++ b/components/gfx/font_cache_thread.rs @@ -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), GetLastResortFontTemplate(FontTemplateDescriptor, IpcSender), AddWebFont(LowercaseString, EffectiveSources, IpcSender<()>), - AddDownloadedWebFont(LowercaseString, Url, Vec, IpcSender<()>), + AddDownloadedWebFont(LowercaseString, ServoUrl, Vec, 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; diff --git a/components/gfx/lib.rs b/components/gfx/lib.rs index 38c43af3019f..32fd79875ea3 100644 --- a/components/gfx/lib.rs +++ b/components/gfx/lib.rs @@ -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; diff --git a/components/gfx/platform/macos/font_template.rs b/components/gfx/platform/macos/font_template.rs index 955c5b4df2da..a98f60a95b2a 100644 --- a/components/gfx/platform/macos/font_template.rs +++ b/components/gfx/platform/macos/font_template.rs @@ -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(); diff --git a/components/layout/Cargo.toml b/components/layout/Cargo.toml index 59a5ad9f8cdd..49322a340868 100644 --- a/components/layout/Cargo.toml +++ b/components/layout/Cargo.toml @@ -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] diff --git a/components/layout/construct.rs b/components/layout/construct.rs index d9fa67cd756f..26d47f95f052 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -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; + fn object_data(&self) -> Option; } impl ObjectElement for N where N: ThreadSafeLayoutNode { @@ -1691,14 +1691,14 @@ impl ObjectElement for N where N: ThreadSafeLayoutNode { } } - fn object_data(&self) -> Option { + fn object_data(&self) -> Option { 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 } } diff --git a/components/layout/context.rs b/components/layout/context.rs index 98e1ffe4092b..cb5b9efb0ef3 100644 --- a/components/layout/context.rs +++ b/components/layout/context.rs @@ -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, /// A cache of WebRender image info. - pub webrender_image_cache: Arc>>>, } @@ -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> { 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 { // 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 { 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) } diff --git a/components/layout/display_list_builder.rs b/components/layout/display_list_builder.rs index 0b2beedcff9e..500af8009393 100644 --- a/components/layout/display_list_builder.rs +++ b/components/layout/display_list_builder.rs @@ -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, 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, 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 { diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index f947c4f94934..9b4ee750a452 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -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(node: &N, url: Option, + pub fn new(node: &N, url: Option, shared_layout_context: &SharedLayoutContext) -> ImageFragmentInfo { let image_or_metadata = url.and_then(|url| { diff --git a/components/layout/lib.rs b/components/layout/lib.rs index 8fa25f2f0693..c54fd2611777 100644 --- a/components/layout/lib.rs +++ b/components/layout/lib.rs @@ -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; diff --git a/components/layout_thread/Cargo.toml b/components/layout_thread/Cargo.toml index 798abe3eb03f..7bdb3ee8e32f 100644 --- a/components/layout_thread/Cargo.toml +++ b/components/layout_thread/Cargo.toml @@ -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] diff --git a/components/layout_thread/lib.rs b/components/layout_thread/lib.rs index fbb7d2fb724b..4725c73f0168 100644 --- a/components/layout_thread/lib.rs +++ b/components/layout_thread/lib.rs @@ -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>>>, @@ -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, Receiver), pipeline_port: IpcReceiver, @@ -254,18 +255,18 @@ impl LayoutThreadFactory for LayoutThread { { // Ensures layout thread is destroyed before we send shutdown message let sender = chan.0; let layout = LayoutThread::new(id, - url, - is_iframe, - chan.1, - pipeline_port, - constellation_chan, - script_chan, - image_cache_thread, - font_cache_thread, - time_profiler_chan, - mem_profiler_chan.clone(), - webrender_api_sender, - layout_threads); + url, + is_iframe, + chan.1, + pipeline_port, + constellation_chan, + script_chan, + image_cache_thread, + font_cache_thread, + time_profiler_chan, + mem_profiler_chan.clone(), + webrender_api_sender, + layout_threads); let reporter_name = format!("layout-reporter-{}", id); mem_profiler_chan.run_with_memory_reporting(|| { @@ -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, pipeline_port: IpcReceiver, @@ -1500,7 +1501,7 @@ fn get_ua_stylesheets() -> Result { 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, diff --git a/components/layout_traits/Cargo.toml b/components/layout_traits/Cargo.toml index e286a52b9401..7c773e587c05 100644 --- a/components/layout_traits/Cargo.toml +++ b/components/layout_traits/Cargo.toml @@ -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" diff --git a/components/layout_traits/lib.rs b/components/layout_traits/lib.rs index aeeae1bdb26b..a38fbc8e1f4f 100644 --- a/components/layout_traits/lib.rs +++ b/components/layout_traits/lib.rs @@ -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, Receiver), pipeline_port: IpcReceiver, diff --git a/components/net/Cargo.toml b/components/net/Cargo.toml index ff1b99a1ddc3..ca04ba2f3c2e 100644 --- a/components/net/Cargo.toml +++ b/components/net/Cargo.toml @@ -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" diff --git a/components/net/about_loader.rs b/components/net/about_loader.rs index 21641707a50b..b439733bfeae 100644 --- a/components/net/about_loader.rs +++ b/components/net/about_loader.rs @@ -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(()) } diff --git a/components/net/blob_loader.rs b/components/net/blob_loader.rs index 9bd4eec04c90..ee83717b0804 100644 --- a/components/net/blob_loader.rs +++ b/components/net/blob_loader.rs @@ -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 /// https://fetch.spec.whatwg.org/#concept-basic-fetch (partial) // TODO: make async. pub fn load_blob_sync - (url: Url, + (url: ServoUrl, filemanager: FileManager) -> Result<(Headers, Vec), NetworkError> { let (id, origin) = match parse_blob_url(&url) { diff --git a/components/net/chrome_loader.rs b/components/net/chrome_loader.rs index b019141121e8..5e14d130fb17 100644 --- a/components/net/chrome_loader.rs +++ b/components/net/chrome_loader.rs @@ -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 { +pub fn resolve_chrome_url(url: &ServoUrl) -> Result { 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 { } 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(()) } diff --git a/components/net/cookie.rs b/components/net/cookie.rs index 28972d958069..768017ec6f64 100644 --- a/components/net/cookie.rs +++ b/components/net/cookie.rs @@ -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 { // 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 { diff --git a/components/net/cookie_storage.rs b/components/net/cookie_storage.rs index f1ce7ee31901..6b79095176d9 100644 --- a/components/net/cookie_storage.rs +++ b/components/net/cookie_storage.rs @@ -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 { + pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option { 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 + 'a> { Box::new(self.cookies.iter_mut().filter(move |c| { c.appropriate_for_url(url, source) }).map(|c| { c.touch(); diff --git a/components/net/data_loader.rs b/components/net/data_loader.rs index 5380a87f828d..19a6c92f0e2e 100644 --- a/components/net/data_loader.rs +++ b/components/net/data_loader.rs @@ -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); -pub fn decode(url: &Url) -> Result { - assert!(url.scheme() == "data"); +pub fn decode(url: &ServoUrl) -> Result { + 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 { if is_base64 { // FIXME(#2909): It’s 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::>(); + bytes = bytes.into_iter().filter(|&b| b != b' ').collect::>(); match bytes.from_base64() { Err(..) => return Err(DecodeError::NonBase64DataUri), Ok(data) => bytes = data, diff --git a/components/net/fetch/cors_cache.rs b/components/net/fetch/cors_cache.rs index c56e6cc8aa14..4a16f9d9b005 100644 --- a/components/net/fetch/cors_cache.rs +++ b/components/net/fetch/cors_cache.rs @@ -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, diff --git a/components/net/fetch/methods.rs b/components/net/fetch/methods.rs index 5a98f969b819..82bfd0f7c1d6 100644 --- a/components/net/fetch/methods.rs +++ b/components/net/fetch/methods.rs @@ -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, response: &Response) -> Result<(), ()> { Err(()) } -fn has_credentials(url: &Url) -> bool { +fn has_credentials(url: &ServoUrl) -> bool { !url.username().is_empty() || url.password().is_some() } diff --git a/components/net/file_loader.rs b/components/net/file_loader.rs index 7ef53b0ac690..f5737fecd72b 100644 --- a/components/net/file_loader.rs +++ b/components/net/file_loader.rs @@ -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 { + fn referrer_url(&self) -> Option { None } fn referrer_policy(&self) -> Option { @@ -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; diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index 6b05644f2e87..e9b1154d7eb6 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -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; + fn create(&self, url: ServoUrl, method: Method, headers: Headers) -> Result; } 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 { - 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>) -> Result { - 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 { +fn no_referrer_when_downgrade_header(referrer_url: ServoUrl, url: ServoUrl) -> Option { 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 } /// https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin -fn strict_origin(referrer_url: Url, url: Url) -> Option { +fn strict_origin(referrer_url: ServoUrl, url: ServoUrl) -> Option { if referrer_url.scheme() == "https" && url.scheme() != "https" { return None; } @@ -445,7 +448,7 @@ fn strict_origin(referrer_url: Url, url: Url) -> Option { } /// 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 { +fn strict_origin_when_cross_origin(referrer_url: ServoUrl, url: ServoUrl) -> Option { 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 { } /// https://w3c.github.io/webappsec-referrer-policy/#strip-url -fn strip_url(mut referrer_url: Url, origin_only: bool) -> Option { +fn strip_url(mut referrer_url: ServoUrl, origin_only: bool) -> Option { 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); - if origin_only { - referrer_url.set_path(""); - referrer_url.set_query(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.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 { /// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer pub fn determine_request_referrer(headers: &mut Headers, referrer_policy: Option, - referrer_url: Option, - url: Url) -> Option { + referrer_url: Option, + url: ServoUrl) -> Option { //TODO - algorithm step 2 not addressed assert!(!headers.has::()); 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>) { +pub fn set_request_cookies(url: &ServoUrl, headers: &mut Headers, cookie_jar: &Arc>) { 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>, - 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>, } } -pub fn set_cookies_from_headers(url: &Url, headers: &Headers, cookie_jar: &Arc>) { +pub fn set_cookies_from_headers(url: &ServoUrl, headers: &Headers, cookie_jar: &Arc>) { 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>) { +fn update_sts_list_from_response(url: &ServoUrl, response: &HttpResponse, hsts_list: &Arc>) { 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>, @@ -656,7 +662,7 @@ pub fn send_response_to_devtools(devtools_chan: &Sender, let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)); } -fn request_must_be_secured(url: &Url, hsts_list: &Arc>) -> bool { +fn request_must_be_secured(url: &ServoUrl, hsts_list: &Arc>) -> 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>) -> bool } pub fn modify_request_headers(headers: &mut Headers, - url: &Url, + url: &ServoUrl, user_agent: &str, referrer_policy: Option, - referrer_url: &mut Option) { + referrer_url: &mut Option) { // 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>) { if !headers.has::>() { if let Some(auth) = auth_from_url(url) { @@ -723,7 +729,7 @@ pub fn auth_from_cache(auth_cache: &Arc>, origin: &Origin) -> } } -fn auth_from_url(doc_url: &Url) -> Option> { +fn auth_from_url(doc_url: &ServoUrl) -> Option> { let username = doc_url.username(); if username != "" { Some(Authorization(Basic { @@ -736,7 +742,7 @@ fn auth_from_url(doc_url: &Url) -> Option> { } pub fn process_response_headers(response: &HttpResponse, - url: &Url, + url: &ServoUrl, cookie_jar: &Arc>, hsts_list: &Arc>, load_data: &LoadData) { @@ -755,7 +761,7 @@ pub fn process_response_headers(response: &HttpResponse, } pub fn obtain_response(request_factory: &HttpRequestFactory, - url: &Url, + url: &ServoUrl, method: &Method, request_headers: &Headers, cancel_listener: &CancellationListener, @@ -925,7 +931,7 @@ pub fn load(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(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(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, }); diff --git a/components/net/image_cache_thread.rs b/components/net/image_cache_thread.rs index 5929100e2a12..71c70a03b284 100644 --- a/components/net/image_cache_thread.rs +++ b/components/net/image_cache_thread.rs @@ -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: ServoUrl, } enum LoadResult { @@ -59,7 +59,7 @@ enum LoadResult { } impl PendingLoad { - fn new(url: Arc) -> 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, LoadKey>, + url_to_load_key: HashMap, // 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) -> (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, CompletedLoad>, + completed_loads: HashMap, // The placeholder image used when an image fails to load placeholder_image: Option>, @@ -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, 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,9 +578,9 @@ impl ImageCache { } fn get_image_if_available(&mut self, - url: Url, - placeholder: UsePlaceholder, ) - -> Result, ImageState> { + url: ServoUrl, + placeholder: UsePlaceholder, ) + -> Result, ImageState> { let img_or_metadata = self.get_image_or_meta_if_available(url, placeholder); match img_or_metadata { Ok(ImageOrMetadataAvailable::ImageAvailable(image)) => Ok(image), @@ -590,7 +590,7 @@ impl ImageCache { } fn get_image_or_meta_if_available(&mut self, - url: Url, + url: ServoUrl, placeholder: UsePlaceholder) -> Result { 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) { - 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 { diff --git a/components/net/lib.rs b/components/net/lib.rs index 267b4c6d9de4..96d812b030c2 100644 --- a/components/net/lib.rs +++ b/components/net/lib.rs @@ -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"))] diff --git a/components/net/resource_thread.rs b/components/net/resource_thread.rs index 02af5a45bf5f..aaef8b687733 100644 --- a/components/net/resource_thread.rs +++ b/components/net/resource_thread.rs @@ -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(); diff --git a/components/net/storage_thread.rs b/components/net/storage_thread.rs index 0e7c76474209..cdf70aa6b3b4 100644 --- a/components/net/storage_thread.rs +++ b/components/net/storage_thread.rs @@ -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, url: Url, storage_type: StorageType) { + fn length(&self, sender: IpcSender, 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>, - 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>, - 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), ()>>, - url: Url, + url: ServoUrl, storage_type: StorageType, name: String, value: String) { @@ -191,7 +191,7 @@ impl StorageManager { fn request_item(&self, sender: IpcSender>, - 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>, - 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, url: Url, storage_type: StorageType) { + fn clear(&mut self, sender: IpcSender, 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() } } diff --git a/components/net/websocket_loader.rs b/components/net/websocket_loader.rs index 438386eec0ec..c9b67dc7f0f7 100644 --- a/components/net/websocket_loader.rs +++ b/components/net/websocket_loader.rs @@ -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, cookie_jar: Arc>) -> WebSocketResult<(Headers, Sender, Receiver)> { @@ -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) => { diff --git a/components/net_traits/Cargo.toml b/components/net_traits/Cargo.toml index 4808c3e01d82..b474723eba69 100644 --- a/components/net_traits/Cargo.toml +++ b/components/net_traits/Cargo.toml @@ -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"] } diff --git a/components/net_traits/blob_url_store.rs b/components/net_traits/blob_url_store.rs index 1de26f90a2fe..ad01dd28a76b 100644 --- a/components/net_traits/blob_url_store.rs +++ b/components/net_traits/blob_url_store.rs @@ -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), ()> { +pub fn parse_blob_url(url: &ServoUrl) -> Result<(Uuid, FileOrigin, Option), ()> { let url_inner = try!(Url::parse(url.path()).map_err(|_| ())); let fragment = url_inner.fragment().map(|s| s.to_string()); - 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)) + let id = { + let mut segs = try!(url_inner.path_segments().ok_or(())); + let id = try!(segs.nth(0).ok_or(())); + 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), ( /// 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() diff --git a/components/net_traits/hosts.rs b/components/net_traits/hosts.rs index b03bf16100c1..0a42be555725 100644 --- a/components/net_traits/hosts.rs +++ b/components/net_traits/hosts.rs @@ -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> = create_host_table(); @@ -52,14 +52,14 @@ pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap { 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, - 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(); diff --git a/components/net_traits/image_cache_thread.rs b/components/net_traits/image_cache_thread.rs index 713ba52c1791..d816fd628c7e 100644 --- a/components/net_traits/image_cache_thread.rs +++ b/components/net_traits/image_cache_thread.rs @@ -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), + RequestImage(ServoUrl, ImageCacheChan, Option), /// 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), + RequestImageAndMetadata(ServoUrl, ImageCacheChan, Option), /// 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, ImageState>>), + GetImageIfAvailable(ServoUrl, UsePlaceholder, IpcSender, 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>), + GetImageOrMetadataIfAvailable(ServoUrl, UsePlaceholder, IpcSender>), /// Instruct the cache to store this data as a newly-complete network request and continue /// decoding the result into pixel data - StoreDecodeImage(Url, Vec), + StoreDecodeImage(ServoUrl, Vec), /// 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) { 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) { 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, 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 { let (sender, receiver) = ipc::channel().unwrap(); let msg = ImageCacheCommand::GetImageOrMetadataIfAvailable(url, use_placeholder, sender); @@ -162,8 +164,8 @@ impl ImageCacheThread { /// Decode the given image bytes and cache the result for the given URL. pub fn store_complete_image_bytes(&self, - url: Url, - image_data: Vec) { + url: ServoUrl, + image_data: Vec) { let msg = ImageCacheCommand::StoreDecodeImage(url, image_data); let _ = self.chan.send(msg); } diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index 61d8400dadc7..9439102bf0c6 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -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>, - 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, - pub referrer_url: Option + pub referrer_url: Option } 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; + fn referrer_url(&self) -> Option; fn referrer_policy(&self) -> Option; fn pipeline_id(&self) -> Option; } @@ -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, } @@ -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>, CookieSource), + GetCookiesForUrl(ServoUrl, IpcSender>, CookieSource), /// Get a cookie by name for a given originating URL - GetCookiesDataForUrl(Url, IpcSender>>, CookieSource), + GetCookiesDataForUrl(ServoUrl, IpcSender>>, 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, + pub referrer: Option, } 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 diff --git a/components/net_traits/request.rs b/components/net_traits/request.rs index c559b41fd9c3..795a8556f6f5 100644 --- a/components/net_traits/request.rs +++ b/components/net_traits/request.rs @@ -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, + pub referrer_url: Option, pub referrer_policy: Option, pub pipeline_id: Option, 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, // 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>, + pub url_list: RefCell>, pub redirect_count: Cell, pub response_tainting: Cell, pub done: Cell, } impl Request { - pub fn new(url: Url, + pub fn new(url: ServoUrl, origin: Option, is_service_worker_global_scope: bool, pipeline_id: Option) -> 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) -> Self { + pub fn from_url(url: Option) -> Self { if let Some(url) = url { Referrer::ReferrerUrl(url) } else { Referrer::NoReferrer } } - pub fn take(&mut self) -> Option { + pub fn take(&mut self) -> Option { let mut new = Referrer::Client; swap(self, &mut new); match new { diff --git a/components/net_traits/response.rs b/components/net_traits/response.rs index da2c9c825d28..d93798be973a 100644 --- a/components/net_traits/response.rs +++ b/components/net_traits/response.rs @@ -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, - url: Option, - pub url_list: RefCell>, + url: Option, + pub url_list: RefCell>, /// `None` can be considered a StatusCode of `0`. #[ignore_heap_size_of = "Defined in hyper"] pub status: Option, @@ -91,7 +91,7 @@ pub struct Response { pub body: Arc>, pub cache_state: CacheState, pub https_state: HttpsState, - pub referrer: Option, + pub referrer: Option, /// [Internal response](https://fetch.spec.whatwg.org/#concept-internal-response), only used if the Response /// is a filtered response pub internal_response: Option>, @@ -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 { - 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), diff --git a/components/net_traits/storage_thread.rs b/components/net_traits/storage_thread.rs index 1057878d1029..e4fec8729f12 100644 --- a/components/net_traits/storage_thread.rs +++ b/components/net_traits/storage_thread.rs @@ -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, Url, StorageType), + Length(IpcSender, ServoUrl, StorageType), /// gets the name of the key at the specified index in the associated storage data - Key(IpcSender>, Url, StorageType, u32), + Key(IpcSender>, ServoUrl, StorageType, u32), /// Gets the available keys in the associated storage data - Keys(IpcSender>, Url, StorageType), + Keys(IpcSender>, ServoUrl, StorageType), /// gets the value associated with the given key in the associated storage data - GetItem(IpcSender>, Url, StorageType, String), + GetItem(IpcSender>, ServoUrl, StorageType, String), /// sets the value of the given key in the associated storage data - SetItem(IpcSender), ()>>, Url, StorageType, String, String), + SetItem(IpcSender), ()>>, ServoUrl, StorageType, String, String), /// removes the key/value pair for the given key in the associated storage data - RemoveItem(IpcSender>, Url, StorageType, String), + RemoveItem(IpcSender>, ServoUrl, StorageType, String), /// clears the associated storage data by removing all the key/value pairs - Clear(IpcSender, Url, StorageType), + Clear(IpcSender, ServoUrl, StorageType), /// send a reply when done cleaning up thread resources and then shut it down Exit(IpcSender<()>) diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index e096dae13479..e5fc53affe68 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -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"} diff --git a/components/script/document_loader.rs b/components/script/document_loader.rs index 04b9e258573c..30d83019c5fa 100644 --- a/components/script/document_loader.rs +++ b/components/script/document_loader.rs @@ -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) -> DocumentLoader { + initial_load: Option) -> DocumentLoader { debug!("Initial blocking load {:?}.", initial_load); let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect(); diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index b38d5d4ec91e..7b0a14d91e5a 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -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 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); diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 5b36249be59e..390a321fe5e4 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -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) } diff --git a/components/script/dom/client.rs b/components/script/dom/client.rs index 7f51b251627f..bc763d41ea99 100644 --- a/components/script/dom/client.rs +++ b/components/script/dom/client.rs @@ -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, diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 86aac32df1bd..3be8f989cfda 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -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, runtime: Runtime, parent_sender: Box, @@ -118,7 +118,7 @@ impl DedicatedWorkerGlobalScope { } pub fn new(init: WorkerGlobalScopeInit, - worker_url: Url, + worker_url: ServoUrl, from_devtools_receiver: Receiver, runtime: Runtime, parent_sender: Box, @@ -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, worker_rt_for_mainthread: Arc>>, worker: TrustedWorkerAddress, diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 56b7b17b0cac..a3263dbbc675 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -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, encoding: Cell, is_html_document: bool, - url: Url, + url: ServoUrl, quirks_mode: Cell, /// Caches for the getElement methods id_map: DOMRefCell>>>, @@ -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 { } /// 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: Option, is_html_document: IsHTMLDocument, content_type: Option, last_modified: Option, @@ -1757,7 +1757,7 @@ impl Document { referrer: Option, referrer_policy: Option) -> 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: Option, doctype: IsHTMLDocument, content_type: Option, last_modified: Option, diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index ac65c01e24c1..bcad336f57bb 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -368,7 +368,7 @@ impl LayoutElementHelpers for LayoutJS { 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 { }) )) ]))))); } diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index 2eabfcbc8b05..c667267cd832 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -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>, last_event_id: DOMRefCell, reconnection_time: Cell, @@ -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 { + fn new(global: &GlobalScope, url: ServoUrl, with_credentials: bool) -> Root { reflect_dom_object(box EventSource::new_inherited(url, with_credentials), global, Wrap) diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 48ba920ad603..e24e5c0e9330 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -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) { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 2338dcf32e79..0251bd8143eb 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -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::() { // 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::() { return window.get_url(); } diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index 24d86df0cc02..a983c75bf91c 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -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>, - url: DOMRefCell>, + url: DOMRefCell>, } impl HTMLAnchorElement { diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index 9fd34768b365..0db9b5398dd0 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -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::().get_attribute(&ns!(), &local_name!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index e89dc21f3dac..ea9b17757876 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -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 `` is parsed, in /// nanoseconds. @@ -85,7 +85,7 @@ impl HTMLBodyElementMethods for HTMLBodyElement { pub trait HTMLBodyElementLayoutHelpers { fn get_background_color(&self) -> Option; fn get_color(&self) -> Option; - fn get_background(&self) -> Option; + fn get_background(&self) -> Option; } impl HTMLBodyElementLayoutHelpers for LayoutJS { @@ -110,7 +110,7 @@ impl HTMLBodyElementLayoutHelpers for LayoutJS { } #[allow(unsafe_code)] - fn get_background(&self) -> Option { + fn get_background(&self) -> Option { unsafe { (*self.upcast::().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("background")) diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 326b1804ddf7..554b029152cd 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -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 } diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 4ecc6a44fa06..cbf32ef9aab0 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -380,10 +380,12 @@ impl HTMLFormElement { fn mutate_action_url(&self, form_data: &mut Vec, mut load_data: LoadData, encoding: EncodingRef) { let charset = &*encoding.whatwg_name().unwrap(); - load_data.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)))); + 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()); - 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() + 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)))); + } + + load_data.url.query().unwrap_or("").to_string().into_bytes() } FormEncType::FormDataEncoded => { let mime = mime!(Multipart / FormData; Boundary =(&boundary)); diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 0430a0f7d260..311cc80aa8c9 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -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 { /// , /// step 1. - fn get_url(&self) -> Url { + fn get_url(&self) -> ServoUrl { let element = self.upcast::(); 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) { diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index d8ecda309433..3b58b383bf4f 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -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, + parsed_url: Option, source_url: Option, #[ignore_heap_size_of = "Arc"] image: Option>, @@ -58,7 +58,7 @@ pub struct HTMLImageElement { } impl HTMLImageElement { - pub fn get_url(&self) -> Option { + pub fn get_url(&self) -> Option { 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>; #[allow(unsafe_code)] - unsafe fn image_url(&self) -> Option; + unsafe fn image_url(&self) -> Option; fn get_width(&self) -> LengthOrPercentageOrAuto; fn get_height(&self) -> LengthOrPercentageOrAuto; @@ -254,7 +254,7 @@ impl LayoutHTMLImageElementHelpers for LayoutJS { } #[allow(unsafe_code)] - unsafe fn image_url(&self) -> Option { + unsafe fn image_url(&self) -> Option { (*self.unsafe_get()).current_request.borrow_for_layout().parsed_url.clone() } diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index 17c9514287e9..f670d8757e31 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -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, /// The initial URL requested. - url: Url, + url: ServoUrl, } impl PreInvoke for StylesheetContext {} diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 09a1b7cc4383..b14803912237 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -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, - 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), } diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 68b65f93142f..50c7658daabb 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -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, /// 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, character_encoding: EncodingRef) { let doc = document_from_node(script); diff --git a/components/script/dom/location.rs b/components/script/dom/location.rs index cf91c683f2f4..c992486b8d17 100644 --- a/components/script/dom/location.rs +++ b/components/script/dom/location.rs @@ -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); diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 37e0548fa13c..79208d82b482 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -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>; - fn image_url(&self) -> Option; + fn image_url(&self) -> Option; fn canvas_data(&self) -> Option; fn svg_data(&self) -> Option; fn iframe_pipeline_id(&self) -> PipelineId; @@ -1126,7 +1126,7 @@ impl LayoutNodeHelpers for LayoutJS { } #[allow(unsafe_code)] - fn image_url(&self) -> Option { + fn image_url(&self) -> Option { unsafe { self.downcast::() .expect("not an image!") diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 614c51398e8f..33a28da99eae 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -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 { 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() } diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index 7607cacc972f..484a1d0beee9 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -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>, raw_status: DOMRefCell)>>, response_type: DOMRefCell, - url: DOMRefCell>, - url_list: DOMRefCell>, + url: DOMRefCell>, + url_list: DOMRefCell>, // For now use the existing NetTraitsResponseBody enum body: DOMRefCell, #[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); } diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index f61dcc4e41c5..a3e5713a22e4 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -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; @@ -27,7 +27,7 @@ pub type TrustedServiceWorkerAddress = Trusted; pub struct ServiceWorker { eventtarget: EventTarget, script_url: DOMRefCell, - scope_url: Url, + scope_url: ServoUrl, state: Cell, skip_waiting: Cell } @@ -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 { reflect_dom_object(box ServiceWorker::new_inherited(script_url.as_str(), skip_waiting, @@ -64,8 +64,8 @@ impl ServiceWorker { self.upcast::().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() } } diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 6a39aad418f5..44dc9aafde38 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -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, - scope_url: Url, + scope_url: ServoUrl, } impl ServiceWorkerGlobalScope { fn new_inherited(init: WorkerGlobalScopeInit, - worker_url: Url, + worker_url: ServoUrl, from_devtools_receiver: Receiver, runtime: Runtime, own_sender: Sender, @@ -93,7 +93,7 @@ impl ServiceWorkerGlobalScope { timer_event_chan: IpcSender, timer_event_port: Receiver<()>, swmanager_sender: IpcSender, - 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, runtime: Runtime, own_sender: Sender, @@ -119,7 +119,7 @@ impl ServiceWorkerGlobalScope { timer_event_chan: IpcSender, timer_event_port: Receiver<()>, swmanager_sender: IpcSender, - scope_url: Url) + scope_url: ServoUrl) -> Root { let cx = runtime.cx(); let scope = box ServiceWorkerGlobalScope::new_inherited(init, @@ -141,7 +141,7 @@ impl ServiceWorkerGlobalScope { receiver: Receiver, devtools_receiver: IpcReceiver, swmanager_sender: IpcSender, - scope_url: Url) { + scope_url: ServoUrl) { let ScopeThings { script_url, init, worker_load_origin, diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index c3a08e514e48..58ca0933d69c 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -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 { 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; } diff --git a/components/script/dom/servoparser/html.rs b/components/script/dom/servoparser/html.rs index a2d636da6f3d..ab5af05a18d9 100644 --- a/components/script/dom/servoparser/html.rs +++ b/components/script/dom/servoparser/html.rs @@ -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) -> Self { let sink = Sink { diff --git a/components/script/dom/servoparser/mod.rs b/components/script/dom/servoparser/mod.rs index 7b5c5c7f4ab5..31ae5d4961a4 100644 --- a/components/script/dom/servoparser/mod.rs +++ b/components/script/dom/servoparser/mod.rs @@ -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) { 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) { 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, } @@ -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, diff --git a/components/script/dom/servoparser/xml.rs b/components/script/dom/servoparser/xml.rs index 6f87d6a389c7..3ce3fb69ca43 100644 --- a/components/script/dom/servoparser/xml.rs +++ b/components/script/dom/servoparser/xml.rs @@ -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), diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 3eb2b1ca844f..6b85241e04f0 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -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, old_value: Option, new_value: Option) { let global = self.global(); let window = global.as_window(); @@ -173,14 +173,14 @@ impl Storage { pub struct StorageEventRunnable { element: Trusted, - url: Url, + url: ServoUrl, key: Option, old_value: Option, new_value: Option } impl StorageEventRunnable { - fn new(storage: Trusted, url: Url, + fn new(storage: Trusted, url: ServoUrl, key: Option, old_value: Option, new_value: Option) -> StorageEventRunnable { StorageEventRunnable { element: storage, url: url, key: key, old_value: old_value, new_value: new_value } } diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index dbcefe48e536..50fe85a507b5 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -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: DOMRefCell, // https://url.spec.whatwg.org/#dom-url-searchparams search_params: MutNullableHeap>, } impl URL { - fn new_inherited(url: Url) -> URL { + fn new_inherited(url: ServoUrl) -> URL { URL { reflector_: Reflector::new(), url: DOMRefCell::new(url), @@ -42,18 +42,19 @@ impl URL { } } - pub fn new(global: &GlobalScope, url: Url) -> Root { + pub fn new(global: &GlobalScope, url: ServoUrl) -> Root { 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(); - url.query_pairs_mut().clear().extend_pairs(pairs); + if let Some(ref mut url) = self.url.borrow_mut().as_mut_url() { + url.query_pairs_mut().clear().extend_pairs(pairs); + } } } @@ -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()); } } diff --git a/components/script/dom/urlhelper.rs b/components/script/dom/urlhelper.rs index cd58612a6c1a..dd22e16f5513 100644 --- a/components/script/dom/urlhelper.rs +++ b/components/script/dom/urlhelper.rs @@ -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); + } + } } diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 1764db207643..d3486b7ad22b 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -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, #[dom_struct] pub struct WebSocket { eventtarget: EventTarget, - url: Url, + url: ServoUrl, ready_state: Cell, buffered_amount: Cell, clearing_buffer: Cell, //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 { + fn new(global: &GlobalScope, url: ServoUrl) -> Root { reflect_dom_object(box WebSocket::new_inherited(url), global, WebSocketBinding::Wrap) } @@ -205,10 +205,10 @@ impl WebSocket { protocols: Option) -> Fallible> { // 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. diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 63485e45dfca..f2e56fcff369 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -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) { + pub fn load_url(&self, url: ServoUrl, replace: bool, referrer_policy: Option) { 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() } diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 041ce8448de2..6adb9ff7b60e 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -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>) -> 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>, #[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, timer_event_chan: IpcSender, @@ -144,7 +144,7 @@ impl WorkerGlobalScope { } } - pub fn get_url(&self) -> &Url { + pub fn get_url(&self) -> &ServoUrl { &self.worker_url } diff --git a/components/script/dom/workerlocation.rs b/components/script/dom/workerlocation.rs index 287a803a612e..aee423304635 100644 --- a/components/script/dom/workerlocation.rs +++ b/components/script/dom/workerlocation.rs @@ -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 { + pub fn new(global: &WorkerGlobalScope, url: ServoUrl) -> Root { reflect_dom_object(box WorkerLocation::new_inherited(url), global, WorkerLocationBinding::Wrap) diff --git a/components/script/dom/xmldocument.rs b/components/script/dom/xmldocument.rs index 87038d3aa45b..bca9f6a65e35 100644 --- a/components/script/dom/xmldocument.rs +++ b/components/script/dom/xmldocument.rs @@ -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: Option, is_html_document: IsHTMLDocument, content_type: Option, last_modified: Option, @@ -49,7 +49,7 @@ impl XMLDocument { pub fn new(window: &Window, browsing_context: Option<&BrowsingContext>, - url: Option, + url: Option, doctype: IsHTMLDocument, content_type: Option, last_modified: Option, diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 57191d1d4e9f..de4350c5307f 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -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, - request_url: DOMRefCell>, + request_url: DOMRefCell>, #[ignore_heap_size_of = "Defined in hyper"] request_headers: DOMRefCell, request_body_len: Cell, @@ -149,7 +150,7 @@ pub struct XMLHttpRequest { fetch_time: Cell, generation_id: Cell, response_status: Cell>, - referrer_url: Option, + referrer_url: Option, referrer_policy: Option, } @@ -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 { + fn referrer_url(&self) -> Option { return self.referrer_url.clone(); } @@ -862,7 +863,8 @@ impl XMLHttpRequest { } fn process_headers_available(&self, - gen_id: GenerationId, metadata: Result) + gen_id: GenerationId, + metadata: Result) -> 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( diff --git a/components/script/fetch.rs b/components/script/fetch.rs index 740099344bf8..70a92910caaa 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -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, @@ -35,7 +35,7 @@ struct FetchContext { body: Vec, } -fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option { +fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option { let referrer = request.referrer.borrow(); referrer.to_url().map(|url| url.clone()) } diff --git a/components/script/layout_wrapper.rs b/components/script/layout_wrapper.rs index 00c7ce1413c5..b239a053366b 100644 --- a/components/script/layout_wrapper.rs +++ b/components/script/layout_wrapper.rs @@ -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 { + fn image_url(&self) -> Option { let this = unsafe { self.get_jsmanaged() }; this.image_url() } diff --git a/components/script/lib.rs b/components/script/lib.rs index ed3283868d53..fce55d94dca8 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -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; diff --git a/components/script/origin.rs b/components/script/origin.rs index 21204980e266..067eb77dcdac 100644 --- a/components/script/origin.rs +++ b/components/script/origin.rs @@ -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()), } diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 632397cc1476..1d434f591b8c 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -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, window_size: Option, - 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>, /// A map to store service worker registrations for a given origin - registration_map: DOMRefCell>>, + registration_map: DOMRefCell>>, /// 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, old_value: Option, new_value: Option) { 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)) { + fn notify_devtools(&self, title: DOMString, url: ServoUrl, ids: (PipelineId, Option)) { if let Some(ref chan) = self.devtools_chan { let page_info = DevtoolsPageInfo { title: String::from(title), @@ -1994,11 +1995,13 @@ impl ScriptThread { Some(document) => document, None => return warn!("Message sent to closed pipeline {}.", parent_pipeline_id), }; - let url = document.url(); - if &url[..Position::AfterQuery] == &nurl[..Position::AfterQuery] && - load_data.method == Method::Get { - self.check_and_scroll_fragment(fragment, parent_pipeline_id, &document); - return; + 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); + return; + } } } } @@ -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 { diff --git a/components/script/serviceworker_manager.rs b/components/script/serviceworker_manager.rs index 3920b0cd62b2..ac3c2ab41098 100644 --- a/components/script/serviceworker_manager.rs +++ b/components/script/serviceworker_manager.rs @@ -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, + registered_workers: HashMap, // map of active service worker descriptors - active_workers: HashMap>, + active_workers: HashMap>, // own sender to send messages here own_sender: IpcSender, // receiver to receive messages from constellation @@ -67,7 +67,7 @@ impl ServiceWorkerManager { }); } - pub fn get_matching_scope(&self, load_url: &Url) -> Option { + pub fn get_matching_scope(&self, load_url: &ServoUrl) -> Option { 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> { + pub fn wakeup_serviceworker(&mut self, scope_url: ServoUrl) -> Option> { let scope_things = self.registered_workers.get(&scope_url); if let Some(scope_things) = scope_things { let (sender, receiver) = channel(); diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 331f0fbbf8c4..a0de437d02f9 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -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) { + reply: IpcSender) { // 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(); } diff --git a/components/script_layout_interface/Cargo.toml b/components/script_layout_interface/Cargo.toml index 5d81df1261d7..44b0a3c320d4 100644 --- a/components/script_layout_interface/Cargo.toml +++ b/components/script_layout_interface/Cargo.toml @@ -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"]} diff --git a/components/script_layout_interface/lib.rs b/components/script_layout_interface/lib.rs index 284f6f33498e..50565e4426a7 100644 --- a/components/script_layout_interface/lib.rs +++ b/components/script_layout_interface/lib.rs @@ -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; diff --git a/components/script_layout_interface/message.rs b/components/script_layout_interface/message.rs index cd82dc79cd72..0f34a6bea754 100644 --- a/components/script_layout_interface/message.rs +++ b/components/script_layout_interface/message.rs @@ -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), @@ -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, Receiver), pub pipeline_port: IpcReceiver, diff --git a/components/script_layout_interface/wrapper_traits.rs b/components/script_layout_interface/wrapper_traits.rs index 9123c0c1f452..e68bdebcea09 100644 --- a/components/script_layout_interface/wrapper_traits.rs +++ b/components/script_layout_interface/wrapper_traits.rs @@ -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 { @@ -251,9 +251,7 @@ pub trait ThreadSafeLayoutNode: Clone + Copy + GetLayoutData + NodeInfo + Partia fn selection(&self) -> Option>; /// 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; + fn image_url(&self) -> Option; fn canvas_data(&self) -> Option; diff --git a/components/script_traits/Cargo.toml b/components/script_traits/Cargo.toml index b0e1669dd340..74df7f4ba4e5 100644 --- a/components/script_traits/Cargo.toml +++ b/components/script_traits/Cargo.toml @@ -31,6 +31,7 @@ profile_traits = {path = "../profile_traits"} rustc-serialize = "0.3.4" serde = "0.8" serde_derive = "0.8" +servo_url = {path = "../url", features = ["servo"]} style_traits = {path = "../style_traits", features = ["servo"]} time = "0.1.12" url = {version = "1.2", features = ["heap_size"]} diff --git a/components/script_traits/lib.rs b/components/script_traits/lib.rs index b475a214cc19..cfab945f99b5 100644 --- a/components/script_traits/lib.rs +++ b/components/script_traits/lib.rs @@ -31,9 +31,9 @@ extern crate rustc_serialize; extern crate serde; #[macro_use] extern crate serde_derive; +extern crate servo_url; extern crate style_traits; extern crate time; -extern crate url; mod script_msg; pub mod webdriver_msg; @@ -64,11 +64,11 @@ use net_traits::storage_thread::StorageType; use profile_traits::mem; use profile_traits::time as profile_time; use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use servo_url::ServoUrl; use std::collections::HashMap; use std::fmt; use std::sync::mpsc::{Receiver, Sender}; use style_traits::{PagePx, UnsafeNode, ViewportPx}; -use url::Url; use webdriver_msg::{LoadStatus, WebDriverScriptCommand}; pub use script_msg::{LayoutMsg, ScriptMsg, EventResult, LogEntry}; @@ -131,7 +131,7 @@ pub enum LayoutControlMsg { #[derive(Clone, Deserialize, Serialize)] pub struct LoadData { /// The URL. - pub url: Url, + pub url: ServoUrl, /// The method. #[serde(deserialize_with = "::hyper_serde::deserialize", serialize_with = "::hyper_serde::serialize")] @@ -145,12 +145,12 @@ pub struct LoadData { /// The referrer policy. pub referrer_policy: Option, /// The referrer URL. - pub referrer_url: Option, + pub referrer_url: Option, } impl LoadData { /// Create a new `LoadData` object. - pub fn new(url: Url, referrer_policy: Option, referrer_url: Option) -> LoadData { + pub fn new(url: ServoUrl, referrer_policy: Option, referrer_url: Option) -> LoadData { LoadData { url: url, method: Method::Get, @@ -247,7 +247,7 @@ pub enum ConstellationControlMsg { }, /// Cause a `storage` event to be dispatched at the appropriate window. /// The strings are key, old value and new value. - DispatchStorageEvent(PipelineId, StorageType, Url, Option, Option, Option), + DispatchStorageEvent(PipelineId, StorageType, ServoUrl, Option, Option, Option), /// Notifies a parent pipeline that one of its child frames is now active. /// PipelineId is for the parent, FrameId is the child frame. FramedContentChanged(PipelineId, FrameId), @@ -682,7 +682,7 @@ pub enum ConstellationMsg { /// immediately. GetPipelineTitle(PipelineId), /// Request to load the initial page. - InitLoadUrl(Url), + InitLoadUrl(ServoUrl), /// Query the constellation to see if the current compositor output is stable IsReadyToSaveImage(HashMap), /// Inform the constellation of a key event. @@ -730,7 +730,7 @@ pub struct WorkerGlobalScopeInit { #[derive(Deserialize, Serialize, Clone)] pub struct WorkerScriptLoadOrigin { /// referrer url - pub referrer_url: Option, + pub referrer_url: Option, /// the referrer policy which is used pub referrer_policy: Option, /// the pipeline id of the entity requesting the load diff --git a/components/script_traits/script_msg.rs b/components/script_traits/script_msg.rs index 434aa0011e69..61c64bbc7500 100644 --- a/components/script_traits/script_msg.rs +++ b/components/script_traits/script_msg.rs @@ -20,9 +20,9 @@ use msg::constellation_msg::{PipelineId, TraversalDirection}; use net_traits::CoreResourceMsg; use net_traits::storage_thread::StorageType; use offscreen_gl_context::{GLContextAttributes, GLLimits}; +use servo_url::ServoUrl; use style_traits::cursor::Cursor; use style_traits::viewport::ViewportConstraints; -use url::Url; /// Messages from the layout to the constellation. #[derive(Deserialize, Serialize)] @@ -62,7 +62,7 @@ pub enum LogEntry { pub enum ScriptMsg { /// Broadcast a storage event to every same-origin pipeline. /// The strings are key, old value and new value. - BroadcastStorageEvent(PipelineId, StorageType, Url, Option, Option, Option), + BroadcastStorageEvent(PipelineId, StorageType, ServoUrl, Option, Option, Option), /// Indicates whether this pipeline is currently running animations. ChangeRunningAnimationsState(PipelineId, AnimationState), /// Requests that a new 2D canvas thread be created. (This is done in the constellation because @@ -95,7 +95,7 @@ pub enum ScriptMsg { /// Gets the length of the joint session history from the constellation. JointSessionHistoryLength(PipelineId, IpcSender), /// Favicon detected - NewFavicon(Url), + NewFavicon(ServoUrl), /// Status message to be displayed in the chrome, eg. a link URL on mouseover. NodeStatus(Option), /// Notification that this iframe should be removed. @@ -113,7 +113,7 @@ pub enum ScriptMsg { /// Set the document state for a pipeline (used by screenshot / reftests) SetDocumentState(PipelineId, DocumentState), /// Update the pipeline Url, which can change after redirections. - SetFinalUrl(PipelineId, Url), + SetFinalUrl(PipelineId, ServoUrl), /// Check if an alert dialog box should be presented Alert(PipelineId, String, IpcSender), /// Scroll a page in a window @@ -137,9 +137,9 @@ pub enum ScriptMsg { PipelineExited(PipelineId), /// Send messages from postMessage calls from serviceworker /// to constellation for storing in service worker manager - ForwardDOMMessage(DOMMessage, Url), + ForwardDOMMessage(DOMMessage, ServoUrl), /// Store the data required to activate a service worker for the given scope - RegisterServiceWorker(ScopeThings, Url), + RegisterServiceWorker(ScopeThings, ServoUrl), /// Requests that the compositor shut down. Exit } @@ -148,7 +148,7 @@ pub enum ScriptMsg { #[derive(Deserialize, Serialize, Clone)] pub struct ScopeThings { /// script resource url - pub script_url: Url, + pub script_url: ServoUrl, /// network load origin of the resource pub worker_load_origin: WorkerScriptLoadOrigin, /// base resources required to create worker global scopes @@ -175,11 +175,11 @@ pub struct SWManagerSenders { #[derive(Deserialize, Serialize)] pub enum ServiceWorkerMsg { /// Message to register the service worker - RegisterServiceWorker(ScopeThings, Url), + RegisterServiceWorker(ScopeThings, ServoUrl), /// Timeout message sent by active service workers - Timeout(Url), + Timeout(ServoUrl), /// Message sent by constellation to forward to a running service worker - ForwardDOMMessage(DOMMessage, Url), + ForwardDOMMessage(DOMMessage, ServoUrl), /// Exit the service worker manager Exit, } diff --git a/components/script_traits/webdriver_msg.rs b/components/script_traits/webdriver_msg.rs index 788dbd5ad36f..b8c102ee4a23 100644 --- a/components/script_traits/webdriver_msg.rs +++ b/components/script_traits/webdriver_msg.rs @@ -10,7 +10,7 @@ use hyper_serde::Serde; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use rustc_serialize::json::{Json, ToJson}; -use url::Url; +use servo_url::ServoUrl; #[derive(Deserialize, Serialize)] pub enum WebDriverScriptCommand { @@ -34,7 +34,7 @@ pub enum WebDriverScriptCommand { GetElementTagName(String, IpcSender>), GetElementText(String, IpcSender>), GetFrameId(WebDriverFrameId, IpcSender, ()>>), - GetUrl(IpcSender), + GetUrl(IpcSender), IsEnabled(String, IpcSender>), IsSelected(String, IpcSender>), GetTitle(IpcSender) diff --git a/components/servo/Cargo.toml b/components/servo/Cargo.toml index ac1aa402cb43..ae804fdd2149 100644 --- a/components/servo/Cargo.toml +++ b/components/servo/Cargo.toml @@ -57,6 +57,7 @@ profile_traits = {path = "../profile_traits"} script = {path = "../script"} script_layout_interface = {path = "../script_layout_interface"} script_traits = {path = "../script_traits"} +servo_url = {path = "../url"} style = {path = "../style", features = ["servo"]} url = "1.2" util = {path = "../util"} diff --git a/components/servo/lib.rs b/components/servo/lib.rs index 509d9fa00ce7..05f250907fc9 100644 --- a/components/servo/lib.rs +++ b/components/servo/lib.rs @@ -45,6 +45,7 @@ pub extern crate profile_traits; pub extern crate script; pub extern crate script_traits; pub extern crate script_layout_interface; +pub extern crate servo_url; pub extern crate style; pub extern crate url; pub extern crate util; @@ -87,12 +88,12 @@ use profile::time as profile_time; use profile_traits::mem; use profile_traits::time; use script_traits::{ConstellationMsg, SWManagerSenders, ScriptMsg}; +use servo_url::ServoUrl; use std::borrow::Cow; use std::cmp::max; use std::path::PathBuf; use std::rc::Rc; use std::sync::mpsc::Sender; -use url::Url; use util::opts; use util::prefs::PREFS; use util::resource_files::resources_dir_path; @@ -249,7 +250,7 @@ impl Browser where Window: WindowMethods + 'static { fn create_constellation(user_agent: Cow<'static, str>, config_dir: Option, - url: Option, + url: Option, compositor_proxy: Box, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, diff --git a/components/style/Cargo.toml b/components/style/Cargo.toml index 1374926b08b7..6b828ab89bba 100644 --- a/components/style/Cargo.toml +++ b/components/style/Cargo.toml @@ -17,7 +17,7 @@ gecko = ["nsstring_vendor", "num_cpus", "rayon/unstable"] servo = ["serde/unstable", "serde", "serde_derive", "heapsize_derive", "style_traits/servo", "app_units/plugins", "servo_atoms", "html5ever-atoms", "cssparser/heap_size", "cssparser/serde-serialization", - "url/heap_size", "plugins", "rayon/unstable"] + "plugins", "rayon/unstable", "servo_url/servo"] testing = [] [dependencies] @@ -50,9 +50,9 @@ serde_derive = {version = "0.8", optional = true} servo_atoms = {path = "../atoms", optional = true} smallvec = "0.1" style_traits = {path = "../style_traits"} +servo_url = {path = "../url"} time = "0.1" unicode-segmentation = "0.1.2" -url = "1.2" util = {path = "../util"} plugins = {path = "../plugins", optional = true} diff --git a/components/style/attr.rs b/components/style/attr.rs index ffa4fa37eed9..c3064b089fd4 100644 --- a/components/style/attr.rs +++ b/components/style/attr.rs @@ -11,12 +11,12 @@ use app_units::Au; use cssparser::{self, Color, RGBA}; use euclid::num::Zero; use num_traits::ToPrimitive; +use servo_url::ServoUrl; use std::ascii::AsciiExt; use std::str::FromStr; use str::{HTML_SPACE_CHARACTERS, read_exponent, read_fraction}; use str::{read_numbers, split_commas, split_html_space_chars}; #[cfg(not(feature = "gecko"))] use str::str_join; -use url::Url; use values::specified::Length; // Duplicated from script::dom::values. @@ -42,7 +42,7 @@ pub enum AttrValue { Length(String, Option), Color(String, Option), Dimension(String, LengthOrPercentageOrAuto), - Url(String, Option), + Url(String, Option), } /// Shared implementation to parse an integer according to @@ -208,7 +208,7 @@ impl AttrValue { AttrValue::Atom(value) } - pub fn from_url(base: &Url, url: String) -> AttrValue { + pub fn from_url(base: &ServoUrl, url: String) -> AttrValue { let joined = base.join(&url).ok(); AttrValue::Url(url, joined) } @@ -293,7 +293,7 @@ impl AttrValue { /// ## Panics /// /// Panics if the `AttrValue` is not a `Url` - pub fn as_url(&self) -> Option<&Url> { + pub fn as_url(&self) -> Option<&ServoUrl> { match *self { AttrValue::Url(_, ref url) => url.as_ref(), _ => panic!("Url not found"), diff --git a/components/style/font_face.rs b/components/style/font_face.rs index c01d26c1b322..8fc2d51c1003 100644 --- a/components/style/font_face.rs +++ b/components/style/font_face.rs @@ -11,7 +11,7 @@ use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser}; use parser::{ParserContext, log_css_error}; use properties::longhands::font_family::parse_one_family; use std::iter; -use url::Url; +use values::specified::url::SpecifiedUrl; #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] @@ -23,7 +23,7 @@ pub enum Source { #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct UrlSource { - pub url: Url, + pub url: SpecifiedUrl, pub format_hints: Vec, } @@ -139,9 +139,8 @@ fn parse_one_src(context: &ParserContext, input: &mut Parser) -> Result GeckoElement<'le> { } lazy_static! { - pub static ref DUMMY_BASE_URL: Url = { - Url::parse("http://www.example.org").unwrap() + pub static ref DUMMY_BASE_URL: ServoUrl = { + ServoUrl::parse("http://www.example.org").unwrap() }; } diff --git a/components/style/lib.rs b/components/style/lib.rs index 64fe606d9c1f..3fca994960c6 100644 --- a/components/style/lib.rs +++ b/components/style/lib.rs @@ -79,13 +79,13 @@ extern crate selectors; extern crate serde; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; +extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_traits; extern crate time; #[allow(unused_extern_crates)] extern crate unicode_segmentation; -extern crate url; extern crate util; pub mod animation; diff --git a/components/style/parser.rs b/components/style/parser.rs index 84d421b9ee66..5b29834df1a5 100644 --- a/components/style/parser.rs +++ b/components/style/parser.rs @@ -10,8 +10,8 @@ use error_reporting::ParseErrorReporter; use gecko_bindings::sugar::refptr::{GeckoArcPrincipal, GeckoArcURI}; use selector_impl::TheSelectorImpl; use selectors::parser::ParserContext as SelectorParserContext; +use servo_url::ServoUrl; use stylesheets::Origin; -use url::Url; #[cfg(not(feature = "gecko"))] pub struct ParserContextExtraData; @@ -37,14 +37,14 @@ impl ParserContextExtraData { pub struct ParserContext<'a> { pub stylesheet_origin: Origin, - pub base_url: &'a Url, + pub base_url: &'a ServoUrl, pub selector_context: SelectorParserContext, pub error_reporter: Box, pub extra_data: ParserContextExtraData, } impl<'a> ParserContext<'a> { - pub fn new_with_extra_data(stylesheet_origin: Origin, base_url: &'a Url, + pub fn new_with_extra_data(stylesheet_origin: Origin, base_url: &'a ServoUrl, error_reporter: Box, extra_data: ParserContextExtraData) -> ParserContext<'a> { @@ -59,7 +59,7 @@ impl<'a> ParserContext<'a> { } } - pub fn new(stylesheet_origin: Origin, base_url: &'a Url, error_reporter: Box) + pub fn new(stylesheet_origin: Origin, base_url: &'a ServoUrl, error_reporter: Box) -> ParserContext<'a> { let extra_data = ParserContextExtraData::default(); ParserContext::new_with_extra_data(stylesheet_origin, base_url, error_reporter, extra_data) diff --git a/components/style/properties/declaration_block.rs b/components/style/properties/declaration_block.rs index b65fc6698d68..c720c93e6bfc 100644 --- a/components/style/properties/declaration_block.rs +++ b/components/style/properties/declaration_block.rs @@ -6,13 +6,13 @@ use cssparser::{DeclarationListParser, parse_important}; use cssparser::{Parser, AtRuleParser, DeclarationParser, Delimiter}; use error_reporting::ParseErrorReporter; use parser::{ParserContext, ParserContextExtraData, log_css_error}; +use servo_url::ServoUrl; use std::ascii::AsciiExt; use std::boxed::Box as StdBox; use std::fmt; use style_traits::ToCss; use stylesheets::Origin; use super::*; -use url::Url; #[cfg_attr(feature = "servo", derive(HeapSizeOf))] @@ -423,14 +423,19 @@ pub fn append_serialization<'a, W, I>(dest: &mut W, write!(dest, ";") } -pub fn parse_style_attribute(input: &str, base_url: &Url, error_reporter: StdBox, +pub fn parse_style_attribute(input: &str, + base_url: &ServoUrl, + error_reporter: StdBox, extra_data: ParserContextExtraData) -> PropertyDeclarationBlock { let context = ParserContext::new_with_extra_data(Origin::Author, base_url, error_reporter, extra_data); parse_property_declaration_list(&context, &mut Parser::new(input)) } -pub fn parse_one_declaration(name: &str, input: &str, base_url: &Url, error_reporter: StdBox, +pub fn parse_one_declaration(name: &str, + input: &str, + base_url: &ServoUrl, + error_reporter: StdBox, extra_data: ParserContextExtraData) -> Result, ()> { let context = ParserContext::new_with_extra_data(Origin::Author, base_url, error_reporter, extra_data); diff --git a/components/style/properties/properties.mako.rs b/components/style/properties/properties.mako.rs index 343842b468c2..ef0196081479 100644 --- a/components/style/properties/properties.mako.rs +++ b/components/style/properties/properties.mako.rs @@ -21,7 +21,6 @@ use app_units::Au; #[cfg(feature = "servo")] use cssparser::{Color as CSSParserColor, RGBA}; use cssparser::{Parser, TokenSerializationType}; use error_reporting::ParseErrorReporter; -use url::Url; #[cfg(feature = "servo")] use euclid::side_offsets::SideOffsets2D; use euclid::size::Size2D; use computed_values; @@ -29,6 +28,7 @@ use font_metrics::FontMetricsProvider; #[cfg(feature = "servo")] use logical_geometry::{LogicalMargin, PhysicalSide}; use logical_geometry::WritingMode; use parser::{Parse, ParserContext, ParserContextExtraData}; +use servo_url::ServoUrl; use style_traits::ToCss; use stylesheets::Origin; #[cfg(feature = "servo")] use values::Either; @@ -221,7 +221,7 @@ mod property_bit_field { fn substitute_variables_${property.ident}_slow( css: &String, first_token_type: TokenSerializationType, - base_url: &Url, + base_url: &ServoUrl, from_shorthand: Option, custom_properties: &Option>, f: F, @@ -474,7 +474,7 @@ pub enum DeclaredValue { WithVariables { css: String, first_token_type: TokenSerializationType, - base_url: Url, + base_url: ServoUrl, from_shorthand: Option, }, Initial, diff --git a/components/style/stylesheets.rs b/components/style/stylesheets.rs index 1538e9e0f25d..8b632737a894 100644 --- a/components/style/stylesheets.rs +++ b/components/style/stylesheets.rs @@ -18,11 +18,11 @@ use parser::{ParserContext, ParserContextExtraData, log_css_error}; use properties::{PropertyDeclarationBlock, parse_property_declaration_list}; use selector_impl::TheSelectorImpl; use selectors::parser::{Selector, parse_selector_list}; +use servo_url::ServoUrl; use std::cell::Cell; use std::fmt; use std::sync::Arc; use style_traits::ToCss; -use url::Url; use viewport::ViewportRule; @@ -171,7 +171,7 @@ impl ToCss for StyleRule { impl Stylesheet { pub fn from_bytes_iter>>( - input: I, base_url: Url, protocol_encoding_label: Option<&str>, + input: I, base_url: ServoUrl, protocol_encoding_label: Option<&str>, environment_encoding: Option, origin: Origin, error_reporter: Box, extra_data: ParserContextExtraData) -> Stylesheet { @@ -186,7 +186,7 @@ impl Stylesheet { } pub fn from_bytes(bytes: &[u8], - base_url: Url, + base_url: ServoUrl, protocol_encoding_label: Option<&str>, environment_encoding: Option, origin: Origin, error_reporter: Box, @@ -198,7 +198,7 @@ impl Stylesheet { Stylesheet::from_str(&string, base_url, origin, error_reporter, extra_data) } - pub fn from_str(css: &str, base_url: Url, origin: Origin, + pub fn from_str(css: &str, base_url: ServoUrl, origin: Origin, error_reporter: Box, extra_data: ParserContextExtraData) -> Stylesheet { let rule_parser = TopLevelRuleParser { diff --git a/components/style/values/specified/image.rs b/components/style/values/specified/image.rs index 96af3fc91d3d..ba751704465b 100644 --- a/components/style/values/specified/image.rs +++ b/components/style/values/specified/image.rs @@ -9,11 +9,10 @@ use cssparser::Parser; use parser::{Parse, ParserContext}; +use servo_url::ServoUrl; use std::f32::consts::PI; use std::fmt; -use std::sync::Arc; use style_traits::ToCss; -use url::Url; use values::computed::ComputedValueAsSpecified; use values::specified::{Angle, CSSColor, Length, LengthOrPercentage}; use values::specified::position::Position; @@ -48,7 +47,7 @@ impl Image { /// Creates an already specified image value from an already resolved URL /// for insertion in the cascade. - pub fn for_cascade(url: Option>, extra_data: UrlExtraData) -> Self { + pub fn for_cascade(url: Option, extra_data: UrlExtraData) -> Self { Image::Url(SpecifiedUrl::for_cascade(url, extra_data)) } } diff --git a/components/style/values/specified/url.rs b/components/style/values/specified/url.rs index b81c89f887d1..84fb5faf4a7a 100644 --- a/components/style/values/specified/url.rs +++ b/components/style/values/specified/url.rs @@ -10,15 +10,15 @@ use gecko_bindings::sugar::refptr::{GeckoArcPrincipal, GeckoArcURI}; use parser::ParserContext; #[cfg(feature = "gecko")] use parser::ParserContextExtraData; +use servo_url::ServoUrl; use std::fmt::{self, Write}; use std::ptr; use std::sync::Arc; use style_traits::ToCss; -use url::Url; use values::computed::ComputedValueAsSpecified; #[derive(PartialEq, Clone, Debug)] -#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize, Eq))] pub struct UrlExtraData { #[cfg(feature = "gecko")] pub base: GeckoArcURI, @@ -55,7 +55,7 @@ impl UrlExtraData { /// A specified url() value. #[derive(Clone, Debug)] -#[cfg_attr(feature = "servo", derive(HeapSizeOf))] +#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize))] pub struct SpecifiedUrl { /// The original URI. This might be optional since we may insert computed /// values of images into the cascade directly, and we don't bother to @@ -66,7 +66,7 @@ pub struct SpecifiedUrl { original: Option>, /// The resolved value for the url, if valid. - resolved: Option>, + resolved: Option, /// Extra data used for Stylo. extra_data: UrlExtraData, @@ -88,7 +88,7 @@ impl SpecifiedUrl { }; let serialization = Arc::new(url.into_owned()); - let resolved = context.base_url.join(&serialization).ok().map(Arc::new); + let resolved = context.base_url.join(&serialization).ok(); Ok(SpecifiedUrl { original: Some(serialization), resolved: resolved, @@ -100,7 +100,7 @@ impl SpecifiedUrl { &self.extra_data } - pub fn url(&self) -> Option<&Arc> { + pub fn url(&self) -> Option<&ServoUrl> { self.resolved.as_ref() } @@ -114,7 +114,7 @@ impl SpecifiedUrl { /// Creates an already specified url value from an already resolved URL /// for insertion in the cascade. - pub fn for_cascade(url: Option>, extra_data: UrlExtraData) -> Self { + pub fn for_cascade(url: Option, extra_data: UrlExtraData) -> Self { SpecifiedUrl { original: None, resolved: url, @@ -122,12 +122,11 @@ impl SpecifiedUrl { } } - // Just for unit tests, don't use outside of them! #[cfg(feature = "servo")] pub fn new_for_testing(url: &str) -> Self { SpecifiedUrl { original: Some(Arc::new(url.into())), - resolved: Url::parse(url).ok().map(Arc::new), + resolved: ServoUrl::parse(url).ok(), extra_data: UrlExtraData {} } } @@ -142,6 +141,8 @@ impl PartialEq for SpecifiedUrl { } } +impl Eq for SpecifiedUrl {} + impl ToCss for SpecifiedUrl { fn to_css(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("url(\"")); diff --git a/components/url/Cargo.toml b/components/url/Cargo.toml new file mode 100644 index 000000000000..48184fb702cb --- /dev/null +++ b/components/url/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "servo_url" +version = "0.0.1" +authors = ["The Servo Project Developers"] +license = "MPL-2.0" +publish = false + +[lib] +name = "servo_url" +path = "lib.rs" + +[features] +servo = ["heapsize", "heapsize_derive", "serde", "serde_derive", + "url/heap_size"] + + +[dependencies] +url = "1.2" +heapsize = {version = "0.3.0", optional = true} +heapsize_derive = {version = "0.1", optional = true} +serde = {version = "0.8", optional = true} +serde_derive = {version = "0.8", optional = true} diff --git a/components/url/lib.rs b/components/url/lib.rs new file mode 100644 index 000000000000..d040c18ec9fa --- /dev/null +++ b/components/url/lib.rs @@ -0,0 +1,150 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#![deny(unsafe_code)] + +#![crate_name = "servo_url"] +#![crate_type = "rlib"] + +#![cfg_attr(feature = "servo", feature(plugin))] +#![cfg_attr(feature = "servo", feature(proc_macro))] + +#[cfg(feature = "servo")] extern crate serde; +#[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; +#[cfg(feature = "servo")] extern crate heapsize; +#[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; + +extern crate url; + +use std::fmt; +use std::net::IpAddr; +use std::path::Path; +use std::sync::Arc; +use url::{Url, Origin}; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "servo", derive(HeapSizeOf, Serialize, Deserialize))] +pub struct ServoUrl(Arc); + +impl ServoUrl { + pub fn from_url(url: Url) -> Self { + ServoUrl(Arc::new(url)) + } + + pub fn parse_with_base(base: Option<&Self>, input: &str) -> Result { + Url::options().base_url(base.map(|b| &*b.0)).parse(input).map(Self::from_url) + } + + pub fn into_string(self) -> String { + Arc::try_unwrap(self.0).unwrap_or_else(|s| (*s).clone()).into_string() + } + + // NOTE: These methods return options that are always true temporarily until + // we special-case some urls to avoid going through rust-url. + pub fn into_url(self) -> Option { + Some(Arc::try_unwrap(self.0).unwrap_or_else(|s| (*s).clone())) + } + + pub fn as_url(&self) -> Option<&Arc> { + Some(&self.0) + } + + pub fn parse(input: &str) -> Result { + Url::parse(input).map(Self::from_url) + } + + pub fn cannot_be_a_base(&self) -> bool { + self.0.cannot_be_a_base() + } + + pub fn domain(&self) -> Option<&str> { + self.0.domain() + } + + pub fn fragment(&self) -> Option<&str> { + self.0.fragment() + } + + pub fn path(&self) -> &str { + self.0.path() + } + + pub fn origin(&self) -> Origin { + self.0.origin() + } + + pub fn scheme(&self) -> &str { + self.0.scheme() + } + + pub fn as_str(&self) -> &str { + self.0.as_str() + } + + pub fn as_mut_url(&mut self) -> Option<&mut Url> { + Some(Arc::make_mut(&mut self.0)) + } + + pub fn set_username(&mut self, user: &str) -> Result<(), ()> { + Arc::make_mut(&mut self.0).set_username(user) + } + + pub fn set_ip_host(&mut self, addr: IpAddr) -> Result<(), ()> { + Arc::make_mut(&mut self.0).set_ip_host(addr) + } + + pub fn set_password(&mut self, pass: Option<&str>) -> Result<(), ()> { + Arc::make_mut(&mut self.0).set_password(pass) + } + + pub fn username(&self) -> &str { + self.0.username() + } + + pub fn password(&self) -> Option<&str> { + self.0.password() + } + + pub fn to_file_path(&self) -> Result<::std::path::PathBuf, ()> { + self.0.to_file_path() + } + + pub fn host(&self) -> Option> { + self.0.host() + } + + pub fn host_str(&self) -> Option<&str> { + self.0.host_str() + } + + pub fn port(&self) -> Option { + self.0.port() + } + + pub fn port_or_known_default(&self) -> Option { + self.0.port_or_known_default() + } + + pub fn join(&self, input: &str) -> Result { + self.0.join(input).map(Self::from_url) + } + + pub fn path_segments(&self) -> Option<::std::str::Split> { + self.0.path_segments() + } + + pub fn query(&self) -> Option<&str> { + self.0.query() + } + + pub fn from_file_path>(path: P) -> Result { + Ok(Self::from_url(try!(Url::from_file_path(path)))) + } +} + +impl fmt::Display for ServoUrl { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(formatter) + } +} diff --git a/components/util/Cargo.toml b/components/util/Cargo.toml index 5426b32d7394..2f9ee4486cf5 100644 --- a/components/util/Cargo.toml +++ b/components/util/Cargo.toml @@ -26,8 +26,9 @@ num_cpus = "1.1.0" rustc-serialize = "0.3" serde = {version = "0.8", optional = true} serde_derive = {version = "0.8", optional = true} -url = "1.2" +servo_url = {path = "../url"} plugins = {path = "../plugins", optional = true} +url = "1.2" [dev-dependencies] env_logger = "0.3" diff --git a/components/util/lib.rs b/components/util/lib.rs index b8ec37a01fef..3c72d90d2575 100644 --- a/components/util/lib.rs +++ b/components/util/lib.rs @@ -21,6 +21,7 @@ extern crate num_cpus; extern crate rustc_serialize; #[cfg(feature = "servo")] extern crate serde; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; +extern crate servo_url; extern crate url; #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] extern crate xdg; diff --git a/components/util/opts.rs b/components/util/opts.rs index 1d032a07d08f..4f159f326a87 100644 --- a/components/util/opts.rs +++ b/components/util/opts.rs @@ -11,6 +11,7 @@ use getopts::Options; use num_cpus; use prefs::{self, PrefValue, PREFS}; use resource_files::set_resources_path; +use servo_url::ServoUrl; use std::borrow::Cow; use std::cmp; use std::default::Default; @@ -30,7 +31,7 @@ pub struct Opts { pub is_running_problem_test: bool, /// The initial URL to load. - pub url: Option, + pub url: Option, /// How many threads to use for CPU painting (`-t`). /// @@ -63,7 +64,7 @@ pub struct Opts { /// won't be loaded pub userscripts: Option, - pub user_stylesheets: Vec<(Vec, Url)>, + pub user_stylesheets: Vec<(Vec, ServoUrl)>, pub output_file: Option, @@ -502,7 +503,7 @@ const DEFAULT_USER_AGENT: UserAgent = UserAgent::Desktop; pub fn default_opts() -> Opts { Opts { is_running_problem_test: false, - url: Some(Url::parse("about:blank").unwrap()), + url: Some(ServoUrl::parse("about:blank").unwrap()), paint_threads: 1, tile_size: 512, device_pixels_per_px: None, @@ -788,7 +789,7 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { let user_stylesheets = opt_match.opt_strs("user-stylesheet").iter().map(|filename| { let path = cwd.join(filename); - let url = Url::from_file_path(&path).unwrap(); + let url = ServoUrl::from_url(Url::from_file_path(&path).unwrap()); let mut contents = Vec::new(); File::open(path) .unwrap_or_else(|err| args_fail(&format!("Couldn't open {}: {}", filename, err))) @@ -936,11 +937,11 @@ pub fn get() -> &'static Opts { &OPTIONS } -pub fn parse_url_or_filename(cwd: &Path, input: &str) -> Result { - match Url::parse(input) { +pub fn parse_url_or_filename(cwd: &Path, input: &str) -> Result { + match ServoUrl::parse(input) { Ok(url) => Ok(url), Err(url::ParseError::RelativeUrlWithoutBase) => { - Url::from_file_path(&*cwd.join(input)) + Url::from_file_path(&*cwd.join(input)).map(ServoUrl::from_url) } Err(_) => Err(()), } diff --git a/components/webdriver_server/Cargo.toml b/components/webdriver_server/Cargo.toml index 8b34b97da700..6bb75d93b60f 100644 --- a/components/webdriver_server/Cargo.toml +++ b/components/webdriver_server/Cargo.toml @@ -22,6 +22,7 @@ plugins = {path = "../plugins"} regex = "0.1.55" rustc-serialize = "0.3.4" script_traits = {path = "../script_traits"} +servo_url = {path = "../url", features = ["servo"]} url = {version = "1.2", features = ["heap_size"]} util = {path = "../util"} uuid = { version = "0.3.1", features = ["v4"] } diff --git a/components/webdriver_server/lib.rs b/components/webdriver_server/lib.rs index bf0ebbaee378..e6cf2ac6f620 100644 --- a/components/webdriver_server/lib.rs +++ b/components/webdriver_server/lib.rs @@ -22,7 +22,7 @@ extern crate net_traits; extern crate regex; extern crate rustc_serialize; extern crate script_traits; -extern crate url; +extern crate servo_url; extern crate util; extern crate uuid; extern crate webdriver; @@ -42,13 +42,13 @@ use rustc_serialize::json::{Json, ToJson}; use script_traits::{ConstellationMsg, LoadData, WebDriverCommandMsg}; use script_traits::webdriver_msg::{LoadStatus, WebDriverCookieError, WebDriverFrameId}; use script_traits::webdriver_msg::{WebDriverJSError, WebDriverJSResult, WebDriverScriptCommand}; +use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::BTreeMap; use std::net::{SocketAddr, SocketAddrV4}; use std::sync::mpsc::Sender; use std::thread; use std::time::Duration; -use url::Url; use util::prefs::{PREFS, PrefValue}; use util::thread::spawn_named; use uuid::Uuid; @@ -337,7 +337,7 @@ impl Handler { } fn handle_get(&self, parameters: &GetParameters) -> WebDriverResult { - let url = match Url::parse(¶meters.url[..]) { + let url = match ServoUrl::parse(¶meters.url[..]) { Ok(url) => url, Err(_) => return Err(WebDriverError::new(ErrorStatus::InvalidArgument, "Invalid URL")) diff --git a/ports/cef/Cargo.lock b/ports/cef/Cargo.lock index f940a33dc33f..1e23ecaf3212 100644 --- a/ports/cef/Cargo.lock +++ b/ports/cef/Cargo.lock @@ -17,8 +17,8 @@ dependencies = [ "objc 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "plugins 0.0.1", "script_traits 0.0.1", + "servo_url 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "x11 2.8.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -332,9 +332,9 @@ dependencies = [ "script_traits 0.0.1", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender 0.9.0 (git+https://github.com/servo/webrender)", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", @@ -367,8 +367,8 @@ dependencies = [ "script_traits 0.0.1", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -532,8 +532,8 @@ dependencies = [ "msg 0.0.1", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -791,13 +791,13 @@ dependencies = [ "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "servo-fontconfig 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "simd 0.1.1 (git+https://github.com/huonw/simd)", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-script 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", "xi-unicode 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -867,8 +867,8 @@ dependencies = [ "script_traits 0.0.1", "servo-egl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo-glutin 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "user32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1163,12 +1163,12 @@ dependencies = [ "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "style_traits 0.0.1", "unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-script 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -1201,8 +1201,9 @@ dependencies = [ "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "style_traits 0.0.1", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -1217,7 +1218,7 @@ dependencies = [ "net_traits 0.0.1", "profile_traits 0.0.1", "script_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -1302,6 +1303,7 @@ dependencies = [ "script 0.0.1", "script_layout_interface 0.0.1", "script_traits 0.0.1", + "servo_url 0.0.1", "sig 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1488,6 +1490,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "threadpool 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "tinyfiledialogs 0.1.0 (git+https://github.com/jdm/tinyfiledialogs)", @@ -1529,6 +1532,7 @@ dependencies = [ "num-traits 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "uuid 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2018,6 +2022,7 @@ dependencies = [ "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "style_traits 0.0.1", @@ -2055,8 +2060,8 @@ dependencies = [ "script_traits 0.0.1", "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "style 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2084,6 +2089,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2244,6 +2250,17 @@ dependencies = [ "string_cache_codegen 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "servo_url" +version = "0.0.1" +dependencies = [ + "heapsize 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", + "heapsize_derive 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "sha1" version = "0.2.0" @@ -2361,11 +2378,11 @@ dependencies = [ "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-segmentation 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "walkdir 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2652,6 +2669,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "xdg 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2760,6 +2778,7 @@ dependencies = [ "regex 0.1.76 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "script_traits 0.0.1", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "uuid 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/ports/cef/Cargo.toml b/ports/cef/Cargo.toml index 400d89635972..3d2625b3aacb 100644 --- a/ports/cef/Cargo.toml +++ b/ports/cef/Cargo.toml @@ -25,14 +25,14 @@ gfx_traits = {path = "../../components/gfx_traits"} gleam = "0.2.8" glutin_app = {path = "../glutin"} libc = "0.2" +libservo = {path = "../../components/servo"} log = {version = "0.3.5", features = ["release_max_level_info"]} msg = {path = "../../components/msg"} net_traits = {path = "../../components/net_traits"} plugins = {path = "../../components/plugins"} script_traits = {path = "../../components/script_traits"} -libservo = {path = "../../components/servo"} +servo_url = {path = "../../components/url"} style_traits = {path = "../../components/style_traits"} -url = "1.2" util = {path = "../../components/util"} [target.'cfg(target_os="macos")'.dependencies] diff --git a/ports/cef/lib.rs b/ports/cef/lib.rs index 02a39d901fec..c0008757dbab 100644 --- a/ports/cef/lib.rs +++ b/ports/cef/lib.rs @@ -24,14 +24,14 @@ extern crate gleam; extern crate glutin_app; extern crate rustc_unicode; extern crate script_traits; +extern crate servo_url; +extern crate style_traits; extern crate net_traits; extern crate msg; extern crate util; -extern crate style_traits; extern crate libc; -extern crate url as std_url; #[cfg(target_os="macos")] #[link_args="-Xlinker -undefined -Xlinker dynamic_lookup"] diff --git a/ports/cef/window.rs b/ports/cef/window.rs index 8a3b1d9d2ce1..16ea145bf0ca 100644 --- a/ports/cef/window.rs +++ b/ports/cef/window.rs @@ -33,7 +33,7 @@ use std::os::raw::{c_char, c_void}; use std::ptr; use std::rc::Rc; use std::sync::mpsc::{Sender, channel}; -use std_url::Url; +use servo_url::ServoUrl; use style_traits::cursor::Cursor; use util::geometry::ScreenPx; #[cfg(target_os="linux")] @@ -312,13 +312,13 @@ impl WindowMethods for Window { } } - fn set_favicon(&self, url: Url) { + fn set_favicon(&self, url: ServoUrl) { let browser = self.cef_browser.borrow(); let browser = match *browser { None => return, Some(ref browser) => browser, }; - browser.downcast().favicons.borrow_mut().push(url.to_string().clone()); + browser.downcast().favicons.borrow_mut().push(url.into_string()); } fn status(&self, info: Option) { @@ -444,7 +444,7 @@ impl WindowMethods for Window { }; } - fn set_page_url(&self, url: Url) { + fn set_page_url(&self, url: ServoUrl) { // it seems to be the case that load start is always called // IMMEDIATELY before address change, so just stick it here on_load_start(self); @@ -457,7 +457,7 @@ impl WindowMethods for Window { let servoframe = frame.downcast(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let mut frame_url = servoframe.url.borrow_mut(); - *frame_url = url.to_string(); + *frame_url = url.into_string(); let utf16_chars: Vec = Utf16Encoder::new((*frame_url).chars()).collect(); if check_ptr_exist!(browser.get_host().get_client(), get_display_handler) && check_ptr_exist!(browser.get_host().get_client().get_display_handler(), on_address_change) { diff --git a/ports/geckolib/Cargo.lock b/ports/geckolib/Cargo.lock index 5e9e96f30854..33f120421f4b 100644 --- a/ports/geckolib/Cargo.lock +++ b/ports/geckolib/Cargo.lock @@ -12,10 +12,10 @@ dependencies = [ "num_cpus 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style 0.0.1", "style_traits 0.0.1", "stylo_tests 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -333,6 +333,13 @@ name = "serde" version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "servo_url" +version = "0.0.1" +dependencies = [ + "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "smallvec" version = "0.1.8" @@ -366,11 +373,11 @@ dependencies = [ "rayon 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-segmentation 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "walkdir 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -400,9 +407,9 @@ dependencies = [ "num_cpus 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -485,6 +492,7 @@ dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "xdg 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/ports/geckolib/Cargo.toml b/ports/geckolib/Cargo.toml index 265c68bc2504..08533a648605 100644 --- a/ports/geckolib/Cargo.toml +++ b/ports/geckolib/Cargo.toml @@ -20,9 +20,9 @@ log = {version = "0.3.5", features = ["release_max_level_info"]} num_cpus = "1.1.0" parking_lot = "0.3" selectors = "0.14" +servo_url = {path = "../../components/url"} style = {path = "../../components/style", features = ["gecko"]} style_traits = {path = "../../components/style_traits"} -url = "1.2" [dev-dependencies] stylo_tests = {path = "../../tests/unit/stylo"} diff --git a/ports/geckolib/glue.rs b/ports/geckolib/glue.rs index 8a1745c16ca6..763170ba8fe4 100644 --- a/ports/geckolib/glue.rs +++ b/ports/geckolib/glue.rs @@ -7,6 +7,7 @@ use cssparser::Parser; use env_logger; use euclid::Size2D; use parking_lot::RwLock; +use servo_url::ServoUrl; use std::fmt::Write; use std::mem::transmute; use std::sync::{Arc, Mutex}; @@ -47,7 +48,6 @@ use style::string_cache::Atom; use style::stylesheets::{Origin, Stylesheet}; use style::timer::Timer; use style_traits::ToCss; -use url::Url; /* * For Gecko->Servo function calls, we need to redeclare the same signature that was declared in @@ -167,7 +167,7 @@ pub extern "C" fn Servo_Node_ClearNodeData(node: RawGeckoNodeBorrowed) -> () { #[no_mangle] pub extern "C" fn Servo_StyleSheet_Empty(mode: SheetParsingMode) -> RawServoStyleSheetStrong { - let url = Url::parse("about:blank").unwrap(); + let url = ServoUrl::parse("about:blank").unwrap(); let extra_data = ParserContextExtraData::default(); let origin = match mode { SheetParsingMode::eAuthorSheetFeatures => Origin::Author, @@ -198,7 +198,7 @@ pub extern "C" fn Servo_StyleSheet_FromUTF8Bytes(data: *const nsACString, }; let base_str = unsafe { base_url.as_ref().unwrap().as_str_unchecked() }; - let url = Url::parse(base_str).unwrap(); + let url = ServoUrl::parse(base_str).unwrap(); let extra_data = unsafe { ParserContextExtraData { base: Some(GeckoArcURI::new(base)), referrer: Some(GeckoArcURI::new(referrer)), @@ -408,7 +408,7 @@ pub extern "C" fn Servo_ParseProperty(property: *const nsACString, value: *const let name = unsafe { property.as_ref().unwrap().as_str_unchecked() }; let value = unsafe { value.as_ref().unwrap().as_str_unchecked() }; let base_str = unsafe { base_url.as_ref().unwrap().as_str_unchecked() }; - let base_url = Url::parse(base_str).unwrap(); + let base_url = ServoUrl::parse(base_str).unwrap(); let extra_data = unsafe { ParserContextExtraData { base: Some(GeckoArcURI::new(base)), referrer: Some(GeckoArcURI::new(referrer)), diff --git a/ports/geckolib/lib.rs b/ports/geckolib/lib.rs index 23a03fa8b7f1..a09fc47f7822 100644 --- a/ports/geckolib/lib.rs +++ b/ports/geckolib/lib.rs @@ -12,8 +12,8 @@ extern crate euclid; extern crate libc; #[macro_use] extern crate log; extern crate parking_lot; +extern crate servo_url; extern crate style_traits; -extern crate url; #[allow(non_snake_case)] pub mod glue; diff --git a/ports/glutin/Cargo.toml b/ports/glutin/Cargo.toml index 51fc586c84b1..e18061babe01 100644 --- a/ports/glutin/Cargo.toml +++ b/ports/glutin/Cargo.toml @@ -19,8 +19,8 @@ msg = {path = "../../components/msg"} net_traits = {path = "../../components/net_traits"} script_traits = {path = "../../components/script_traits"} servo-glutin = "0.6" +servo_url = {path = "../../components/url"} style_traits = {path = "../../components/style_traits"} -url = {version = "1.2", features = ["heap_size"]} util = {path = "../../components/util"} [target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies] diff --git a/ports/glutin/lib.rs b/ports/glutin/lib.rs index 99e57439b241..d44e8952530a 100644 --- a/ports/glutin/lib.rs +++ b/ports/glutin/lib.rs @@ -19,8 +19,8 @@ extern crate msg; extern crate net_traits; #[cfg(any(target_os = "linux", target_os = "macos"))] extern crate osmesa_sys; extern crate script_traits; +extern crate servo_url; extern crate style_traits; -extern crate url; extern crate util; #[cfg(target_os = "windows")] extern crate winapi; #[cfg(target_os = "windows")] extern crate user32; diff --git a/ports/glutin/window.rs b/ports/glutin/window.rs index f473b5915c19..11953f64b92a 100644 --- a/ports/glutin/window.rs +++ b/ports/glutin/window.rs @@ -26,6 +26,7 @@ use net_traits::net_error_list::NetError; #[cfg(any(target_os = "linux", target_os = "macos"))] use osmesa_sys; use script_traits::{TouchEventType, TouchpadPressurePhase}; +use servo_url::ServoUrl; use std::cell::{Cell, RefCell}; #[cfg(any(target_os = "linux", target_os = "macos"))] use std::ffi::CString; @@ -36,7 +37,6 @@ use std::ptr; use std::rc::Rc; use std::sync::mpsc::{Sender, channel}; use style_traits::cursor::Cursor; -use url::Url; #[cfg(target_os = "windows")] use user32; use util::geometry::ScreenPx; @@ -183,7 +183,7 @@ pub struct Window { mouse_pos: Cell>, key_modifiers: Cell, - current_url: RefCell>, + current_url: RefCell>, /// The contents of the last ReceivedCharacter event for use in a subsequent KeyEvent. pending_key_event_char: Cell>, @@ -904,7 +904,7 @@ impl WindowMethods for Window { } } - fn set_page_url(&self, url: Url) { + fn set_page_url(&self, url: ServoUrl) { *self.current_url.borrow_mut() = Some(url); } @@ -980,7 +980,7 @@ impl WindowMethods for Window { } } - fn set_favicon(&self, _: Url) { + fn set_favicon(&self, _: ServoUrl) { } fn prepare_for_composite(&self, _width: usize, _height: usize) -> bool { diff --git a/ports/servo/Cargo.lock b/ports/servo/Cargo.lock index c2f4a1b7c90f..35f7167efce2 100644 --- a/ports/servo/Cargo.lock +++ b/ports/servo/Cargo.lock @@ -361,9 +361,9 @@ dependencies = [ "script_traits 0.0.1", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender 0.9.0 (git+https://github.com/servo/webrender)", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", @@ -396,8 +396,8 @@ dependencies = [ "script_traits 0.0.1", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -561,8 +561,8 @@ dependencies = [ "msg 0.0.1", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -861,13 +861,13 @@ dependencies = [ "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "servo-fontconfig 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "simd 0.1.1 (git+https://github.com/huonw/simd)", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-script 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", "xi-unicode 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -946,8 +946,8 @@ dependencies = [ "script_traits 0.0.1", "servo-egl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo-glutin 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "user32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1242,12 +1242,12 @@ dependencies = [ "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "style_traits 0.0.1", "unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-script 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -1287,8 +1287,9 @@ dependencies = [ "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "style_traits 0.0.1", "util 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -1303,7 +1304,7 @@ dependencies = [ "net_traits 0.0.1", "profile_traits 0.0.1", "script_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "webrender_traits 0.9.0 (git+https://github.com/servo/webrender)", ] @@ -1389,6 +1390,7 @@ dependencies = [ "script 0.0.1", "script_layout_interface 0.0.1", "script_traits 0.0.1", + "servo_url 0.0.1", "sig 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1575,6 +1577,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "threadpool 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "tinyfiledialogs 0.1.0 (git+https://github.com/jdm/tinyfiledialogs)", @@ -1614,6 +1617,7 @@ dependencies = [ "net_traits 0.0.1", "plugins 0.0.1", "profile_traits 0.0.1", + "servo_url 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1638,6 +1642,7 @@ dependencies = [ "num-traits 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "uuid 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2167,6 +2172,7 @@ dependencies = [ "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style 0.0.1", "style_traits 0.0.1", @@ -2204,8 +2210,8 @@ dependencies = [ "script_traits 0.0.1", "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "style 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2215,7 +2221,7 @@ dependencies = [ "msg 0.0.1", "plugins 0.0.1", "script 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", ] [[package]] @@ -2243,6 +2249,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2411,6 +2418,17 @@ dependencies = [ "string_cache_codegen 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "servo_url" +version = "0.0.1" +dependencies = [ + "heapsize 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", + "heapsize_derive 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "sha1" version = "0.2.0" @@ -2527,11 +2545,11 @@ dependencies = [ "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "style_traits 0.0.1", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-segmentation 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "walkdir 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2549,9 +2567,9 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "selectors 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", + "servo_url 0.0.1", "style 0.0.1", "style_traits 0.0.1", - "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", ] @@ -2845,6 +2863,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "xdg 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2960,6 +2979,7 @@ dependencies = [ "regex 0.1.76 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "script_traits 0.0.1", + "servo_url 0.0.1", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.0.1", "uuid 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/tests/unit/net/Cargo.toml b/tests/unit/net/Cargo.toml index 1c9a275e4457..aa462c0c156f 100644 --- a/tests/unit/net/Cargo.toml +++ b/tests/unit/net/Cargo.toml @@ -25,4 +25,5 @@ profile_traits = {path = "../../../components/profile_traits"} time = "0.1" unicase = "1.0" url = {version = "1.2", features = ["heap_size"]} +servo_url = {path = "../../../components/url"} util = {path = "../../../components/util"} diff --git a/tests/unit/net/chrome_loader.rs b/tests/unit/net/chrome_loader.rs index 72776d248f7c..c7669d9a0ac2 100644 --- a/tests/unit/net/chrome_loader.rs +++ b/tests/unit/net/chrome_loader.rs @@ -3,10 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net::test::resolve_chrome_url; -use url::Url; +use servo_url::ServoUrl; -fn c(s: &str) -> Result { - resolve_chrome_url(&Url::parse(s).unwrap()) +fn c(s: &str) -> Result { + resolve_chrome_url(&ServoUrl::parse(s).unwrap()) } #[test] diff --git a/tests/unit/net/cookie.rs b/tests/unit/net/cookie.rs index e96ebdd4fbda..2a8e4d19b1e5 100644 --- a/tests/unit/net/cookie.rs +++ b/tests/unit/net/cookie.rs @@ -6,7 +6,7 @@ use cookie_rs; use net::cookie::Cookie; use net::cookie_storage::CookieStorage; use net_traits::CookieSource; -use url::Url; +use servo_url::ServoUrl; #[test] fn test_domain_match() { @@ -56,9 +56,9 @@ fn test_default_path() { fn fn_cookie_constructor() { use net_traits::CookieSource; - let url = &Url::parse("http://example.com/foo").unwrap(); + let url = &ServoUrl::parse("http://example.com/foo").unwrap(); - let gov_url = &Url::parse("http://gov.ac/foo").unwrap(); + let gov_url = &ServoUrl::parse("http://gov.ac/foo").unwrap(); // cookie name/value test assert!(cookie_rs::Cookie::parse(" baz ").is_err()); assert!(cookie_rs::Cookie::parse(" = bar ").is_err()); @@ -94,7 +94,7 @@ fn fn_cookie_constructor() { assert!(&cookie.cookie.domain.as_ref().unwrap()[..] == "example.com"); assert!(cookie.host_only); - let u = &Url::parse("http://example.com/foobar").unwrap(); + let u = &ServoUrl::parse("http://example.com/foobar").unwrap(); let cookie = cookie_rs::Cookie::parse("foobar=value;path=/").unwrap(); assert!(Cookie::new_wrapped(cookie, u, CookieSource::HTTP).is_some()); } @@ -117,7 +117,7 @@ fn delay_to_ensure_different_timestamp() { fn test_sort_order() { use std::cmp::Ordering; - let url = &Url::parse("http://example.com/foo").unwrap(); + let url = &ServoUrl::parse("http://example.com/foo").unwrap(); let a_wrapped = cookie_rs::Cookie::parse("baz=bar; Path=/foo/bar/").unwrap(); let a = Cookie::new_wrapped(a_wrapped.clone(), url, CookieSource::HTTP).unwrap(); delay_to_ensure_different_timestamp(); diff --git a/tests/unit/net/cookie_http_state.rs b/tests/unit/net/cookie_http_state.rs index fceb9189f523..4f40157dd8e5 100644 --- a/tests/unit/net/cookie_http_state.rs +++ b/tests/unit/net/cookie_http_state.rs @@ -6,12 +6,12 @@ use hyper::header::{Header, SetCookie}; use net::cookie::Cookie; use net::cookie_storage::CookieStorage; use net_traits::CookieSource; -use url::Url; +use servo_url::ServoUrl; fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String { let mut storage = CookieStorage::new(); - let url = Url::parse(set_location).unwrap(); + let url = ServoUrl::parse(set_location).unwrap(); let source = CookieSource::HTTP; // Add all cookies to the store @@ -28,7 +28,7 @@ fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String } // Get cookies for the test location - let url = Url::parse(final_location).unwrap(); + let url = ServoUrl::parse(final_location).unwrap(); storage.cookies_for_url(&url, source).unwrap_or("".to_string()) } diff --git a/tests/unit/net/data_loader.rs b/tests/unit/net/data_loader.rs index 91edcdf619c4..93c625f30d9e 100644 --- a/tests/unit/net/data_loader.rs +++ b/tests/unit/net/data_loader.rs @@ -9,15 +9,15 @@ use hyper_serde::Serde; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; +use servo_url::ServoUrl; use std::ops::Deref; -use url::Url; #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option, charset: Option<&str>, data: Option<&[u8]>) { - let url = Url::parse(url).unwrap(); + let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let request = Request::new(url, Some(origin), false, None); diff --git a/tests/unit/net/fetch.rs b/tests/unit/net/fetch.rs index 086ff0e0a050..2b973b6f7744 100644 --- a/tests/unit/net/fetch.rs +++ b/tests/unit/net/fetch.rs @@ -25,6 +25,7 @@ use net::fetch::methods::{fetch, fetch_with_cors_cache}; use net_traits::ReferrerPolicy; use net_traits::request::{Origin, RedirectMode, Referrer, Request, RequestMode}; use net_traits::response::{CacheState, Response, ResponseBody, ResponseType}; +use servo_url::ServoUrl; use std::fs::File; use std::io::Read; use std::rc::Rc; @@ -33,7 +34,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{Sender, channel}; use time::{self, Duration}; use unicase::UniCase; -use url::{Origin as UrlOrigin, Url}; +use url::Origin as UrlOrigin; use util::resource_files::resources_dir_path; // TODO write a struct that impls Handler for storing test values @@ -84,7 +85,7 @@ fn test_fetch_response_body_matches_const_message() { #[test] fn test_fetch_aboutblank() { - let url = Url::parse("about:blank").unwrap(); + let url = ServoUrl::parse("about:blank").unwrap(); let origin = Origin::Origin(url.origin()); let request = Request::new(url, Some(origin), false, None); *request.referrer.borrow_mut() = Referrer::NoReferrer; @@ -109,13 +110,13 @@ fn test_fetch_blob() { bytes: bytes.to_vec(), }; - let origin = Url::parse("http://www.example.org/").unwrap(); + let origin = ServoUrl::parse("http://www.example.org/").unwrap(); let (sender, receiver) = ipc::channel().unwrap(); let message = FileManagerThreadMsg::PromoteMemory(blob_buf, true, sender, "http://www.example.org".into()); context.filemanager.handle(message, None); let id = receiver.recv().unwrap().unwrap(); - let url = Url::parse(&format!("blob:{}{}", origin.as_str(), id.simple())).unwrap(); + let url = ServoUrl::parse(&format!("blob:{}{}", origin.as_str(), id.simple())).unwrap(); let request = Request::new(url, Some(Origin::Origin(origin.origin())), false, None); @@ -140,7 +141,7 @@ fn test_fetch_file() { let mut path = resources_dir_path().expect("Cannot find resource dir"); path.push("servo.css"); - let url = Url::from_file_path(path.clone()).unwrap(); + let url = ServoUrl::from_file_path(path.clone()).unwrap(); let origin = Origin::Origin(url.origin()); let request = Request::new(url, Some(origin), false, None); @@ -454,7 +455,7 @@ fn test_fetch_with_local_urls_only() { }; let (mut server, server_url) = make_server(handler); - let do_fetch = |url: Url| { + let do_fetch = |url: ServoUrl| { let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), false, None); *request.referrer.borrow_mut() = Referrer::NoReferrer; @@ -465,7 +466,7 @@ fn test_fetch_with_local_urls_only() { fetch_sync(request, None) }; - let local_url = Url::parse("about:blank").unwrap(); + let local_url = ServoUrl::parse("about:blank").unwrap(); let local_response = do_fetch(local_url); let server_response = do_fetch(server_url); diff --git a/tests/unit/net/http_loader.rs b/tests/unit/net/http_loader.rs index 096b90a9b47e..f3af14eeb6ac 100644 --- a/tests/unit/net/http_loader.rs +++ b/tests/unit/net/http_loader.rs @@ -34,6 +34,7 @@ use net_traits::{CustomResponse, LoadOrigin, Metadata, NetworkError, ReferrerPol use net_traits::request::{Request, RequestInit, CredentialsMode, Destination}; use net_traits::response::ResponseBody; use new_fetch_context; +use servo_url::ServoUrl; use std::borrow::Cow; use std::io::{self, Cursor, Read, Write}; use std::rc::Rc; @@ -41,14 +42,13 @@ use std::sync::{Arc, Mutex, RwLock, mpsc}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::Receiver; use std::thread; -use url::Url; const DEFAULT_USER_AGENT: &'static str = "Test-agent"; struct HttpTest; impl LoadOrigin for HttpTest { - fn referrer_url(&self) -> Option { + fn referrer_url(&self) -> Option { None } fn referrer_policy(&self) -> Option { @@ -65,8 +65,8 @@ struct LoadOriginInfo<'a> { } impl<'a> LoadOrigin for LoadOriginInfo<'a> { - fn referrer_url(&self) -> Option { - Some(Url::parse(self.referrer_url).unwrap()) + fn referrer_url(&self) -> Option { + Some(ServoUrl::parse(self.referrer_url).unwrap()) } fn referrer_policy(&self) -> Option { self.referrer_policy.clone() @@ -245,7 +245,7 @@ struct AssertAuthHeaderRequestFactory { impl HttpRequestFactory for AssertAuthHeaderRequestFactory { type R = MockRequest; - fn create(&self, _: Url, _: Method, headers: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, headers: Headers) -> Result { let request = if headers.has::>() { assert_headers_included(&self.expected_headers, &headers); MockRequest::new(ResponseType::Text(self.body.clone())) @@ -276,7 +276,7 @@ struct AssertMustIncludeHeadersRequestFactory { impl HttpRequestFactory for AssertMustIncludeHeadersRequestFactory { type R = MockRequest; - fn create(&self, _: Url, _: Method, headers: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, headers: Headers) -> Result { assert_headers_included(&self.expected_headers, &headers); Ok(MockRequest::new(ResponseType::Text(self.body.clone()))) } @@ -284,7 +284,7 @@ impl HttpRequestFactory for AssertMustIncludeHeadersRequestFactory { fn assert_cookie_for_domain(cookie_jar: Arc>, domain: &str, cookie: Option<&str>) { let mut cookie_jar = cookie_jar.write().unwrap(); - let url = Url::parse(&*domain).unwrap(); + let url = ServoUrl::parse(&*domain).unwrap(); let cookies = cookie_jar.cookies_for_url(&url, CookieSource::HTTP); assert_eq!(cookies.as_ref().map(|c| &**c), cookie); } @@ -297,7 +297,7 @@ struct AssertMustNotIncludeHeadersRequestFactory { impl HttpRequestFactory for AssertMustNotIncludeHeadersRequestFactory { type R = MockRequest; - fn create(&self, _: Url, _: Method, headers: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, headers: Headers) -> Result { assert!(self.headers_not_expected.len() != 0); for header in &self.headers_not_expected { assert!(headers.get_raw(header).is_none()); @@ -760,7 +760,7 @@ fn test_load_adds_host_to_sts_list_when_url_is_https_and_sts_headers_are_present impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, _: Url, _: Method, _: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, _: Headers) -> Result { let content = <[_]>::to_vec("Yay!".as_bytes()); let mut headers = Headers::new(); headers.set(StrictTransportSecurity::excluding_subdomains(31536000)); @@ -768,7 +768,7 @@ fn test_load_adds_host_to_sts_list_when_url_is_https_and_sts_headers_are_present } } - let url = Url::parse("https://mozilla.com").unwrap(); + let url = ServoUrl::parse("https://mozilla.com").unwrap(); let load_data = LoadData::new(LoadContext::Browsing, url.clone(), &HttpTest); @@ -857,8 +857,8 @@ fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_re #[test] fn test_load_sends_secure_cookie_if_http_changed_to_https_due_to_entry_in_hsts_store() { - let url = Url::parse("http://mozilla.com").unwrap(); - let secured_url = Url::parse("https://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); + let secured_url = ServoUrl::parse("https://mozilla.com").unwrap(); let ui_provider = TestProvider::new(); let http_state = HttpState::new(); { @@ -1005,8 +1005,8 @@ fn test_when_cookie_received_marked_secure_is_ignored_for_http() { #[test] fn test_when_cookie_set_marked_httpsonly_secure_isnt_sent_on_http_request() { - let sec_url = Url::parse("https://mozilla.com").unwrap(); - let url = Url::parse("http://mozilla.com").unwrap(); + let sec_url = ServoUrl::parse("https://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); let http_state = HttpState::new(); let ui_provider = TestProvider::new(); @@ -1173,7 +1173,7 @@ fn test_load_sets_default_accept_encoding_to_gzip_and_deflate() { #[test] fn test_load_errors_when_there_a_redirect_loop() { - let url_b_for_a = Arc::new(Mutex::new(None::)); + let url_b_for_a = Arc::new(Mutex::new(None::)); let url_b_for_a_clone = url_b_for_a.clone(); let handler_a = move |_: HyperRequest, mut response: HyperResponse| { response.headers_mut().set(Location(url_b_for_a_clone.lock().unwrap().as_ref().unwrap().to_string())); @@ -1211,7 +1211,7 @@ fn test_load_errors_when_there_a_redirect_loop() { #[test] fn test_load_succeeds_with_a_redirect_loop() { - let url_b_for_a = Arc::new(Mutex::new(None::)); + let url_b_for_a = Arc::new(Mutex::new(None::)); let url_b_for_a_clone = url_b_for_a.clone(); let handled_a = AtomicBool::new(false); let handler_a = move |_: HyperRequest, mut response: HyperResponse| { @@ -1262,7 +1262,7 @@ fn test_load_follows_a_redirect() { impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, url: Url, _: Method, _: Headers) -> Result { + fn create(&self, url: ServoUrl, _: Method, _: Headers) -> Result { if url.domain().unwrap() == "mozilla.com" { Ok(MockRequest::new(ResponseType::Redirect("http://mozilla.org".to_owned()))) } else if url.domain().unwrap() == "mozilla.org" { @@ -1279,7 +1279,7 @@ fn test_load_follows_a_redirect() { } } - let url = Url::parse("http://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); let load_data = LoadData::new(LoadContext::Browsing, url.clone(), &HttpTest); let http_state = HttpState::new(); let ui_provider = TestProvider::new(); @@ -1299,14 +1299,14 @@ struct DontConnectFactory; impl HttpRequestFactory for DontConnectFactory { type R = MockRequest; - fn create(&self, url: Url, _: Method, _: Headers) -> Result { + fn create(&self, url: ServoUrl, _: Method, _: Headers) -> Result { Err(LoadError::new(url, LoadErrorType::Connection { reason: "should not have connected".into() })) } } #[test] fn test_load_errors_when_scheme_is_not_http_or_https() { - let url = Url::parse("ftp://not-supported").unwrap(); + let url = ServoUrl::parse("ftp://not-supported").unwrap(); let load_data = LoadData::new(LoadContext::Browsing, url.clone(), &HttpTest); let http_state = HttpState::new(); @@ -1325,7 +1325,7 @@ fn test_load_errors_when_scheme_is_not_http_or_https() { #[test] fn test_load_errors_when_viewing_source_and_inner_url_scheme_is_not_http_or_https() { - let url = Url::parse("view-source:ftp://not-supported").unwrap(); + let url = ServoUrl::parse("view-source:ftp://not-supported").unwrap(); let load_data = LoadData::new(LoadContext::Browsing, url.clone(), &HttpTest); let http_state = HttpState::new(); @@ -1353,7 +1353,7 @@ fn test_load_errors_when_cancelled() { impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, _: Url, _: Method, _: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, _: Headers) -> Result { let mut headers = Headers::new(); headers.set(Host { hostname: "Kaboom!".to_owned(), port: None }); Ok(MockRequest::new( @@ -1368,7 +1368,7 @@ fn test_load_errors_when_cancelled() { let cancel_listener = CancellationListener::new(Some(cancel_resource)); cancel_sender.send(()).unwrap(); - let url = Url::parse("https://mozilla.com").unwrap(); + let url = ServoUrl::parse("https://mozilla.com").unwrap(); let load_data = LoadData::new(LoadContext::Browsing, url.clone(), &HttpTest); let http_state = HttpState::new(); let ui_provider = TestProvider::new(); @@ -1386,15 +1386,15 @@ fn test_load_errors_when_cancelled() { #[test] fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { - let url_x = Url::parse("http://mozilla.com").unwrap(); - let url_y = Url::parse("http://mozilla.org").unwrap(); + let url_x = ServoUrl::parse("http://mozilla.com").unwrap(); + let url_y = ServoUrl::parse("http://mozilla.org").unwrap(); struct Factory; impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, url: Url, _: Method, headers: Headers) -> Result { + fn create(&self, url: ServoUrl, _: Method, headers: Headers) -> Result { if url.domain().unwrap() == "mozilla.com" { let mut expected_headers_x = Headers::new(); expected_headers_x.set_raw("Cookie".to_owned(), @@ -1459,14 +1459,14 @@ fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { #[test] fn test_redirect_from_x_to_x_provides_x_with_cookie_from_first_response() { - let url = Url::parse("http://mozilla.org/initial/").unwrap(); + let url = ServoUrl::parse("http://mozilla.org/initial/").unwrap(); struct Factory; impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, url: Url, _: Method, headers: Headers) -> Result { + fn create(&self, url: ServoUrl, _: Method, headers: Headers) -> Result { if url.path_segments().unwrap().next().unwrap() == "initial" { let mut initial_answer_headers = Headers::new(); initial_answer_headers.set_raw("set-cookie", vec![b"mozillaIs=theBest; path=/;".to_vec()]); @@ -1505,7 +1505,7 @@ fn test_redirect_from_x_to_x_provides_x_with_cookie_from_first_response() { #[test] fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { - let url = Url::parse("http://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); let http_state = HttpState::new(); let ui_provider = TestProvider::new(); @@ -1541,7 +1541,7 @@ fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { #[test] fn test_auth_ui_sets_header_on_401() { - let url = Url::parse("http://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); let http_state = HttpState::new(); let ui_provider = TestProvider { username: "test".to_owned(), password: "test".to_owned() }; @@ -1574,7 +1574,7 @@ fn test_auth_ui_sets_header_on_401() { #[test] fn test_auth_ui_needs_www_auth() { - let url = Url::parse("http://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); let http_state = HttpState::new(); struct AuthProvider; impl UIProvider for AuthProvider { @@ -1588,7 +1588,7 @@ fn test_auth_ui_needs_www_auth() { impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, _: Url, _: Method, _: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, _: Headers) -> Result { Ok(MockRequest::new(ResponseType::NeedsAuth(Headers::new()))) } } @@ -1610,7 +1610,7 @@ fn test_auth_ui_needs_www_auth() { fn assert_referrer_header_matches(origin_info: &LoadOrigin, request_url: &str, expected_referrer: &str) { - let url = Url::parse(request_url).unwrap(); + let url = ServoUrl::parse(request_url).unwrap(); let ui_provider = TestProvider::new(); let load_data = LoadData::new(LoadContext::Browsing, @@ -1631,7 +1631,7 @@ fn assert_referrer_header_matches(origin_info: &LoadOrigin, } fn assert_referrer_header_not_included(origin_info: &LoadOrigin, request_url: &str) { - let url = Url::parse(request_url).unwrap(); + let url = ServoUrl::parse(request_url).unwrap(); let ui_provider = TestProvider::new(); let load_data = LoadData::new(LoadContext::Browsing, @@ -2039,7 +2039,7 @@ fn load_request_for_custom_response(expected_body: Vec) -> (Metadata, String struct Factory; impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, _: Url, _: Method, _: Headers) -> Result { + fn create(&self, _: ServoUrl, _: Method, _: Headers) -> Result { Ok(MockRequest::new(ResponseType::Dummy404)) } } @@ -2049,7 +2049,7 @@ fn load_request_for_custom_response(expected_body: Vec) -> (Metadata, String RawStatus(200, Cow::Borrowed("OK")), expected_body ); - let url = Url::parse("http://mozilla.com").unwrap(); + let url = ServoUrl::parse("http://mozilla.com").unwrap(); let http_state = HttpState::new(); let ui_provider = TestProvider::new(); let load_data = LoadData::new(LoadContext::Browsing, url.clone(), &HttpTest); @@ -2087,13 +2087,13 @@ fn test_content_blocked() { impl HttpRequestFactory for Factory { type R = MockRequest; - fn create(&self, _url: Url, _method: Method, _: Headers) -> Result { + fn create(&self, _url: ServoUrl, _method: Method, _: Headers) -> Result { Ok(MockRequest::new(ResponseType::Text(<[_]>::to_vec("Yay!".as_bytes())))) } } - let blocked_url = Url::parse("http://mozilla.com").unwrap(); - let url_without_cookies = Url::parse("http://mozilla2.com").unwrap(); + let blocked_url = ServoUrl::parse("http://mozilla.com").unwrap(); + let url_without_cookies = ServoUrl::parse("http://mozilla2.com").unwrap(); let mut http_state = HttpState::new(); let blocked_content_list = "[{ \"trigger\": { \"url-filter\": \"https?://mozilla.com\" }, \ diff --git a/tests/unit/net/lib.rs b/tests/unit/net/lib.rs index d426e198a3f1..400356c6f3b8 100644 --- a/tests/unit/net/lib.rs +++ b/tests/unit/net/lib.rs @@ -16,6 +16,7 @@ extern crate msg; extern crate net; extern crate net_traits; extern crate profile_traits; +extern crate servo_url; extern crate time; extern crate unicase; extern crate url; @@ -42,10 +43,10 @@ use net::test::HttpState; use net_traits::FetchTaskTarget; use net_traits::request::Request; use net_traits::response::Response; +use servo_url::ServoUrl; use std::rc::Rc; use std::sync::mpsc::Sender; use std::thread; -use url::Url; const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; @@ -82,10 +83,10 @@ fn fetch_sync(request: Request, dc: Option>) -> Respo fetch(Rc::new(request), &mut None, &new_fetch_context(dc)) } -fn make_server(handler: H) -> (Listening, Url) { +fn make_server(handler: H) -> (Listening, ServoUrl) { // this is a Listening server because of handle_threads() let server = Server::http("0.0.0.0:0").unwrap().handle_threads(handler, 1).unwrap(); let url_string = format!("http://localhost:{}", server.socket.port()); - let url = Url::parse(&url_string).unwrap(); + let url = ServoUrl::parse(&url_string).unwrap(); (server, url) } diff --git a/tests/unit/net/resource_thread.rs b/tests/unit/net/resource_thread.rs index a8c95c61badf..a11e2c001aed 100644 --- a/tests/unit/net/resource_thread.rs +++ b/tests/unit/net/resource_thread.rs @@ -9,11 +9,11 @@ use net_traits::{CoreResourceMsg, LoadConsumer, LoadContext, LoadData}; use net_traits::{LoadOrigin, NetworkError, ProgressMsg, ReferrerPolicy}; use net_traits::hosts::{host_replacement, parse_hostsfile}; use profile_traits::time::ProfilerChan; +use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::HashMap; use std::net::IpAddr; use std::sync::mpsc::channel; -use url::Url; fn ip(s: &str) -> IpAddr { s.parse().unwrap() @@ -22,7 +22,7 @@ fn ip(s: &str) -> IpAddr { struct ResourceTest; impl LoadOrigin for ResourceTest { - fn referrer_url(&self) -> Option { + fn referrer_url(&self) -> Option { None } fn referrer_policy(&self) -> Option { @@ -50,7 +50,7 @@ fn test_bad_scheme() { let (resource_thread, _) = new_core_resource_thread( "".into(), None, ProfilerChan(tx), None); let (start_chan, start) = ipc::channel().unwrap(); - let url = Url::parse("bogus://whatever").unwrap(); + let url = ServoUrl::parse("bogus://whatever").unwrap(); resource_thread.send(CoreResourceMsg::Load(LoadData::new(LoadContext::Browsing, url, &ResourceTest), LoadConsumer::Channel(start_chan), None)).unwrap(); @@ -187,13 +187,13 @@ fn test_replace_hosts() { host_table.insert("foo.bar.com".to_owned(), ip("127.0.0.1")); host_table.insert("servo.test.server".to_owned(), ip("127.0.0.2")); - let url = Url::parse("http://foo.bar.com:8000/foo").unwrap(); + let url = ServoUrl::parse("http://foo.bar.com:8000/foo").unwrap(); assert_eq!(host_replacement(&host_table, &url).host_str().unwrap(), "127.0.0.1"); - let url = Url::parse("http://servo.test.server").unwrap(); + let url = ServoUrl::parse("http://servo.test.server").unwrap(); assert_eq!(host_replacement(&host_table, &url).host_str().unwrap(), "127.0.0.2"); - let url = Url::parse("http://a.foo.bar.com").unwrap(); + let url = ServoUrl::parse("http://a.foo.bar.com").unwrap(); assert_eq!(host_replacement(&host_table, &url).host_str().unwrap(), "a.foo.bar.com"); } @@ -232,7 +232,7 @@ fn test_cancelled_listener() { let (sender, receiver) = ipc::channel().unwrap(); let (id_sender, id_receiver) = ipc::channel().unwrap(); let (sync_sender, sync_receiver) = ipc::channel().unwrap(); - let url = Url::parse(&format!("http://127.0.0.1:{}", port)).unwrap(); + let url = ServoUrl::parse(&format!("http://127.0.0.1:{}", port)).unwrap(); resource_thread.send(CoreResourceMsg::Load(LoadData::new(LoadContext::Browsing, url, &ResourceTest), LoadConsumer::Channel(sender), diff --git a/tests/unit/script/Cargo.toml b/tests/unit/script/Cargo.toml index 4a4e0c96d6b3..a8f100d2a40f 100644 --- a/tests/unit/script/Cargo.toml +++ b/tests/unit/script/Cargo.toml @@ -13,4 +13,4 @@ doctest = false msg = {path = "../../../components/msg"} plugins = {path = "../../../components/plugins"} script = {path = "../../../components/script"} -url = {version = "1.2", features = ["heap_size"]} +servo_url = {path = "../../../components/url"} diff --git a/tests/unit/script/lib.rs b/tests/unit/script/lib.rs index e05f96f1f0fa..d2993af7f30a 100644 --- a/tests/unit/script/lib.rs +++ b/tests/unit/script/lib.rs @@ -7,7 +7,7 @@ extern crate msg; extern crate script; -extern crate url; +extern crate servo_url; #[cfg(test)] mod origin; #[cfg(all(test, target_pointer_width = "64"))] mod size_of; diff --git a/tests/unit/script/origin.rs b/tests/unit/script/origin.rs index 247a31891eb0..6357587da893 100644 --- a/tests/unit/script/origin.rs +++ b/tests/unit/script/origin.rs @@ -3,33 +3,33 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use script::origin::Origin; -use url::Url; +use servo_url::ServoUrl; #[test] fn same_origin() { - let a = Origin::new(&Url::parse("http://example.com/a.html").unwrap()); - let b = Origin::new(&Url::parse("http://example.com/b.html").unwrap()); + let a = Origin::new(&ServoUrl::parse("http://example.com/a.html").unwrap()); + let b = Origin::new(&ServoUrl::parse("http://example.com/b.html").unwrap()); assert!(a.same_origin(&b)); assert_eq!(a.is_scheme_host_port_tuple(), true); } #[test] fn identical_origin() { - let a = Origin::new(&Url::parse("http://example.com/a.html").unwrap()); + let a = Origin::new(&ServoUrl::parse("http://example.com/a.html").unwrap()); assert!(a.same_origin(&a)); } #[test] fn cross_origin() { - let a = Origin::new(&Url::parse("http://example.com/a.html").unwrap()); - let b = Origin::new(&Url::parse("http://example.org/b.html").unwrap()); + let a = Origin::new(&ServoUrl::parse("http://example.com/a.html").unwrap()); + let b = Origin::new(&ServoUrl::parse("http://example.org/b.html").unwrap()); assert!(!a.same_origin(&b)); } #[test] fn alias_same_origin() { - let a = Origin::new(&Url::parse("http://example.com/a.html").unwrap()); - let b = Origin::new(&Url::parse("http://example.com/b.html").unwrap()); + let a = Origin::new(&ServoUrl::parse("http://example.com/a.html").unwrap()); + let b = Origin::new(&ServoUrl::parse("http://example.com/b.html").unwrap()); let c = b.alias(); assert!(a.same_origin(&c)); assert!(b.same_origin(&b)); @@ -39,8 +39,8 @@ fn alias_same_origin() { #[test] fn alias_cross_origin() { - let a = Origin::new(&Url::parse("http://example.com/a.html").unwrap()); - let b = Origin::new(&Url::parse("http://example.org/b.html").unwrap()); + let a = Origin::new(&ServoUrl::parse("http://example.com/a.html").unwrap()); + let b = Origin::new(&ServoUrl::parse("http://example.org/b.html").unwrap()); let c = b.alias(); assert!(!a.same_origin(&c)); assert!(b.same_origin(&c)); diff --git a/tests/unit/style/Cargo.toml b/tests/unit/style/Cargo.toml index 8e6c99670d73..9ee0c5b17d67 100644 --- a/tests/unit/style/Cargo.toml +++ b/tests/unit/style/Cargo.toml @@ -21,5 +21,5 @@ html5ever-atoms = "0.1" servo_atoms = {path = "../../../components/atoms"} style = {path = "../../../components/style"} style_traits = {path = "../../../components/style_traits"} -url = {version = "1.2", features = ["heap_size"]} +servo_url = {path = "../../../components/url"} util = {path = "../../../components/util"} diff --git a/tests/unit/style/lib.rs b/tests/unit/style/lib.rs index 09ff57605c7e..7367c5a0d8b2 100644 --- a/tests/unit/style/lib.rs +++ b/tests/unit/style/lib.rs @@ -15,9 +15,9 @@ extern crate parking_lot; extern crate rustc_serialize; extern crate selectors; #[macro_use] extern crate servo_atoms; +extern crate servo_url; extern crate style; extern crate style_traits; -extern crate url; extern crate util; mod atomic_refcell; diff --git a/tests/unit/style/media_queries.rs b/tests/unit/style/media_queries.rs index 596281280829..ced55a27f603 100644 --- a/tests/unit/style/media_queries.rs +++ b/tests/unit/style/media_queries.rs @@ -5,6 +5,7 @@ use app_units::Au; use cssparser::{Parser, SourcePosition}; use euclid::size::TypedSize2D; +use servo_url::ServoUrl; use std::borrow::ToOwned; use style::Atom; use style::error_reporting::ParseErrorReporter; @@ -12,7 +13,6 @@ use style::media_queries::*; use style::parser::ParserContextExtraData; use style::stylesheets::{Stylesheet, Origin, CssRule}; use style::values::specified; -use url::Url; pub struct CSSErrorReporterTest; @@ -25,7 +25,7 @@ impl ParseErrorReporter for CSSErrorReporterTest { } fn test_media_rule(css: &str, callback: F) where F: Fn(&MediaList, &str) { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let stylesheet = Stylesheet::from_str(css, url, Origin::Author, Box::new(CSSErrorReporterTest), ParserContextExtraData::default()); let mut rule_count = 0; @@ -48,7 +48,7 @@ fn media_queries(rules: &[CssRule], f: &mut F) where F: FnMut(&MediaList) { } fn media_query_test(device: &Device, css: &str, expected_rule_count: usize) { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let ss = Stylesheet::from_str(css, url, Origin::Author, Box::new(CSSErrorReporterTest), ParserContextExtraData::default()); let mut rule_count = 0; diff --git a/tests/unit/style/parsing/border.rs b/tests/unit/style/parsing/border.rs index 0739cb0eb786..726545267928 100644 --- a/tests/unit/style/parsing/border.rs +++ b/tests/unit/style/parsing/border.rs @@ -4,16 +4,16 @@ use cssparser::Parser; use media_queries::CSSErrorReporterTest; +use servo_url::ServoUrl; use style::parser::ParserContext; use style::properties::longhands::{border_image_outset, border_image_repeat, border_image_slice}; use style::properties::longhands::{border_image_source, border_image_width}; use style::properties::shorthands::border_image; use style::stylesheets::Origin; -use url::Url; #[test] fn border_image_shorhand_should_parse_when_all_properties_specified() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("linear-gradient(red, blue) 30 30% 45 fill / 20px 40px / 10px \ round stretch"); @@ -29,7 +29,7 @@ fn border_image_shorhand_should_parse_when_all_properties_specified() { #[test] fn border_image_shorhand_should_parse_without_width() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("linear-gradient(red, blue) 30 30% 45 fill / / 10px round stretch"); let result = border_image::parse_value(&context, &mut parser).unwrap(); @@ -44,7 +44,7 @@ fn border_image_shorhand_should_parse_without_width() { #[test] fn border_image_shorhand_should_parse_without_outset() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("linear-gradient(red, blue) 30 30% 45 fill / 20px 40px round"); let result = border_image::parse_value(&context, &mut parser).unwrap(); @@ -59,7 +59,7 @@ fn border_image_shorhand_should_parse_without_outset() { #[test] fn border_image_shorhand_should_parse_without_width_or_outset() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("linear-gradient(red, blue) 30 30% 45 fill round"); let result = border_image::parse_value(&context, &mut parser).unwrap(); @@ -74,7 +74,7 @@ fn border_image_shorhand_should_parse_without_width_or_outset() { #[test] fn border_image_shorhand_should_parse_with_just_source() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("linear-gradient(red, blue)"); let result = border_image::parse_value(&context, &mut parser).unwrap(); diff --git a/tests/unit/style/parsing/font.rs b/tests/unit/style/parsing/font.rs index 178a43f6e9b6..02d043bcd075 100644 --- a/tests/unit/style/parsing/font.rs +++ b/tests/unit/style/parsing/font.rs @@ -4,13 +4,13 @@ use cssparser::Parser; use media_queries::CSSErrorReporterTest; +use servo_url::ServoUrl; use style::parser::ParserContext; use style::properties::longhands::font_feature_settings; use style::properties::longhands::font_feature_settings::computed_value; use style::properties::longhands::font_feature_settings::computed_value::FeatureTagValue; use style::stylesheets::Origin; use style_traits::ToCss; -use url::Url; #[test] fn font_feature_settings_should_parse_properly() { @@ -52,7 +52,7 @@ fn font_feature_settings_should_parse_properly() { #[test] fn font_feature_settings_should_throw_on_bad_input() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut empty = Parser::new(""); diff --git a/tests/unit/style/parsing/image.rs b/tests/unit/style/parsing/image.rs index d6d8651381e9..5565a72dc3e9 100644 --- a/tests/unit/style/parsing/image.rs +++ b/tests/unit/style/parsing/image.rs @@ -8,7 +8,6 @@ use style::parser::ParserContext; use style::stylesheets::Origin; use style::values::specified::image::*; use style_traits::ToCss; -use url::Url; #[test] fn test_linear_gradient() { diff --git a/tests/unit/style/parsing/inherited_text.rs b/tests/unit/style/parsing/inherited_text.rs index bb57e3443004..51c801b6f91f 100644 --- a/tests/unit/style/parsing/inherited_text.rs +++ b/tests/unit/style/parsing/inherited_text.rs @@ -6,7 +6,6 @@ use cssparser::Parser; use media_queries::CSSErrorReporterTest; use style::parser::ParserContext; use style::stylesheets::Origin; -use url::Url; #[test] fn text_emphasis_style_longhand_should_parse_properly() { diff --git a/tests/unit/style/parsing/mask.rs b/tests/unit/style/parsing/mask.rs index bb4729cdf9b4..98abe602e46c 100644 --- a/tests/unit/style/parsing/mask.rs +++ b/tests/unit/style/parsing/mask.rs @@ -4,16 +4,16 @@ use cssparser::Parser; use media_queries::CSSErrorReporterTest; +use servo_url::ServoUrl; use style::parser::ParserContext; use style::properties::longhands::{mask_clip, mask_composite, mask_image, mask_mode}; use style::properties::longhands::{mask_origin, mask_position, mask_repeat, mask_size}; use style::properties::shorthands::mask; use style::stylesheets::Origin; -use url::Url; #[test] fn mask_shorthand_should_parse_all_available_properties_when_specified() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("url(\"http://servo/test.png\") luminance 7px 4px / 70px 50px \ repeat-x padding-box border-box subtract"); @@ -31,7 +31,7 @@ fn mask_shorthand_should_parse_all_available_properties_when_specified() { #[test] fn mask_shorthand_should_parse_when_some_fields_set() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("14px 40px repeat-y"); let result = mask::parse_value(&context, &mut parser).unwrap(); @@ -59,7 +59,7 @@ fn mask_shorthand_should_parse_when_some_fields_set() { #[test] fn mask_shorthand_should_parse_position_and_size_correctly() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("7px 4px"); let result = mask::parse_value(&context, &mut parser).unwrap(); @@ -81,7 +81,7 @@ fn mask_shorthand_should_parse_position_and_size_correctly() { #[test] fn mask_shorthand_should_parse_origin_and_clip_correctly() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("padding-box content-box"); let result = mask::parse_value(&context, &mut parser).unwrap(); @@ -104,7 +104,7 @@ fn mask_shorthand_should_parse_origin_and_clip_correctly() { #[test] fn mask_shorthand_should_not_parse_when_mode_specified_but_image_not() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new("luminance 7px 4px repeat-x padding"); assert!(mask::parse_value(&context, &mut parser).is_err()); diff --git a/tests/unit/style/parsing/mod.rs b/tests/unit/style/parsing/mod.rs index 47a52d470f64..5f7735e5df2d 100644 --- a/tests/unit/style/parsing/mod.rs +++ b/tests/unit/style/parsing/mod.rs @@ -36,7 +36,7 @@ macro_rules! assert_roundtrip_with_context { assert_roundtrip_with_context!($fun, $string, $string); }; ($fun:expr,$input:expr, $output:expr) => { - let url = Url::parse("http://localhost").unwrap(); + let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); let mut parser = Parser::new($input); let parsed = $fun(&context, &mut parser) @@ -55,7 +55,7 @@ macro_rules! assert_roundtrip_with_context { macro_rules! parse_longhand { ($name:ident, $s:expr) => {{ - let url = Url::parse("http://localhost").unwrap(); + let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); $name::parse(&context, &mut Parser::new($s)).unwrap() }}; diff --git a/tests/unit/style/stylesheets.rs b/tests/unit/style/stylesheets.rs index 2efd471b99f0..978d012c2d73 100644 --- a/tests/unit/style/stylesheets.rs +++ b/tests/unit/style/stylesheets.rs @@ -8,6 +8,7 @@ use media_queries::CSSErrorReporterTest; use parking_lot::RwLock; use selectors::parser::*; use servo_atoms::Atom; +use servo_url::ServoUrl; use std::borrow::ToOwned; use std::sync::Arc; use std::sync::Mutex; @@ -19,7 +20,6 @@ use style::properties::Importance; use style::properties::longhands::animation_play_state; use style::stylesheets::{Stylesheet, NamespaceRule, CssRule, StyleRule, KeyframesRule, Origin}; use style::values::specified::{LengthOrPercentageOrAuto, Percentage}; -use url::Url; #[test] fn test_parse_stylesheet() { @@ -48,7 +48,7 @@ fn test_parse_stylesheet() { animation-play-state: running; /* … except animation-play-state */ } }"; - let url = Url::parse("about::test").unwrap(); + let url = ServoUrl::parse("about::test").unwrap(); let stylesheet = Stylesheet::from_str(css, url, Origin::UserAgent, Box::new(CSSErrorReporterTest), ParserContextExtraData::default()); @@ -315,7 +315,7 @@ fn test_report_error_stylesheet() { invalid: true; } "; - let url = Url::parse("about::test").unwrap(); + let url = ServoUrl::parse("about::test").unwrap(); let error_reporter = Box::new(CSSInvalidErrorReporterTest::new()); let errors = error_reporter.errors.clone(); diff --git a/tests/unit/style/viewport.rs b/tests/unit/style/viewport.rs index bde97310e410..97e527395d4d 100644 --- a/tests/unit/style/viewport.rs +++ b/tests/unit/style/viewport.rs @@ -6,6 +6,7 @@ use cssparser::Parser; use euclid::scale_factor::ScaleFactor; use euclid::size::TypedSize2D; use media_queries::CSSErrorReporterTest; +use servo_url::ServoUrl; use style::error_reporting::ParseErrorReporter; use style::media_queries::{Device, MediaType}; use style::parser::{ParserContext, ParserContextExtraData}; @@ -15,13 +16,12 @@ use style::values::specified::LengthOrPercentageOrAuto::{self, Auto}; use style::values::specified::ViewportPercentageLength::Vw; use style::viewport::*; use style_traits::viewport::*; -use url::Url; macro_rules! stylesheet { ($css:expr, $origin:ident, $error_reporter:expr) => { Box::new(Stylesheet::from_str( $css, - Url::parse("http://localhost").unwrap(), + ServoUrl::parse("http://localhost").unwrap(), Origin::$origin, $error_reporter, ParserContextExtraData::default() @@ -279,7 +279,7 @@ fn multiple_stylesheets_cascading() { #[test] fn constrain_viewport() { - let url = Url::parse("http://localhost").unwrap(); + let url = ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest)); macro_rules! from_css { diff --git a/tests/unit/stylo/Cargo.toml b/tests/unit/stylo/Cargo.toml index 4da472583842..796c351426d6 100644 --- a/tests/unit/stylo/Cargo.toml +++ b/tests/unit/stylo/Cargo.toml @@ -22,7 +22,7 @@ log = {version = "0.3.5", features = ["release_max_level_info"]} num_cpus = "1.1.0" parking_lot = "0.3" selectors = "0.14" -url = "1.2" +servo_url = {path = "../../../components/url"} style_traits = {path = "../../../components/style_traits"} geckoservo = {path = "../../../ports/geckolib"} style = {path = "../../../components/style", features = ["gecko"]} diff --git a/tests/unit/stylo/lib.rs b/tests/unit/stylo/lib.rs index 03df4957b9aa..497d1366cb99 100644 --- a/tests/unit/stylo/lib.rs +++ b/tests/unit/stylo/lib.rs @@ -10,9 +10,9 @@ extern crate geckoservo; extern crate libc; #[macro_use] extern crate log; extern crate parking_lot; +extern crate servo_url; extern crate style; extern crate style_traits; -extern crate url; mod sanity_checks;