Skip to content

Commit

Permalink
Script: removed a few opts::get()
Browse files Browse the repository at this point in the history
  • Loading branch information
oneturkmen committed Jun 27, 2019
1 parent 5720531 commit 4256928
Show file tree
Hide file tree
Showing 17 changed files with 238 additions and 45 deletions.
2 changes: 1 addition & 1 deletion components/config/opts.rs
Expand Up @@ -66,7 +66,7 @@ pub struct Opts {

pub output_file: Option<String>,

/// Replace unpaires surrogates in DOM strings with U+FFFD.
/// Replace unpaired surrogates in DOM strings with U+FFFD.
/// See <https://github.com/servo/servo/issues/6564>
pub replace_surrogates: bool,

Expand Down
11 changes: 11 additions & 0 deletions components/constellation/pipeline.rs
Expand Up @@ -559,6 +559,17 @@ impl UnprivilegedPipelineContent {
layout_is_busy: layout_thread_busy_flag.clone(),
},
self.load_data.clone(),
self.opts.profile_script_events,
self.opts.print_pwm,
self.opts.relayout_event,
self.opts.output_file.is_some() ||
self.opts.exit_after_load ||
self.opts.webdriver_port.is_some(),
self.opts.unminify_js,
self.opts.userscripts,
self.opts.headless,
self.opts.replace_surrogates,
self.opts.user_agent,
);

LTF::create(
Expand Down
3 changes: 3 additions & 0 deletions components/script/dom/bindings/trace.rs
Expand Up @@ -109,6 +109,7 @@ use servo_media::streams::MediaStreamType;
use servo_media::webrtc::WebRtcController;
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use smallvec::SmallVec;
use std::borrow::Cow;
use std::cell::{Cell, RefCell, UnsafeCell};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash};
Expand Down Expand Up @@ -164,6 +165,8 @@ unsafe_no_jsmanaged_fields!(TexDataType, TexFormat);

unsafe_no_jsmanaged_fields!(*mut JobQueue);

