servo: Merge #12178 - Refactor `util::prefs` operations to be methods on static struct (from frewsxcv:prefs); r=emilio

<!-- Please describe your changes on the following line: -->

---
<!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `__` with appropriate data: -->
- [X] `./mach build -d` does not report any errors
- [X] `./mach test-tidy` does not report any errors
- [ ] These changes fix #__ (github issue number if applicable).

<!-- Either: -->
- [ ] There are tests for these changes OR
- [X] These changes do not require tests because _____

<!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. -->

Source-Repo: https://github.com/servo/servo
Source-Revision: b0a8ce5341f5148e36523fee0b0fcbc2684c0a68
This commit is contained in:
Corey Farwell 2016-07-03 08:19:04 -07:00
Родитель 9433a65299
Коммит df29454b47
30 изменённых файлов: 167 добавлений и 163 удалений

Просмотреть файл

@ -49,8 +49,9 @@ use time::{precise_time_ns, precise_time_s};
use touch::{TouchHandler, TouchAction};
use url::Url;
use util::geometry::{PagePx, ScreenPx, ViewportPx};
use util::opts;
use util::prefs::PREFS;
use util::print_tree::PrintTree;
use util::{opts, prefs};
use webrender;
use webrender_traits::{self, ScrollEventPhase};
use windowing::{self, MouseWindowEvent, WindowEvent, WindowMethods, WindowNavigateMsg};
@ -1871,7 +1872,7 @@ impl<Window: WindowMethods> IOCompositor<Window> {
fn on_touchpad_pressure_event(&self, cursor: TypedPoint2D<DevicePixel, f32>, pressure: f32,
phase: TouchpadPressurePhase) {
if let Some(true) = prefs::get_pref("dom.forcetouch.enabled").as_boolean() {
if let Some(true) = PREFS.get("dom.forcetouch.enabled").as_boolean() {
match self.find_topmost_layer_at_point(cursor / self.scene.scale) {
Some(result) => result.layer.send_touchpad_pressure_event(self, result.point, pressure, phase),
None => {},

Просмотреть файл

@ -60,7 +60,7 @@ use timer_scheduler::TimerScheduler;
use url::Url;
use util::geometry::PagePx;
use util::opts;
use util::prefs::mozbrowser_enabled;
use util::prefs::PREFS;
use util::thread::spawn_named;
use webrender_traits;
@ -1146,7 +1146,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
}
fn handle_alert(&mut self, pipeline_id: PipelineId, message: String, sender: IpcSender<bool>) {
let display_alert_dialog = if mozbrowser_enabled() {
let display_alert_dialog = if PREFS.is_mozbrowser_enabled() {
let parent_pipeline_info = self.pipelines.get(&pipeline_id).and_then(|source| source.parent_info);
if let Some(_) = parent_pipeline_info {
let root_pipeline_id = self.root_frame_id
@ -1457,7 +1457,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
containing_pipeline_id: PipelineId,
subpage_id: SubpageId,
event: MozBrowserEvent) {
assert!(mozbrowser_enabled());
assert!(PREFS.is_mozbrowser_enabled());
// Find the script channel for the given parent pipeline,
// and pass the event to that script thread.
@ -2046,7 +2046,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
if let Some(pipeline_id) = rng.choose(&*pipeline_ids) {
if let Some(pipeline) = self.pipelines.get(pipeline_id) {
// Don't kill the mozbrowser pipeline
if mozbrowser_enabled() && pipeline.parent_info.is_none() {
if PREFS.is_mozbrowser_enabled() && pipeline.parent_info.is_none() {
info!("Not closing mozbrowser pipeline {}.", pipeline_id);
} else {
// Note that we deliberately do not do any of the tidying up
@ -2132,7 +2132,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowserlocationchange
// Note that this is a no-op if the pipeline is not a mozbrowser iframe
fn trigger_mozbrowserlocationchange(&self, pipeline_id: PipelineId) {
if !mozbrowser_enabled() { return; }
if !PREFS.is_mozbrowser_enabled() { return; }
let event_info = self.pipelines.get(&pipeline_id).and_then(|pipeline| {
pipeline.parent_info.map(|(containing_pipeline_id, subpage_id, frame_type)| {
@ -2158,7 +2158,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsererror
// Note that this does not require the pipeline to be an immediate child of the root
fn trigger_mozbrowsererror(&self, pipeline_id: PipelineId, reason: String, backtrace: String) {
if !mozbrowser_enabled() { return; }
if !PREFS.is_mozbrowser_enabled() { return; }
let ancestor_info = self.get_mozbrowser_ancestor_info(pipeline_id);

Просмотреть файл

@ -36,7 +36,7 @@ use util;
use util::geometry::{PagePx, ViewportPx};
use util::ipc::OptionalIpcSender;
use util::opts::{self, Opts};
use util::prefs::{self, Pref};
use util::prefs::{PREFS, Pref};
use webrender_traits;
pub enum ChildProcess {
@ -234,7 +234,7 @@ impl Pipeline {
panic_chan: state.panic_chan,
script_port: script_port,
opts: (*opts::get()).clone(),
prefs: prefs::get_cloned(),
prefs: PREFS.cloned(),
layout_to_paint_chan: layout_to_paint_chan,
pipeline_port: pipeline_port,
pipeline_namespace_id: state.pipeline_namespace_id,
@ -378,7 +378,7 @@ impl Pipeline {
pub fn trigger_mozbrowser_event(&self,
subpage_id: SubpageId,
event: MozBrowserEvent) {
assert!(prefs::mozbrowser_enabled());
assert!(PREFS.is_mozbrowser_enabled());
let event = ConstellationControlMsg::MozBrowserEvent(self.id,
subpage_id,

Просмотреть файл

@ -24,7 +24,7 @@ use string_cache::Atom;
use style::font_face::{EffectiveSources, Source};
use style::properties::longhands::font_family::computed_value::FontFamily;
use url::Url;
use util::prefs;
use util::prefs::PREFS;
use util::thread::spawn_named;
use webrender_traits;
@ -456,7 +456,7 @@ impl FontCacheThread {
// derived from http://stackoverflow.com/a/10864297/3830
fn is_supported_font_type(toplevel: &TopLevel, sublevel: &SubLevel) -> bool {
if !prefs::get_pref("network.mime.sniff").as_boolean().unwrap_or(false) {
if !PREFS.get("network.mime.sniff").as_boolean().unwrap_or(false) {
return true;
}

Просмотреть файл

@ -51,7 +51,7 @@ use time::Tm;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use tinyfiledialogs;
use url::{Url, Position};
use util::prefs;
use util::prefs::PREFS;
use util::thread::spawn_named;
use uuid;
@ -860,7 +860,7 @@ pub fn load<A, B>(load_data: &LoadData,
user_agent: String,
cancel_listener: &CancellationListener)
-> Result<StreamedResponse, LoadError> where A: HttpRequest + 'static, B: UIProvider {
let max_redirects = prefs::get_pref("network.http.redirection-limit").as_i64().unwrap() as u32;
let max_redirects = PREFS.get("network.http.redirection-limit").as_i64().unwrap() as u32;
let mut iters = 0;
// URL of the document being loaded, as seen by all the higher-level code.
let mut doc_url = load_data.url.clone();

Просмотреть файл

@ -48,7 +48,7 @@ use std::sync::{Arc, RwLock};
use storage_thread::StorageThreadFactory;
use url::Url;
use util::opts;
use util::prefs;
use util::prefs::PREFS;
use util::thread::spawn_named;
use websocket_loader;
@ -106,7 +106,7 @@ pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadat
classifier: Arc<MIMEClassifier>, partial_body: &[u8],
context: LoadContext)
-> Result<ProgressSender, ()> {
if prefs::get_pref("network.mime.sniff").as_boolean().unwrap_or(false) {
if PREFS.get("network.mime.sniff").as_boolean().unwrap_or(false) {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut no_sniff = NoSniffFlag::OFF;
let mut check_for_apache_bug = ApacheBugFlag::OFF;

Просмотреть файл

@ -2250,7 +2250,7 @@ class CGConstructorEnabled(CGAbstractMethod):
pref = iface.getExtendedAttribute("Pref")
if pref:
assert isinstance(pref, list) and len(pref) == 1
conditions.append('prefs::get_pref("%s").as_boolean().unwrap_or(false)' % pref[0])
conditions.append('PREFS.get("%s").as_boolean().unwrap_or(false)' % pref[0])
func = iface.getExtendedAttribute("Func")
if func:
assert isinstance(func, list) and len(func) == 1
@ -5605,7 +5605,7 @@ class CGBindingRoot(CGThing):
'dom::browsingcontext::BrowsingContext',
'mem::heap_size_of_raw_self_and_children',
'libc',
'util::prefs',
'util::prefs::PREFS',
'script_runtime::{store_panic_result, maybe_take_panic_result}',
'std::borrow::ToOwned',
'std::cmp',

Просмотреть файл

@ -5,7 +5,7 @@
//! Machinery to conditionally expose things.
use js::jsapi::{HandleObject, JSContext};
use util::prefs::get_pref;
use util::prefs::PREFS;
/// A container with a condition.
pub struct Guard<T: Clone + Copy> {
@ -47,7 +47,7 @@ pub enum Condition {
impl Condition {
unsafe fn is_satisfied(&self, cx: *mut JSContext, obj: HandleObject) -> bool {
match *self {
Condition::Pref(name) => get_pref(name).as_boolean().unwrap_or(false),
Condition::Pref(name) => PREFS.get(name).as_boolean().unwrap_or(false),
Condition::Func(f) => f(cx, obj),
Condition::Satisfied => true,
}

Просмотреть файл

@ -127,7 +127,7 @@ use style::servo::Stylesheet;
use time;
use url::Url;
use url::percent_encoding::percent_decode;
use util::prefs::mozbrowser_enabled;
use util::prefs::PREFS;
use util::str::{split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, HeapSizeOf)]
@ -1262,7 +1262,7 @@ impl Document {
}
pub fn trigger_mozbrowser_event(&self, event: MozBrowserEvent) {
if mozbrowser_enabled() {
if PREFS.is_mozbrowser_enabled() {
if let Some((containing_pipeline_id, subpage_id, _)) = self.window.parent_info() {
let event = ConstellationMsg::MozBrowserEvent(containing_pipeline_id,
subpage_id,

Просмотреть файл

@ -29,7 +29,7 @@ use std::default::Default;
use string_cache::Atom;
use style::attr::AttrValue;
use url::Url;
use util::prefs::mozbrowser_enabled;
use util::prefs::PREFS;
#[dom_struct]
pub struct HTMLAnchorElement {
@ -575,7 +575,7 @@ fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<String>) {
// Step 8: navigate to the URL.
if let Some(target) = target {
if mozbrowser_enabled() && !is_current_browsing_context(target.Value()) {
if PREFS.is_mozbrowser_enabled() && !is_current_browsing_context(target.Value()) {
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowseropenwindow
// TODO: referrer and opener
// TODO: should we send the normalized url or the non-normalized href?

Просмотреть файл

@ -48,7 +48,7 @@ use string_cache::Atom;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};
use style::context::ReflowGoal;
use url::Url;
use util::prefs::mozbrowser_enabled;
use util::prefs::PREFS;
use util::servo_version;
bitflags! {
@ -145,7 +145,7 @@ impl HTMLIFrameElement {
.send(ConstellationMsg::ScriptLoadedURLInIFrame(load_info))
.unwrap();
if mozbrowser_enabled() {
if PREFS.is_mozbrowser_enabled() {
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowserloadstart
self.dispatch_mozbrowser_event(MozBrowserEvent::LoadStart);
}
@ -164,7 +164,7 @@ impl HTMLIFrameElement {
// TODO(gw): Support mozbrowser event types that have detail which is not a string.
// See https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API
// for a list of mozbrowser events.
assert!(mozbrowser_enabled());
assert!(PREFS.is_mozbrowser_enabled());
if self.Mozbrowser() {
let window = window_from_node(self);

Просмотреть файл

@ -70,7 +70,7 @@ impl HTMLMetaElement {
}
fn apply_viewport(&self) {
if !::util::prefs::get_pref("layout.viewport.enabled").as_boolean().unwrap_or(false) {
if !::util::prefs::PREFS.get("layout.viewport.enabled").as_boolean().unwrap_or(false) {
return;
}
let element = self.upcast::<Element>();

Просмотреть файл

@ -17,7 +17,7 @@ use dom::uievent::UIEvent;
use dom::window::Window;
use std::cell::Cell;
use std::default::Default;
use util::prefs;
use util::prefs::PREFS;
#[dom_struct]
pub struct MouseEvent {
@ -157,7 +157,7 @@ impl MouseEventMethods for MouseEvent {
// This returns the same result as current gecko.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
fn Which(&self) -> i32 {
if prefs::get_pref("dom.mouseevent.which.enabled").as_boolean().unwrap_or(false) {
if PREFS.get("dom.mouseevent.which.enabled").as_boolean().unwrap_or(false) {
(self.button.get() + 1) as i32
} else {
0

Просмотреть файл

@ -37,7 +37,7 @@ use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use url::Url;
use util::prefs;
use util::prefs::PREFS;
use util::thread::spawn_named;
use util::thread_state;
use util::thread_state::{IN_WORKER, SCRIPT};
@ -225,7 +225,7 @@ impl ServiceWorkerGlobalScope {
scope.mem_profiler_chan().run_with_memory_reporting(|| {
// Service workers are time limited
let sw_lifetime = Instant::now();
let sw_lifetime_timeout = prefs::get_pref("dom.serviceworker.timeout_seconds").as_u64().unwrap();
let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap();
while let Ok(event) = global.receive_event() {
if scope.is_closing() {
break;

Просмотреть файл

@ -29,7 +29,7 @@ use js::jsval::{JSVal, NullValue};
use std::borrow::ToOwned;
use std::ptr;
use std::rc::Rc;
use util::prefs::get_pref;
use util::prefs::PREFS;
#[dom_struct]
pub struct TestBinding {
@ -558,10 +558,10 @@ impl TestBindingMethods for TestBinding {
fn PassVariadicAny(&self, _: *mut JSContext, _: Vec<HandleValue>) {}
fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {}
fn BooleanMozPreference(&self, pref_name: DOMString) -> bool {
get_pref(pref_name.as_ref()).as_boolean().unwrap_or(false)
PREFS.get(pref_name.as_ref()).as_boolean().unwrap_or(false)
}
fn StringMozPreference(&self, pref_name: DOMString) -> DOMString {
get_pref(pref_name.as_ref()).as_string().map(|s| DOMString::from(s)).unwrap_or_else(|| DOMString::new())
PREFS.get(pref_name.as_ref()).as_string().map(|s| DOMString::from(s)).unwrap_or_else(|| DOMString::new())
}
fn PrefControlledAttributeDisabled(&self) -> bool { false }
fn PrefControlledAttributeEnabled(&self) -> bool { false }

Просмотреть файл

@ -96,7 +96,7 @@ use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers
use tinyfiledialogs::{self, MessageBoxIcon};
use url::Url;
use util::geometry::{self, MAX_RECT};
use util::prefs::mozbrowser_enabled;
use util::prefs::PREFS;
use util::str::HTML_SPACE_CHARACTERS;
use util::{breakpoint, opts};
use webdriver_handlers::jsval_to_webdriver;
@ -1581,7 +1581,7 @@ impl Window {
/// Returns whether this window is mozbrowser.
pub fn is_mozbrowser(&self) -> bool {
mozbrowser_enabled() && self.parent_info().is_none()
PREFS.is_mozbrowser_enabled() && self.parent_info().is_none()
}
/// Returns whether mozbrowser is enabled and `obj` has been created
@ -1757,4 +1757,3 @@ fn debug_reflow_events(id: PipelineId, goal: &ReflowGoal, query_type: &ReflowQue
println!("{}", debug_msg);
}

Просмотреть файл

@ -62,7 +62,7 @@ use string_cache::Atom;
use time;
use timers::{OneshotTimerCallback, OneshotTimerHandle};
use url::{Url, Position};
use util::prefs::mozbrowser_enabled;
use util::prefs::PREFS;
#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf)]
enum XMLHttpRequestState {
@ -581,8 +581,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
// story. See https://github.com/servo/servo/issues/9582
if let GlobalRoot::Window(win) = self.global() {
let is_root_pipeline = win.parent_info().is_none();
let is_mozbrowser_enabled = mozbrowser_enabled();
is_root_pipeline && is_mozbrowser_enabled
is_root_pipeline && PREFS.is_mozbrowser_enabled()
} else {
false
}

Просмотреть файл

@ -27,7 +27,7 @@ use std::os;
use std::ptr;
use time::{Tm, now};
use util::opts;
use util::prefs::get_pref;
use util::prefs::PREFS;
use util::thread_state;
/// Common messages used to control the event loops in both the script and the worker
@ -124,30 +124,30 @@ pub unsafe fn new_rt_and_cx() -> Runtime {
// Enable or disable the JITs.
let rt_opts = &mut *RuntimeOptionsRef(runtime.rt());
if let Some(val) = get_pref("js.baseline.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.baseline.enabled").as_boolean() {
rt_opts.set_baseline_(val);
}
if let Some(val) = get_pref("js.ion.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.ion.enabled").as_boolean() {
rt_opts.set_ion_(val);
}
if let Some(val) = get_pref("js.asmjs.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.asmjs.enabled").as_boolean() {
rt_opts.set_asmJS_(val);
}
if let Some(val) = get_pref("js.strict.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.strict.enabled").as_boolean() {
rt_opts.set_extraWarnings_(val);
}
// TODO: handle js.strict.debug.enabled
// TODO: handle js.throw_on_asmjs_validation_failure (needs new Spidermonkey)
if let Some(val) = get_pref("js.native_regexp.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.native_regexp.enabled").as_boolean() {
rt_opts.set_nativeRegExp_(val);
}
if let Some(val) = get_pref("js.parallel_parsing.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.parallel_parsing.enabled").as_boolean() {
JS_SetParallelParsingEnabled(runtime.rt(), val);
}
if let Some(val) = get_pref("js.offthread_compilation_enabled").as_boolean() {
if let Some(val) = PREFS.get("js.offthread_compilation_enabled").as_boolean() {
JS_SetOffthreadIonCompilationEnabled(runtime.rt(), val);
}
if let Some(val) = get_pref("js.baseline.unsafe_eager_compilation.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.baseline.unsafe_eager_compilation.enabled").as_boolean() {
let trigger: i32 = if val {
0
} else {
@ -157,7 +157,7 @@ pub unsafe fn new_rt_and_cx() -> Runtime {
JSJitCompilerOption::JSJITCOMPILER_BASELINE_WARMUP_TRIGGER,
trigger as u32);
}
if let Some(val) = get_pref("js.ion.unsafe_eager_compilation.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.ion.unsafe_eager_compilation.enabled").as_boolean() {
let trigger: i64 = if val {
0
} else {
@ -171,14 +171,14 @@ pub unsafe fn new_rt_and_cx() -> Runtime {
// TODO: handle js.asyncstack.enabled (needs new Spidermonkey)
// TODO: handle js.throw_on_debugee_would_run (needs new Spidermonkey)
// TODO: handle js.dump_stack_on_debugee_would_run (needs new Spidermonkey)
if let Some(val) = get_pref("js.werror.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.werror.enabled").as_boolean() {
rt_opts.set_werror_(val);
}
// TODO: handle js.shared_memory.enabled
if let Some(val) = get_pref("js.mem.high_water_mark").as_i64() {
if let Some(val) = PREFS.get("js.mem.high_water_mark").as_i64() {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_MALLOC_BYTES, val as u32 * 1024 * 1024);
}
if let Some(val) = get_pref("js.mem.max").as_i64() {
if let Some(val) = PREFS.get("js.mem.max").as_i64() {
let max = if val <= 0 || val >= 0x1000 {
-1
} else {
@ -187,8 +187,8 @@ pub unsafe fn new_rt_and_cx() -> Runtime {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_BYTES, max as u32);
}
// NOTE: This is disabled above, so enabling it here will do nothing for now.
if let Some(val) = get_pref("js.mem.gc.incremental.enabled").as_boolean() {
let compartment = if let Some(val) = get_pref("js.mem.gc.per_compartment.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.mem.gc.incremental.enabled").as_boolean() {
let compartment = if let Some(val) = PREFS.get("js.mem.gc.per_compartment.enabled").as_boolean() {
val
} else {
false
@ -202,67 +202,67 @@ pub unsafe fn new_rt_and_cx() -> Runtime {
};
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MODE, mode as u32);
}
if let Some(val) = get_pref("js.mem.gc.incremental.slice_ms").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.incremental.slice_ms").as_i64() {
if val >= 0 && val < 100000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_SLICE_TIME_BUDGET, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.compacting.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.mem.gc.compacting.enabled").as_boolean() {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_COMPACTING_ENABLED, val as u32);
}
if let Some(val) = get_pref("js.mem.gc.high_frequency_time_limit_ms").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.high_frequency_time_limit_ms").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_TIME_LIMIT, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.dynamic_mark_slice.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.mem.gc.dynamic_mark_slice.enabled").as_boolean() {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_DYNAMIC_MARK_SLICE, val as u32);
}
// TODO: handle js.mem.gc.refresh_frame_slices.enabled
if let Some(val) = get_pref("js.mem.gc.dynamic_heap_growth.enabled").as_boolean() {
if let Some(val) = PREFS.get("js.mem.gc.dynamic_heap_growth.enabled").as_boolean() {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_DYNAMIC_HEAP_GROWTH, val as u32);
}
if let Some(val) = get_pref("js.mem.gc.low_frequency_heap_growth").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.low_frequency_heap_growth").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_LOW_FREQUENCY_HEAP_GROWTH, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.high_frequency_heap_growth_min").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.high_frequency_heap_growth_min").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.high_frequency_heap_growth_max").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.high_frequency_heap_growth_max").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.high_frequency_low_limit_mb").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.high_frequency_low_limit_mb").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_LOW_LIMIT, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.high_frequency_high_limit_mb").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.high_frequency_high_limit_mb").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_HIGH_FREQUENCY_HIGH_LIMIT, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.allocation_threshold_mb").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.allocation_threshold_mb").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_ALLOCATION_THRESHOLD, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.decommit_threshold_mb").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.decommit_threshold_mb").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_DECOMMIT_THRESHOLD, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.empty_chunk_count_min").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.empty_chunk_count_min").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MIN_EMPTY_CHUNK_COUNT, val as u32);
}
}
if let Some(val) = get_pref("js.mem.gc.empty_chunk_count_max").as_i64() {
if let Some(val) = PREFS.get("js.mem.gc.empty_chunk_count_max").as_i64() {
if val >= 0 && val < 10000 {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_EMPTY_CHUNK_COUNT, val as u32);
}
@ -403,11 +403,11 @@ unsafe extern fn trace_rust_roots(tr: *mut JSTracer, _data: *mut os::raw::c_void
unsafe fn set_gc_zeal_options(cx: *mut JSContext) {
use js::jsapi::{JS_DEFAULT_ZEAL_FREQ, JS_SetGCZeal};
let level = match get_pref("js.mem.gc.zeal.level").as_i64() {
let level = match PREFS.get("js.mem.gc.zeal.level").as_i64() {
Some(level @ 0...14) => level as u8,
_ => return,
};
let frequency = match get_pref("js.mem.gc.zeal.frequency").as_i64() {
let frequency = match PREFS.get("js.mem.gc.zeal.frequency").as_i64() {
Some(frequency) if frequency >= 0 => frequency as u32,
_ => JS_DEFAULT_ZEAL_FREQ,
};

Просмотреть файл

@ -22,7 +22,7 @@ use std::cmp::{self, Ord, Ordering};
use std::collections::HashMap;
use std::default::Default;
use std::rc::Rc;
use util::prefs::get_pref;
use util::prefs::PREFS;
#[derive(JSTraceable, PartialEq, Eq, Copy, Clone, HeapSizeOf, Hash, PartialOrd, Ord, Debug)]
pub struct OneshotTimerHandle(i32);
@ -214,7 +214,7 @@ impl OneshotTimers {
}
pub fn slow_down(&self) {
let duration = get_pref("js.timers.minimum_duration").as_u64().unwrap_or(1000);
let duration = PREFS.get("js.timers.minimum_duration").as_u64().unwrap_or(1000);
self.js_timers.set_min_duration(MsDuration::new(duration));
}

Просмотреть файл

@ -81,8 +81,9 @@ use profile_traits::time;
use script_traits::ConstellationMsg;
use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts;
use util::prefs::PREFS;
use util::resource_files::resources_dir_path;
use util::{opts, prefs};
pub use gleam::gl;
@ -257,7 +258,7 @@ pub fn run_content_process(token: String) {
let unprivileged_content = unprivileged_content_receiver.recv().unwrap();
opts::set_defaults(unprivileged_content.opts());
prefs::extend_prefs(unprivileged_content.prefs());
PREFS.extend(unprivileged_content.prefs());
// Enter the sandbox if necessary.
if opts::get().sandbox {

Просмотреть файл

@ -58,7 +58,7 @@
% for value in values:
"${value}" => {
% if value in experimental_values:
if !::util::prefs::get_pref("layout.${value}.enabled")
if !::util::prefs::PREFS.get("layout.${value}.enabled")
.as_boolean().unwrap_or(false) {
return Err(())
}

Просмотреть файл

@ -950,7 +950,7 @@ impl PropertyDeclaration {
}
% endif
% if property.experimental:
if !::util::prefs::get_pref("${property.experimental}")
if !::util::prefs::PREFS.get("${property.experimental}")
.as_boolean().unwrap_or(false) {
return PropertyDeclarationParseResult::ExperimentalProperty
}
@ -975,7 +975,7 @@ impl PropertyDeclaration {
}
% endif
% if shorthand.experimental:
if !::util::prefs::get_pref("${shorthand.experimental}")
if !::util::prefs::PREFS.get("${shorthand.experimental}")
.as_boolean().unwrap_or(false) {
return PropertyDeclarationParseResult::ExperimentalProperty
}

Просмотреть файл

@ -499,7 +499,7 @@ impl<'a, 'b, Impl: SelectorImpl> AtRuleParser for NestedRuleParser<'a, 'b, Impl>
Ok(AtRuleType::WithBlock(AtRulePrelude::FontFace))
},
"viewport" => {
if ::util::prefs::get_pref("layout.viewport.enabled").as_boolean().unwrap_or(false) {
if ::util::prefs::PREFS.get("layout.viewport.enabled").as_boolean().unwrap_or(false) {
Ok(AtRuleType::WithBlock(AtRulePrelude::Viewport))
} else {
Err(())

Просмотреть файл

@ -9,7 +9,7 @@ use euclid::size::{Size2D, TypedSize2D};
use geometry::ScreenPx;
use getopts::Options;
use num_cpus;
use prefs::{self, PrefValue};
use prefs::{self, PrefValue, PREFS};
use resource_files::set_resources_path;
use std::cmp;
use std::default::Default;
@ -605,7 +605,7 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult {
}
let cwd = env::current_dir().unwrap();
let homepage_pref = prefs::get_pref("shell.homepage");
let homepage_pref = PREFS.get("shell.homepage");
let url_opt = if !opt_match.free.is_empty() {
Some(&opt_match.free[0][..])
} else {
@ -745,10 +745,10 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult {
let do_not_use_native_titlebar =
opt_match.opt_present("b") ||
!prefs::get_pref("shell.native-titlebar.enabled").as_boolean().unwrap();
!PREFS.get("shell.native-titlebar.enabled").as_boolean().unwrap();
let use_webrender =
(prefs::get_pref("gfx.webrender.enabled").as_boolean().unwrap() || opt_match.opt_present("w")) &&
(PREFS.get("gfx.webrender.enabled").as_boolean().unwrap() || opt_match.opt_present("w")) &&
!opt_match.opt_present("z");
let render_api = match opt_match.opt_str("G") {
@ -830,9 +830,9 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult {
let pref_name = split[0];
let value = split.get(1);
match value {
Some(&"false") => prefs::set_pref(pref_name, PrefValue::Boolean(false)),
Some(&"true") | None => prefs::set_pref(pref_name, PrefValue::Boolean(true)),
_ => prefs::set_pref(pref_name, PrefValue::String(value.unwrap().to_string()))
Some(&"false") => PREFS.set(pref_name, PrefValue::Boolean(false)),
Some(&"true") | None => PREFS.set(pref_name, PrefValue::Boolean(true)),
_ => PREFS.set(pref_name, PrefValue::String(value.unwrap().to_string()))
};
}

Просмотреть файл

@ -14,9 +14,9 @@ use std::path::PathBuf;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref PREFS: Arc<Mutex<HashMap<String, Pref>>> = {
let prefs = read_prefs().unwrap_or(HashMap::new());
Arc::new(Mutex::new(prefs))
pub static ref PREFS: Preferences = {
let prefs = read_prefs().unwrap_or_else(|_| HashMap::new());
Preferences(Arc::new(Mutex::new(prefs)))
};
}
@ -167,14 +167,6 @@ pub fn read_prefs_from_file<T>(mut file: T)
Ok(prefs)
}
pub fn get_cloned() -> HashMap<String, Pref> {
PREFS.lock().unwrap().clone()
}
pub fn extend_prefs(extension: HashMap<String, Pref>) {
PREFS.lock().unwrap().extend(extension);
}
pub fn add_user_prefs() {
match opts::get().config_dir {
Some(ref config_path) => {
@ -194,7 +186,7 @@ fn init_user_prefs(path: &mut PathBuf) {
path.push("prefs.json");
if let Ok(file) = File::open(path) {
if let Ok(prefs) = read_prefs_from_file(file) {
extend_prefs(prefs);
PREFS.extend(prefs);
}
} else {
writeln!(&mut stderr(), "Error opening prefs.json from config directory")
@ -215,44 +207,56 @@ fn read_prefs() -> Result<HashMap<String, Pref>, ()> {
read_prefs_from_file(file)
}
pub fn get_pref(name: &str) -> Arc<PrefValue> {
PREFS.lock().unwrap().get(name).map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}
pub struct Preferences(Arc<Mutex<HashMap<String, Pref>>>);
pub fn set_pref(name: &str, value: PrefValue) {
let mut prefs = PREFS.lock().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
impl Preferences {
pub fn get(&self, name: &str) -> Arc<PrefValue> {
self.0.lock().unwrap().get(name).map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset_pref(name: &str) -> Arc<PrefValue> {
let mut prefs = PREFS.lock().unwrap();
let result = match prefs.get_mut(name) {
None => return Arc::new(PrefValue::Missing),
Some(&mut Pref::NoDefault(_)) => Arc::new(PrefValue::Missing),
Some(&mut Pref::WithDefault(ref default, ref mut set_value)) => {
*set_value = None;
default.clone()
},
};
if *result == PrefValue::Missing {
prefs.remove(name);
pub fn cloned(&self) -> HashMap<String, Pref> {
self.0.lock().unwrap().clone()
}
result
}
pub fn reset_all_prefs() {
let names = {
PREFS.lock().unwrap().keys().cloned().collect::<Vec<String>>()
};
for name in names.iter() {
reset_pref(name);
pub fn is_mozbrowser_enabled(&self) -> bool {
self.get("dom.mozbrowser.enabled").as_boolean().unwrap_or(false)
}
pub fn set(&self, name: &str, value: PrefValue) {
let mut prefs = self.0.lock().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
let mut prefs = self.0.lock().unwrap();
let result = match prefs.get_mut(name) {
None => return Arc::new(PrefValue::Missing),
Some(&mut Pref::NoDefault(_)) => Arc::new(PrefValue::Missing),
Some(&mut Pref::WithDefault(ref default, ref mut set_value)) => {
*set_value = None;
default.clone()
},
};
if *result == PrefValue::Missing {
prefs.remove(name);
}
result
}
pub fn reset_all(&self) {
let names = {
self.0.lock().unwrap().keys().cloned().collect::<Vec<String>>()
};
for name in names.iter() {
self.reset(name);
}
}
pub fn extend(&self, extension: HashMap<String, Pref>) {
self.0.lock().unwrap().extend(extension);
}
}
pub fn mozbrowser_enabled() -> bool {
get_pref("dom.mozbrowser.enabled").as_boolean().unwrap_or(false)
}

Просмотреть файл

@ -46,7 +46,7 @@ use std::sync::mpsc::Sender;
use std::thread;
use std::time::Duration;
use url::Url;
use util::prefs::{get_pref, reset_all_prefs, reset_pref, set_pref, PrefValue};
use util::prefs::{PREFS, PrefValue};
use util::thread::spawn_named;
use uuid::Uuid;
use webdriver::command::WindowSizeParameters;
@ -813,7 +813,7 @@ impl Handler {
parameters: &GetPrefsParameters) -> WebDriverResult<WebDriverResponse> {
let prefs = parameters.prefs
.iter()
.map(|item| (item.clone(), get_pref(item).to_json()))
.map(|item| (item.clone(), PREFS.get(item).to_json()))
.collect::<BTreeMap<_, _>>();
Ok(WebDriverResponse::Generic(ValueResponse::new(prefs.to_json())))
@ -822,7 +822,7 @@ impl Handler {
fn handle_set_prefs(&self,
parameters: &SetPrefsParameters) -> WebDriverResult<WebDriverResponse> {
for &(ref key, ref value) in parameters.prefs.iter() {
set_pref(key, value.clone());
PREFS.set(key, value.clone());
}
Ok(WebDriverResponse::Void)
}
@ -830,12 +830,12 @@ impl Handler {
fn handle_reset_prefs(&self,
parameters: &GetPrefsParameters) -> WebDriverResult<WebDriverResponse> {
let prefs = if parameters.prefs.len() == 0 {
reset_all_prefs();
PREFS.reset_all();
BTreeMap::new()
} else {
parameters.prefs
.iter()
.map(|item| (item.clone(), reset_pref(item).to_json()))
.map(|item| (item.clone(), PREFS.reset(item).to_json()))
.collect::<BTreeMap<_, _>>()
};
Ok(WebDriverResponse::Generic(ValueResponse::new(prefs.to_json())))

Просмотреть файл

@ -36,7 +36,7 @@ use util::geometry::ScreenPx;
use util::opts;
#[cfg(not(target_os = "android"))]
use util::opts::RenderApi;
use util::prefs;
use util::prefs::PREFS;
use util::resource_files;
#[cfg(target_os = "windows")] use winapi;
@ -822,7 +822,7 @@ impl WindowMethods for Window {
}
(NONE, Key::Escape) => {
if let Some(true) = prefs::get_pref("shell.builtin-key-shortcuts.enabled").as_boolean() {
if let Some(true) = PREFS.get("shell.builtin-key-shortcuts.enabled").as_boolean() {
self.event_queue.borrow_mut().push(WindowEvent::Quit);
}
}
@ -865,7 +865,7 @@ impl WindowMethods for Window {
self.scroll_window(-LINE_HEIGHT, 0.0, TouchEventType::Move);
}
(CMD_OR_CONTROL, Key::R) => {
if let Some(true) = prefs::get_pref("shell.builtin-key-shortcuts.enabled").as_boolean() {
if let Some(true) = PREFS.get("shell.builtin-key-shortcuts.enabled").as_boolean() {
self.event_queue.borrow_mut().push(WindowEvent::Reload);
}
}

Просмотреть файл

@ -33,7 +33,7 @@ use std::sync::mpsc::Receiver;
use std::sync::{Arc, mpsc, RwLock};
use std::thread;
use url::Url;
use util::prefs;
use util::prefs::{self, PREFS};
const DEFAULT_USER_AGENT: &'static str = "Test-agent";
@ -1218,8 +1218,8 @@ fn test_load_errors_when_there_is_too_many_redirects() {
let ui_provider = TestProvider::new();
let redirect_limit = 13.;
prefs::set_pref("network.http.redirection-limit",
prefs::PrefValue::Number(redirect_limit));
PREFS.set("network.http.redirection-limit",
prefs::PrefValue::Number(redirect_limit));
match load(&load_data, &ui_provider, &http_state, None, &Factory,
DEFAULT_USER_AGENT.to_owned(), &CancellationListener::new(None)) {
@ -1231,7 +1231,7 @@ fn test_load_errors_when_there_is_too_many_redirects() {
_ => panic!("expected max redirects to fail")
}
prefs::reset_pref("network.http.redirection-limit");
PREFS.reset("network.http.redirection-limit");
}
#[test]

Просмотреть файл

@ -30,8 +30,8 @@ fn test_viewport_rule<F>(css: &str,
callback: F)
where F: Fn(&Vec<ViewportDescriptorDeclaration>, &str)
{
::util::prefs::set_pref("layout.viewport.enabled",
::util::prefs::PrefValue::Boolean(true));
::util::prefs::PREFS.set("layout.viewport.enabled",
::util::prefs::PrefValue::Boolean(true));
let stylesheet = stylesheet!(css, Author, Box::new(CSSErrorReporterTest));
let mut rule_count = 0;
for rule in stylesheet.effective_rules(&device).viewport() {
@ -245,8 +245,8 @@ fn cascading_within_viewport_rule() {
#[test]
fn multiple_stylesheets_cascading() {
::util::prefs::set_pref("layout.viewport.enabled",
::util::prefs::PrefValue::Boolean(true));
::util::prefs::PREFS.set("layout.viewport.enabled",
::util::prefs::PrefValue::Boolean(true));
let device = Device::new(MediaType::Screen, Size2D::typed(800., 600.));
let error_reporter = CSSErrorReporterTest;
let stylesheets = vec![

Просмотреть файл

@ -5,7 +5,7 @@
use std::fs::{self, File};
use std::io::{Read, Write};
use util::basedir;
use util::prefs::{PrefValue, extend_prefs, read_prefs_from_file, get_pref, set_pref, reset_pref};
use util::prefs::{PREFS, PrefValue, read_prefs_from_file};
#[test]
fn test_create_pref() {
@ -30,20 +30,20 @@ fn test_get_set_reset_extend() {
\"shell.homepage\": \"https://google.com\"\
}";
assert_eq!(*get_pref("test"), PrefValue::Missing);
set_pref("test", PrefValue::String("hi".to_owned()));
assert_eq!(*get_pref("test"), PrefValue::String("hi".to_owned()));
assert_eq!(*get_pref("shell.homepage"), PrefValue::String("http://servo.org".to_owned()));
set_pref("shell.homepage", PrefValue::Boolean(true));
assert_eq!(*get_pref("shell.homepage"), PrefValue::Boolean(true));
reset_pref("shell.homepage");
assert_eq!(*get_pref("shell.homepage"), PrefValue::String("http://servo.org".to_owned()));
assert_eq!(*PREFS.get("test"), PrefValue::Missing);
PREFS.set("test", PrefValue::String("hi".to_owned()));
assert_eq!(*PREFS.get("test"), PrefValue::String("hi".to_owned()));
assert_eq!(*PREFS.get("shell.homepage"), PrefValue::String("http://servo.org".to_owned()));
PREFS.set("shell.homepage", PrefValue::Boolean(true));
assert_eq!(*PREFS.get("shell.homepage"), PrefValue::Boolean(true));
PREFS.reset("shell.homepage");
assert_eq!(*PREFS.get("shell.homepage"), PrefValue::String("http://servo.org".to_owned()));
let extension = read_prefs_from_file(json_str.as_bytes()).unwrap();
extend_prefs(extension);
assert_eq!(*get_pref("shell.homepage"), PrefValue::String("https://google.com".to_owned()));
assert_eq!(*get_pref("layout.writing-mode.enabled"), PrefValue::Boolean(true));
assert_eq!(*get_pref("extra.stuff"), PrefValue::Boolean(false));
PREFS.extend(extension);
assert_eq!(*PREFS.get("shell.homepage"), PrefValue::String("https://google.com".to_owned()));
assert_eq!(*PREFS.get("layout.writing-mode.enabled"), PrefValue::Boolean(true));
assert_eq!(*PREFS.get("extra.stuff"), PrefValue::Boolean(false));
}
#[test]