unsafe_no_jsmanaged_fields!(Cow<'static, str>);

/// Trace a `JSVal`.
pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>) {
unsafe {
Expand Down
27 changes: 20 additions & 7 deletions components/script/dom/characterdata.rs
Expand Up @@ -24,7 +24,6 @@ use crate::dom::processinginstruction::ProcessingInstruction;
use crate::dom::text::Text;
use crate::dom::virtualmethods::vtable_for;
use dom_struct::dom_struct;
use servo_config::opts;
use std::cell::Ref;

// https://dom.spec.whatwg.org/#characterdata
Expand Down Expand Up @@ -122,11 +121,16 @@ impl CharacterDataMethods for CharacterData {

// https://dom.spec.whatwg.org/#dom-characterdata-substringdata
fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
let replace_surrogates = self
.upcast::<Node>()
.owner_doc()
.window()
.replace_surrogates();
let data = self.data.borrow();
// Step 1.
let mut substring = String::new();
let remaining;
match split_at_utf16_code_unit_offset(&data, offset) {
match split_at_utf16_code_unit_offset(&data, offset, replace_surrogates) {
Ok((_, astral, s)) => {
// As if we had split the UTF-16 surrogate pair in half
// and then transcoded that to UTF-8 lossily,
Expand All @@ -139,7 +143,7 @@ impl CharacterDataMethods for CharacterData {
// Step 2.
Err(()) => return Err(Error::IndexSize),
}
match split_at_utf16_code_unit_offset(remaining, count) {
match split_at_utf16_code_unit_offset(remaining, count, replace_surrogates) {
// Steps 3.
Err(()) => substring = substring + remaining,
// Steps 4.
Expand Down Expand Up @@ -176,11 +180,16 @@ impl CharacterDataMethods for CharacterData {
fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult {
let mut new_data;
{
let replace_surrogates = self
.upcast::<Node>()
.owner_doc()
.window()
.replace_surrogates();
let data = self.data.borrow();
let prefix;
let replacement_before;
let remaining;
match split_at_utf16_code_unit_offset(&data, offset) {
match split_at_utf16_code_unit_offset(&data, offset, replace_surrogates) {
Ok((p, astral, r)) => {
prefix = p;
// As if we had split the UTF-16 surrogate pair in half
Expand All @@ -194,7 +203,7 @@ impl CharacterDataMethods for CharacterData {
};
let replacement_after;
let suffix;
match split_at_utf16_code_unit_offset(remaining, count) {
match split_at_utf16_code_unit_offset(remaining, count, replace_surrogates) {
// Steps 3.
Err(()) => {
replacement_after = "";
Expand Down Expand Up @@ -305,7 +314,11 @@ impl LayoutCharacterDataHelpers for LayoutDom<CharacterData> {
/// Note that the third variant is only ever returned when the `-Z replace-surrogates`
/// command-line option is specified.
/// When it *would* be returned but the option is *not* specified, this function panics.
fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> {
fn split_at_utf16_code_unit_offset(
s: &str,
offset: u32,
replace_surrogates: bool,
) -> Result<(&str, Option<char>, &str), ()> {
let mut code_units = 0;
for (i, c) in s.char_indices() {
if code_units == offset {
Expand All @@ -315,7 +328,7 @@ fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option
code_units += 1;
if c > '\u{FFFF}' {
if code_units == offset {
if opts::get().replace_surrogates {
if replace_surrogates {
debug_assert_eq!(c.len_utf8(), 4);
return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..]));
}
Expand Down
2 changes: 2 additions & 0 deletions components/script/dom/dissimilaroriginwindow.rs
Expand Up @@ -62,6 +62,8 @@ impl DissimilarOriginWindow {
// FIXME(nox): The microtask queue is probably not important
// here, but this whole DOM interface is a hack anyway.
global_to_clone_from.microtask_queue().clone(),
global_to_clone_from.is_headless(),
global_to_clone_from.get_user_agent(),
),
window_proxy: Dom::from_ref(window_proxy),
location: Default::default(),
Expand Down
19 changes: 19 additions & 0 deletions components/script/dom/globalscope.rs
Expand Up @@ -58,6 +58,7 @@ use profile_traits::{mem as profile_mem, time as profile_time};
use script_traits::{MsDuration, ScriptToConstellationChan, TimerEvent};
use script_traits::{TimerEventId, TimerSchedulerMsg, TimerSource};
use servo_url::{MutableOrigin, ServoUrl};
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
Expand Down Expand Up @@ -157,6 +158,12 @@ pub struct GlobalScope {
/// <https://html.spec.whatwg.org/multipage/#outstanding-rejected-promises-weak-set>
#[ignore_malloc_size_of = "mozjs"]
consumed_rejections: DomRefCell<Vec<Box<Heap<*mut JSObject>>>>,

/// True if headless mode.
is_headless: bool,

/// An optional string allowing the user agent to be set for testing.
user_agent: Cow<'static, str>,
}

impl GlobalScope {
Expand All @@ -171,6 +178,8 @@ impl GlobalScope {
timer_event_chan: IpcSender<TimerEvent>,
origin: MutableOrigin,
microtask_queue: Rc<MicrotaskQueue>,
is_headless: bool,
user_agent: Cow<'static, str>,
) -> Self {
Self {
eventtarget: EventTarget::new_inherited(),
Expand All @@ -193,6 +202,8 @@ impl GlobalScope {
event_source_tracker: DOMTracker::new(),
uncaught_rejections: Default::default(),
consumed_rejections: Default::default(),
is_headless,
user_agent,
}
}

Expand Down Expand Up @@ -799,6 +810,14 @@ impl GlobalScope {
}
unreachable!();
}

pub fn is_headless(&self) -> bool {
self.is_headless
}

pub fn get_user_agent(&self) -> Cow<'static, str> {
self.user_agent.clone()
}
}

fn timestamp_in_ms(time: Timespec) -> u64 {
Expand Down
3 changes: 1 addition & 2 deletions components/script/dom/htmlscriptelement.rs
Expand Up @@ -38,7 +38,6 @@ use net_traits::request::{
use net_traits::{FetchMetadata, FetchResponseListener, Metadata, NetworkError};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use servo_atoms::Atom;
use servo_config::opts;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::fs::File;
Expand Down Expand Up @@ -533,7 +532,7 @@ impl HTMLScriptElement {
}

fn unminify_js(&self, script: &mut ClassicScript) {
if !opts::get().unminify_js {
if !self.parser_document.window().unminify_js() {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion components/script/dom/navigator.rs
Expand Up @@ -103,7 +103,7 @@ impl NavigatorMethods for Navigator {

// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
navigatorinfo::UserAgent(self.global().get_user_agent())
}

// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
Expand Down
6 changes: 3 additions & 3 deletions components/script/dom/navigatorinfo.rs
Expand Up @@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::str::DOMString;
use servo_config::opts;
use std::borrow::Cow;

pub fn Product() -> DOMString {
DOMString::from("Gecko")
Expand Down Expand Up @@ -53,8 +53,8 @@ pub fn Platform() -> DOMString {
DOMString::from("iOS")
}

pub fn UserAgent() -> DOMString {
DOMString::from(&*opts::get().user_agent)
pub fn UserAgent(user_agent: Cow<'static, str>) -> DOMString {
DOMString::from(&*user_agent)
}

pub fn AppVersion() -> DOMString {
Expand Down
30 changes: 15 additions & 15 deletions components/script/dom/permissions.rs
Expand Up @@ -21,8 +21,6 @@ use dom_struct::dom_struct;
use js::conversions::ConversionResult;
use js::jsapi::{JSContext, JSObject};
use js::jsval::{ObjectValue, UndefinedValue};
#[cfg(target_os = "linux")]
use servo_config::opts;
use servo_config::pref;
use std::rc::Rc;
#[cfg(target_os = "linux")]
Expand Down Expand Up @@ -269,14 +267,15 @@ impl PermissionAlgorithm for Permissions {
// Step 3.
PermissionState::Prompt => {
let perm_name = status.get_query();
// https://w3c.github.io/permissions/#request-permission-to-use (Step 3 - 4)
let state = prompt_user(&format!(
"{} {} ?",
REQUEST_DIALOG_MESSAGE,
perm_name.clone()
));

let globalscope = GlobalScope::current().expect("No current global object");

// https://w3c.github.io/permissions/#request-permission-to-use (Step 3 - 4)
let state = prompt_user(
&format!("{} {} ?", REQUEST_DIALOG_MESSAGE, perm_name.clone()),
globalscope.is_headless(),
);

globalscope
.as_window()
.permission_state_invocation_results()
Expand Down Expand Up @@ -322,10 +321,11 @@ pub fn get_descriptor_permission_state(
.permission_state_invocation_results()
.borrow_mut()
.remove(&permission_name.to_string());
prompt_user(&format!(
"The {} {}",
permission_name, NONSECURE_DIALOG_MESSAGE
))

prompt_user(
&format!("The {} {}", permission_name, NONSECURE_DIALOG_MESSAGE),
settings.is_headless(),
)
}
};

Expand All @@ -351,8 +351,8 @@ pub fn get_descriptor_permission_state(
}

#[cfg(target_os = "linux")]
fn prompt_user(message: &str) -> PermissionState {
if opts::get().headless {
fn prompt_user(message: &str, headless: bool) -> PermissionState {
if headless {
return PermissionState::Denied;
}
match tinyfiledialogs::message_box_yes_no(
Expand All @@ -367,7 +367,7 @@ fn prompt_user(message: &str) -> PermissionState {
}

#[cfg(not(target_os = "linux"))]
fn prompt_user(_message: &str) -> PermissionState {
fn prompt_user(_message: &str, _headless: bool) -> PermissionState {
// TODO popup only supported on linux
PermissionState::Denied
}
Expand Down
5 changes: 2 additions & 3 deletions components/script/dom/userscripts.rs
Expand Up @@ -8,17 +8,16 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlheadelement::HTMLHeadElement;
use crate::dom::node::document_from_node;
use js::jsval::UndefinedValue;
use servo_config::opts;
use std::fs::{read_dir, File};
use std::io::Read;
use std::path::PathBuf;

pub fn load_script(head: &HTMLHeadElement) {
let path_str = match opts::get().userscripts.clone() {
let doc = document_from_node(head);
let path_str = match doc.window().get_userscripts_path() {
Some(p) => p,
None => return,
};
let doc = document_from_node(head);
let win = Trusted::new(doc.window());
doc.add_delayed_task(task!(UserScriptExecute: move || {
let win = win.root();
Expand Down

0 comments on commit 4256928

Please sign in to comment.