Skip to main content

servo_config/
prefs.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Preferences are the global configuration options that can be changed at runtime.
6
7use std::env::consts::ARCH;
8use std::sync::{RwLock, RwLockReadGuard};
9use std::time::Duration;
10
11use serde::{Deserialize, Serialize};
12use servo_config_macro::ServoPreferences;
13
14pub use crate::pref_util::PrefValue;
15
16static PREFERENCES: RwLock<Preferences> = RwLock::new(Preferences::const_default());
17
18/// A trait to be implemented by components that wish to be notified about runtime changes to the
19/// global preferences for the current process.
20pub trait PreferencesObserver: Send + Sync {
21    /// This method is called when the global preferences have been updated. The argument to the
22    /// method is an array of tuples where the first component is the name of the preference and
23    /// the second component is the new value of the preference.
24    fn prefs_changed(&self, _changes: &[(&'static str, PrefValue)]) {}
25}
26
27static OBSERVERS: RwLock<Vec<Box<dyn PreferencesObserver>>> = RwLock::new(Vec::new());
28
29#[inline]
30/// Get the current set of global preferences for Servo.
31pub fn get() -> RwLockReadGuard<'static, Preferences> {
32    PREFERENCES.read().unwrap()
33}
34
35/// Subscribe to notifications about changes to the global preferences for the current process.
36pub fn add_observer(observer: Box<dyn PreferencesObserver>) {
37    OBSERVERS.write().unwrap().push(observer);
38}
39
40/// Update the values of the global preferences for the current process. This also notifies the
41/// observers previously added using [`add_observer`].
42pub fn set(preferences: Preferences) {
43    // Get list of changes, returning early if the preferences haven't changed.
44    let changed = preferences.diff(&PREFERENCES.read().unwrap());
45    if changed.is_empty() {
46        return;
47    }
48
49    // Map between Stylo preference names and Servo preference names.
50    stylo_static_prefs::set_pref!("layout.threads", preferences.layout_threads as i32);
51    stylo_static_prefs::set_pref!(
52        "layout.css.backdrop-filter.enabled",
53        preferences.layout_css_backdrop_filter_enabled
54    );
55    stylo_static_prefs::set_pref!(
56        "layout.css.columns.enabled",
57        preferences.layout_css_columns_enabled
58    );
59    stylo_static_prefs::set_pref!(
60        "layout.css.container-queries.enabled",
61        preferences.layout_css_container_queries_enabled
62    );
63    stylo_static_prefs::set_pref!(
64        "layout.css.ellipse-corners.enabled",
65        preferences.layout_css_ellipse_corners_enabled
66    );
67    stylo_static_prefs::set_pref!(
68        "layout.css.font-variations.enabled",
69        preferences.layout_css_font_variations_enabled
70    );
71    stylo_static_prefs::set_pref!(
72        "layout.css.webkit-text-fill-color.enabled",
73        preferences.layout_css_webkit_text_fill_color_enabled
74    );
75    stylo_static_prefs::set_pref!(
76        "layout.css.writing-mode.enabled",
77        preferences.layout_css_writing_mode_enabled
78    );
79
80    *PREFERENCES.write().unwrap() = preferences;
81
82    for observer in &*OBSERVERS.read().unwrap() {
83        observer.prefs_changed(&changed);
84    }
85}
86
87/// A convenience macro for accessing a preference value using its static path.
88/// Passing an invalid path is a compile-time error.
89#[macro_export]
90macro_rules! pref {
91    ($name: ident) => {
92        $crate::prefs::get().$name.clone()
93    };
94}
95
96/// The set of global preferences supported by Servo.
97///
98/// Each preference has a default value that determines its initial state. These defaults
99/// fall into roughly three categories:
100/// - **Stable**: enabled by default.
101/// - **Experimental**: disabled by default, but intended to be enabled for experimental use.
102/// - **Unstable**: disabled by default.
103///
104/// For a full overview of which preferences are experimental, see the
105/// [experimental features documentation](https://book.servo.org/design-documentation/experimental-features.html).
106#[derive(Clone, Deserialize, Serialize, ServoPreferences)]
107pub struct Preferences {
108    pub fonts_default: String,
109    pub fonts_serif: String,
110    pub fonts_sans_serif: String,
111    pub fonts_monospace: String,
112    pub fonts_default_size: u64,
113    pub fonts_default_monospace_size: u64,
114    /// The amount of time that a half cycle of a text caret blink takes in milliseconds.
115    /// If this value is less than or equal to zero, then caret blink is disabled.
116    pub editing_caret_blink_time: u64,
117    pub css_animations_testing_enabled: bool,
118    /// Start the devtools server at startup
119    pub devtools_server_enabled: bool,
120    /// The address:port the devtools server listens to, default to 127.0.0.1:7000.
121    pub devtools_server_listen_address: String,
122    /// Maximum number of bytes of each network response body that is sent to devtools.
123    pub devtools_network_response_body_limit: i64,
124    // feature: WebGPU | #24706 | Web/API/WebGPU_API
125    pub dom_webgpu_enabled: bool,
126    /// List of comma-separated backends to be used by wgpu.
127    pub dom_webgpu_wgpu_backend: String,
128    // feature: Adopted Stylesheet | #38132 | Web/API/Document/adoptedStyleSheets
129    pub dom_adoptedstylesheet_enabled: bool,
130    pub dom_allow_preloading_module_descendants: bool,
131    // feature: Clipboard API | #36084 | Web/API/Clipboard_API
132    pub dom_async_clipboard_enabled: bool,
133    pub dom_bluetooth_enabled: bool,
134    pub dom_bluetooth_testing_enabled: bool,
135    pub dom_allow_scripts_to_close_windows: bool,
136    // feature: Media Capture and Streams API | #26861 | Web/API/Media_Capture_and_Streams_API
137    pub dom_canvas_capture_enabled: bool,
138    pub dom_canvas_text_enabled: bool,
139    /// Selects canvas backend
140    ///
141    /// Available values:
142    /// - vello
143    /// - Everything else selects vello_cpu
144    pub dom_canvas_backend: String,
145    /// Maximum number of buffered canvas commands before an automatic flush is triggered.
146    ///
147    /// A lower value keeps the paint thread fed with work (better parallelism),
148    /// while a higher value improves batching efficiency (fewer channel operations, lower power).
149    ///
150    /// See <https://github.com/servo/servo/pull/45301> for measurements.
151    pub dom_canvas_msg_buffer_size: u64,
152    pub dom_composition_event_enabled: bool,
153    // feature: CookieStore | #37674 | Web/API/CookieStore
154    pub dom_cookiestore_enabled: bool,
155    // feature: Credential Management API | #38788 | Web/API/Credential_Management_API
156    pub dom_credential_management_enabled: bool,
157    // feature: WebCrypto API | #40687 | Web/API/Web_Crypto_API
158    pub dom_crypto_subtle_enabled: bool,
159    pub dom_document_dblclick_timeout: u64,
160    pub dom_document_dblclick_dist: u64,
161    // feature: File and Directory Entries API | #45653 | Web/API/File_and_Directory_Entries_API
162    pub dom_entries_api_enabled: bool,
163    // feature: Document.execCommand | #25005 | Web/API/Document/execCommand
164    pub dom_exec_command_enabled: bool,
165    // feature: CSS Font Loading API | #29376 | Web/API/CSS_Font_Loading_API
166    pub dom_fontface_enabled: bool,
167    pub dom_fullscreen_test: bool,
168    // feature: Gamepad API | #10977 | Web/API/Gamepad_API
169    pub dom_gamepad_enabled: bool,
170    // feature: Geolocation API | #38903 | Web/API/Geolocation_API
171    pub dom_geolocation_enabled: bool,
172    /// Make the built-in geolocation backend report a fixed position instead of reporting that
173    /// no position is available for testing purposes.
174    pub dom_geolocation_test_position_enabled: bool,
175    /// The accuracy, in meters, reported when `dom_geolocation_test_position_enabled` is set.
176    pub dom_geolocation_test_accuracy: f64,
177    /// The heading, in degrees, reported when `dom_geolocation_test_position_enabled` is set.
178    pub dom_geolocation_test_heading: f64,
179    /// The latitude, in degrees, reported when `dom_geolocation_test_position_enabled` is set.
180    pub dom_geolocation_test_latitude: f64,
181    /// The longitude, in degrees, reported when `dom_geolocation_test_position_enabled` is set.
182    pub dom_geolocation_test_longitude: f64,
183    /// The speed, in meters per second, reported when `dom_geolocation_test_position_enabled`
184    /// is set.
185    pub dom_geolocation_test_speed: f64,
186    // feature: Screen Wake Lock API | #43615 | Web/API/Screen_Wake_Lock_API
187    pub dom_wakelock_enabled: bool,
188    // feature: IndexedDB | #6963 | Web/API/IndexedDB_API
189    pub dom_indexeddb_enabled: bool,
190    // feature: IntersectionObserver | #35767 | Web/API/Intersection_Observer_API
191    pub dom_intersection_observer_enabled: bool,
192    pub dom_microdata_testing_enabled: bool,
193    // feature: Navigator.registerProtocolHandler() | #40615 | Web/API/Navigator/registerProtocolHandler
194    pub dom_navigator_protocol_handlers_enabled: bool,
195    // feature: Notification API | #34841 | Web/API/Notifications_API
196    pub dom_notification_enabled: bool,
197    // feature: OffscreenCanvas | #34111 | Web/API/OffscreenCanvas
198    pub dom_offscreen_canvas_enabled: bool,
199    pub dom_parallel_css_parsing_enabled: bool,
200    // feature: Permissions API | #31235 | Web/API/Permissions_API
201    pub dom_permissions_enabled: bool,
202    pub dom_permissions_testing_allowed_in_nonsecure_contexts: bool,
203    // feature: ResizeObserver | #39790 | Web/API/ResizeObserver
204    pub dom_resize_observer_enabled: bool,
205    // feature: Sanitizer API | #43948 | Web/API/HTML_Sanitizer_API
206    pub dom_sanitizer_enabled: bool,
207    pub dom_script_asynch: bool,
208    // feature: Storage API | #43976 | Web/API/Storage_API
209    pub dom_storage_manager_api_enabled: bool,
210    // feature: ServiceWorker | #36538 | Web/API/Service_Worker_API
211    pub dom_serviceworker_enabled: bool,
212    pub dom_serviceworker_timeout_seconds: u64,
213    // feature: SharedWorker | #7458 | Web/API/SharedWorker
214    pub dom_sharedworker_enabled: bool,
215    pub dom_servo_helpers_enabled: bool,
216    pub dom_servoparser_async_html_tokenizer_enabled: bool,
217    pub dom_testbinding_enabled: bool,
218    pub dom_testbinding_prefcontrolled_enabled: bool,
219    pub dom_testbinding_prefcontrolled2_enabled: bool,
220    pub dom_testbinding_preference_value_falsy: bool,
221    pub dom_testbinding_preference_value_quote_string_test: String,
222    pub dom_testbinding_preference_value_space_string_test: String,
223    pub dom_testbinding_preference_value_string_empty: String,
224    pub dom_testbinding_preference_value_string_test: String,
225    pub dom_testbinding_preference_value_truthy: bool,
226    pub dom_testing_element_activation_enabled: bool,
227    pub dom_testing_html_input_element_select_files_enabled: bool,
228    pub dom_testperf_enabled: bool,
229    // https://testutils.spec.whatwg.org#availability
230    pub dom_testutils_enabled: bool,
231    /// <https://w3c.github.io/touch-events/#conditionally-exposing-legacy-touch-event-apis>
232    pub dom_touch_events_legacy_apis_enabled: bool,
233    /// <https://html.spec.whatwg.org/multipage/#transient-activation-duration>
234    pub dom_transient_activation_duration_ms: i64,
235    // feature: Web Animations | #36950 | Web/API/Web_Animations_API
236    pub dom_web_animations_enabled: bool,
237    /// Enable WebGL2 APIs.
238    // feature: WebGL2 | #41394 | Web/API/WebGL2RenderingContext
239    pub dom_webgl2_enabled: bool,
240    // feature: WebRTC | #41396 | Web/API/WebRTC_API
241    pub dom_webrtc_enabled: bool,
242    // feature: WebRTC Transceiver | #41396 | Web/API/RTCRtpTransceiver
243    pub dom_webrtc_transceiver_enabled: bool,
244    pub dom_webxr_enabled: bool,
245    pub dom_webxr_test: bool,
246    pub dom_webxr_first_person_observer_view: bool,
247    pub dom_webxr_glwindow_enabled: bool,
248    pub dom_webxr_glwindow_left_right: bool,
249    pub dom_webxr_glwindow_red_cyan: bool,
250    pub dom_webxr_glwindow_spherical: bool,
251    pub dom_webxr_glwindow_cubemap: bool,
252    pub dom_webxr_hands_enabled: bool,
253    // feature: WebXR Layers | #27468 | Web/API/XRCompositionLayer
254    pub dom_webxr_layers_enabled: bool,
255    pub dom_webxr_openxr_enabled: bool,
256    pub dom_webxr_sessionavailable: bool,
257    pub dom_webxr_unsafe_assume_user_intent: bool,
258    pub dom_worklet_enabled: bool,
259    pub dom_worklet_blockingsleep_enabled: bool,
260    pub dom_worklet_testing_enabled: bool,
261    pub dom_worklet_timeout_ms: u64,
262    /// <https://drafts.csswg.org/cssom-view/#the-visualviewport-interface>
263    // feature: VisualViewport | #41341 | Web/API/VisualViewport
264    pub dom_visual_viewport_enabled: bool,
265    /// True to compile all WebRender shaders when Servo initializes. This is mostly
266    /// useful when modifying the shaders, to ensure they all compile after each change is
267    /// made.
268    pub gfx_precache_shaders: bool,
269    /// Whether or not antialiasing is enabled for text rendering.
270    pub gfx_text_antialiasing_enabled: bool,
271    /// Whether or not subpixel antialiasing is enabled for text rendering.
272    pub gfx_subpixel_text_antialiasing_enabled: bool,
273    pub gfx_texture_swizzling_enabled: bool,
274    /// The amount of image keys we request per batch for the image cache.
275    pub image_key_batch_size: u64,
276    /// Whether or not the DOM inspector should show shadow roots of user-agent shadow trees
277    pub inspector_show_servo_internal_shadow_roots: bool,
278    /// A locale tag (eg. es-ES) to use for language negotiation instead of the system locale.
279    /// An empty string represents no override.
280    /// TODO: Option<> support in PrefValue
281    pub intl_locale_override: String,
282    pub js_asmjs_enabled: bool,
283    pub js_baseline_interpreter_enabled: bool,
284    /// Whether to disable the jit within SpiderMonkey
285    pub js_disable_jit: bool,
286    pub js_baseline_jit_enabled: bool,
287    pub js_baseline_jit_unsafe_eager_compilation_enabled: bool,
288    pub js_ion_enabled: bool,
289    pub js_ion_unsafe_eager_compilation_enabled: bool,
290    pub js_mem_gc_compacting_enabled: bool,
291    pub js_mem_gc_empty_chunk_count_min: u64,
292    pub js_mem_gc_high_frequency_heap_growth_max: u64,
293    pub js_mem_gc_high_frequency_heap_growth_min: u64,
294    pub js_mem_gc_high_frequency_high_limit_mb: u64,
295    pub js_mem_gc_high_frequency_low_limit_mb: u64,
296    pub js_mem_gc_high_frequency_time_limit_ms: u64,
297    /// Whether or not incremental garbage collection is turned on. This is currently
298    /// turned off by default as pre-barriers are not implemented yet. If turned on, it
299    /// will likely lead to memory corruption.
300    ///
301    /// See <https://github.com/servo/servo/issues/7621>.
302    pub js_mem_gc_incremental_enabled: bool,
303    pub js_mem_gc_incremental_slice_ms: u64,
304    pub js_mem_gc_low_frequency_heap_growth: u64,
305    pub js_mem_gc_malloc_threshold_base_mb: u64,
306    pub js_mem_gc_per_zone_enabled: bool,
307    pub js_mem_gc_urgent_threshold_mb: u64,
308    pub js_mem_gc_zeal_frequency: u64,
309    pub js_mem_gc_zeal_level: u64,
310    pub js_mem_max: i64,
311    pub js_native_regex_enabled: bool,
312    pub js_offthread_compilation_enabled: bool,
313    pub js_timers_minimum_duration: u64,
314    pub js_wasm_baseline_enabled: bool,
315    pub js_wasm_enabled: bool,
316    pub js_wasm_ion_enabled: bool,
317    // feature: Container Timing| #48490 | Web/API/ContainerTiming
318    pub container_timing_enabled: bool,
319    // feature: Largest Contentful Paint | #42000 | Web/API/LargestContentfulPaint
320    pub largest_contentful_paint_enabled: bool,
321    pub layout_animations_test_enabled: bool,
322    pub layout_css_backdrop_filter_enabled: bool,
323    // feature: CSS Multicol | #22397 | Web/CSS/Guides/Multicol_layout
324    pub layout_css_columns_enabled: bool,
325    pub layout_css_container_queries_enabled: bool,
326    pub layout_css_ellipse_corners_enabled: bool,
327    // feature: Variable fonts | #38800 | Web/CSS/Guides/Fonts/Variable_fonts
328    pub layout_css_font_variations_enabled: bool,
329    pub layout_css_webkit_text_fill_color_enabled: bool,
330    // feature: CSS writing modes | #2560 | Web/CSS/Guides/Writing_modes
331    pub layout_css_writing_mode_enabled: bool,
332    pub layout_style_sharing_cache_enabled: bool,
333    pub layout_threads: u64,
334    /// The minimum number of parallelizable jobs required before turning on parallelism
335    /// for a set of jobs.
336    ///
337    /// When deciding whether or not to parallelize layout, this is the minimum number of
338    /// jobs that must be larger than [`Self::layout_parallelism_job_size_minimum`] to
339    /// turn on parallelism. An exception is when doing box tree layout, where Servo does
340    /// not know the depth of the tree. In that case any task that has more jobs than this
341    /// value will be parallelized.
342    ///
343    /// The goal of these two values is to allow tuning Servo's parallelism for both wide
344    /// and deep trees.
345    pub layout_parallelism_job_count_minimum: u64,
346    /// The minimum size of a layout job to be considered for parallelization.
347    ///
348    /// When deciding whether or not to parallelize layout, jobs greater than this size
349    /// are counted when considering the [`Self::layout_parallelism_job_count_minimum`]
350    /// threshold for turning on parallelism. Generally the size of the job is based on
351    /// the number of tasks to process in the subtree. For instance, this might be the
352    /// number of boxes to process in a box tree subtree.
353    ///
354    /// The goal of these two values is to allow tuning Servo's parallelism for both wide
355    /// and deep trees.
356    pub layout_parallelism_job_size_minimum: u64,
357    /// feature: MathML | #49078 | Web/MathML
358    pub mathml_core_enabled: bool,
359    /// Enable hardware acceleration for video playback.
360    pub media_glvideo_enabled: bool,
361    /// Enable a non-standard event handler for verifying behavior of media elements during tests.
362    pub media_testing_enabled: bool,
363    /// The default timeout set for establishing a network connection in seconds. This amount
364    /// if for the entire process of connecting to an address. For instance, if a particular host is
365    /// associated with multiple IP addresses, this timeout will be divided equally among
366    /// each IP address.
367    pub network_connection_timeout: u64,
368    pub network_enforce_tls_enabled: bool,
369    pub network_enforce_tls_localhost: bool,
370    pub network_enforce_tls_onion: bool,
371    pub network_http_cache_disabled: bool,
372    /// The path to a disk cache file. Empty string disables the disk cache.
373    pub network_http_disk_cache: String,
374    /// Maximum size of the disk cache file in bytes.
375    pub network_http_disk_cache_size: u64,
376    /// A url for a http proxy. We treat an empty string as no proxy.
377    pub network_http_proxy_uri: String,
378    /// A url for a https proxy. We treat an empty string as no proxy.
379    pub network_https_proxy_uri: String,
380    /// The domains for which we will not have a proxy. No effect if `network_http_proxy_uri` is not set.
381    /// The exact behavior is given by
382    /// <https://docs.rs/hyper-util/latest/hyper_util/client/proxy/matcher/struct.Builder.html#method.no>
383    pub network_http_no_proxy: String,
384    /// The weight of the http memory cache
385    /// Notice that this is not equal to the number of different urls in the cache.
386    pub network_http_cache_size: u64,
387    pub network_local_directory_listing_enabled: bool,
388    /// Force the use of `rust-webpki` verification for CA roots. If this is false (the
389    /// default), then `rustls-platform-verifier` will be used, except on Android where
390    /// `rust-webpki` is always used.
391    pub network_use_webpki_roots: bool,
392    /// The maximum content size we will forward for preallocation, defaults to 5MB
393    pub network_max_content_length: u64,
394    /// Experimental option. If enabled servo will attempt to optimize thread placement
395    /// and/or priority of critical servo threads to optimize performance.
396    #[doc(hidden)]
397    pub perf_thread_boost_enabled: bool,
398    /// The length of the session history, in navigations, for each `WebView. Back-forward
399    /// cache entries that are more than `session_history_max_length` steps in the future or
400    /// `session_history_max_length` steps in the past will be discarded. Navigating forward
401    /// or backward to that entry will cause the entire page to be reloaded.
402    pub session_history_max_length: i64,
403    /// The background color of shell's viewport. This will be used by OpenGL's `glClearColor`.
404    pub shell_background_color_rgba: [f64; 4],
405    pub webgl_testing_context_creation_error: bool,
406    /// Maximum number of workers for the main thread pool
407    pub thread_pool_workers_max: u64,
408    /// Number of workers per thread pool, if we fail to detect how much
409    /// parallelism is available at runtime.
410    pub thread_pool_fallback_workers: u64,
411    /// Maximum number of workers for the asynchronous networking runtime thread pool
412    pub thread_pool_async_runtime_workers_max: u64,
413    /// Number of worker threads used to rasterize a canvas.
414    /// This preference currently only affects the vello_cpu backend.
415    /// Setting this pref to `0` uses the single-threaded backend and
416    /// avoids creating a threadpool.
417    /// For small canvas sizes this pref is ignored and no threadpool is created.
418    pub thread_pool_canvas_workers: u64,
419    /// Maximum number of workers for WebRender
420    pub thread_pool_webrender_workers_max: u64,
421    /// The user-agent to use for Servo. This can also be set via [`UserAgentPlatform`] in
422    /// order to set the value to the default value for the given platform.
423    pub user_agent: String,
424    /// Whether or not the viewport meta tag is enabled.
425    pub viewport_meta_enabled: bool,
426    pub log_filter: String,
427    /// Whether the accessibility code is enabled.
428    pub accessibility_enabled: bool,
429    /// Whether to run accessibility tree integrity checks, and any other expensive checks.
430    /// This should only be true in tests.
431    pub expensive_accessibility_test_assertions_enabled: bool,
432    /// Exposes internal JS API functions that are usually restricted to `about:...` pages
433    /// Useful if you want to get memory report or force GC in a test page
434    pub expose_servointernals_globally: bool,
435}
436
437impl Preferences {
438    const fn const_default() -> Self {
439        Self {
440            css_animations_testing_enabled: false,
441            editing_caret_blink_time: 600,
442            devtools_server_enabled: false,
443            devtools_server_listen_address: String::new(),
444            devtools_network_response_body_limit: 1024 * 1024, // 1 MB
445            dom_adoptedstylesheet_enabled: false,
446            dom_allow_preloading_module_descendants: false,
447            dom_allow_scripts_to_close_windows: false,
448            dom_async_clipboard_enabled: false,
449            dom_bluetooth_enabled: false,
450            dom_bluetooth_testing_enabled: false,
451            dom_canvas_capture_enabled: false,
452            dom_canvas_text_enabled: true,
453            dom_canvas_backend: String::new(),
454            dom_canvas_msg_buffer_size: 16,
455            dom_composition_event_enabled: false,
456            dom_cookiestore_enabled: false,
457            dom_credential_management_enabled: false,
458            dom_crypto_subtle_enabled: true,
459            dom_document_dblclick_dist: 1,
460            dom_document_dblclick_timeout: 300,
461            dom_entries_api_enabled: false,
462            dom_exec_command_enabled: false,
463            dom_fontface_enabled: false,
464            dom_fullscreen_test: false,
465            dom_gamepad_enabled: true,
466            dom_geolocation_enabled: false,
467            dom_geolocation_test_position_enabled: false,
468            dom_geolocation_test_accuracy: 0.0,
469            dom_geolocation_test_heading: 0.0,
470            dom_geolocation_test_latitude: -37.0675,
471            dom_geolocation_test_longitude: -12.3111,
472            dom_geolocation_test_speed: 0.0,
473            dom_wakelock_enabled: false,
474            dom_indexeddb_enabled: false,
475            dom_intersection_observer_enabled: false,
476            dom_microdata_testing_enabled: false,
477            dom_navigator_protocol_handlers_enabled: false,
478            dom_notification_enabled: false,
479            dom_parallel_css_parsing_enabled: true,
480            dom_offscreen_canvas_enabled: false,
481            dom_permissions_enabled: false,
482            dom_permissions_testing_allowed_in_nonsecure_contexts: false,
483            dom_resize_observer_enabled: true,
484            dom_sanitizer_enabled: false,
485            dom_script_asynch: false,
486            dom_storage_manager_api_enabled: false,
487            dom_serviceworker_enabled: false,
488            dom_serviceworker_timeout_seconds: 60,
489            dom_sharedworker_enabled: true,
490            dom_servo_helpers_enabled: false,
491            dom_servoparser_async_html_tokenizer_enabled: false,
492            dom_testbinding_enabled: false,
493            dom_testbinding_prefcontrolled2_enabled: false,
494            dom_testbinding_prefcontrolled_enabled: false,
495            dom_testbinding_preference_value_falsy: false,
496            dom_testbinding_preference_value_quote_string_test: String::new(),
497            dom_testbinding_preference_value_space_string_test: String::new(),
498            dom_testbinding_preference_value_string_empty: String::new(),
499            dom_testbinding_preference_value_string_test: String::new(),
500            dom_testbinding_preference_value_truthy: false,
501            dom_testing_element_activation_enabled: false,
502            dom_testing_html_input_element_select_files_enabled: false,
503            dom_testperf_enabled: false,
504            dom_testutils_enabled: false,
505            // Following Firefox and Chrome, we are enabling the touch events legacy APIs for android.
506            // Additionally, enabling it in ohos for compatibility as well.
507            dom_touch_events_legacy_apis_enabled: cfg!(target_os = "android") |
508                cfg!(target_env = "ohos"),
509            dom_transient_activation_duration_ms: 5000,
510            dom_web_animations_enabled: false,
511            dom_webgl2_enabled: false,
512            dom_webgpu_enabled: false,
513            dom_webgpu_wgpu_backend: String::new(),
514            dom_webrtc_enabled: false,
515            dom_webrtc_transceiver_enabled: false,
516            dom_webxr_enabled: true,
517            dom_webxr_first_person_observer_view: false,
518            dom_webxr_glwindow_cubemap: false,
519            dom_webxr_glwindow_enabled: true,
520            dom_webxr_glwindow_left_right: false,
521            dom_webxr_glwindow_red_cyan: false,
522            dom_webxr_glwindow_spherical: false,
523            dom_webxr_hands_enabled: true,
524            dom_webxr_layers_enabled: false,
525            dom_webxr_openxr_enabled: true,
526            dom_webxr_sessionavailable: false,
527            dom_webxr_test: false,
528            dom_webxr_unsafe_assume_user_intent: false,
529            dom_worklet_blockingsleep_enabled: false,
530            dom_worklet_enabled: false,
531            dom_worklet_testing_enabled: false,
532            dom_worklet_timeout_ms: 10,
533            dom_visual_viewport_enabled: false,
534            accessibility_enabled: false,
535            expensive_accessibility_test_assertions_enabled: false,
536            fonts_default: String::new(),
537            fonts_default_monospace_size: 13,
538            fonts_default_size: 16,
539            fonts_monospace: String::new(),
540            fonts_sans_serif: String::new(),
541            fonts_serif: String::new(),
542            gfx_precache_shaders: false,
543            gfx_text_antialiasing_enabled: true,
544            gfx_subpixel_text_antialiasing_enabled: true,
545            gfx_texture_swizzling_enabled: true,
546            image_key_batch_size: 10,
547            inspector_show_servo_internal_shadow_roots: false,
548            intl_locale_override: String::new(),
549            js_asmjs_enabled: true,
550            js_baseline_interpreter_enabled: true,
551            js_baseline_jit_enabled: true,
552            js_baseline_jit_unsafe_eager_compilation_enabled: false,
553            js_disable_jit: false,
554            js_ion_enabled: true,
555            js_ion_unsafe_eager_compilation_enabled: false,
556            // The layout system currently does not work with compacting GC, so it is disabled by default.
557            // See https://github.com/servo/servo/issues/47577
558            js_mem_gc_compacting_enabled: false,
559            js_mem_gc_empty_chunk_count_min: 1,
560            js_mem_gc_high_frequency_heap_growth_max: 300,
561            js_mem_gc_high_frequency_heap_growth_min: 150,
562            js_mem_gc_high_frequency_high_limit_mb: 500,
563            js_mem_gc_high_frequency_low_limit_mb: 100,
564            js_mem_gc_high_frequency_time_limit_ms: 1000,
565            js_mem_gc_incremental_enabled: false,
566            js_mem_gc_incremental_slice_ms: 10,
567            js_mem_gc_low_frequency_heap_growth: 150,
568            js_mem_gc_malloc_threshold_base_mb: 38,
569            js_mem_gc_per_zone_enabled: false,
570            js_mem_gc_urgent_threshold_mb: 16,
571            js_mem_gc_zeal_frequency: 100,
572            js_mem_gc_zeal_level: 0,
573            js_mem_max: -1,
574            js_native_regex_enabled: true,
575            js_offthread_compilation_enabled: true,
576            js_timers_minimum_duration: 1000,
577            js_wasm_baseline_enabled: true,
578            js_wasm_enabled: true,
579            js_wasm_ion_enabled: true,
580            container_timing_enabled: false,
581            largest_contentful_paint_enabled: false,
582            layout_animations_test_enabled: false,
583            layout_css_backdrop_filter_enabled: false,
584            layout_css_columns_enabled: false,
585            layout_css_container_queries_enabled: false,
586            layout_css_ellipse_corners_enabled: false,
587            layout_css_font_variations_enabled: false,
588            layout_css_webkit_text_fill_color_enabled: false,
589            layout_css_writing_mode_enabled: false,
590            layout_style_sharing_cache_enabled: true,
591            // TODO(mrobinson): This should likely be based on the number of processors.
592            layout_threads: 3,
593            layout_parallelism_job_count_minimum: 4,
594            layout_parallelism_job_size_minimum: 16,
595            mathml_core_enabled: false,
596            media_glvideo_enabled: false,
597            media_testing_enabled: false,
598            network_connection_timeout: 15,
599            network_enforce_tls_enabled: false,
600            network_enforce_tls_localhost: false,
601            network_enforce_tls_onion: false,
602            network_http_cache_disabled: false,
603            network_http_disk_cache: String::new(),
604            network_http_disk_cache_size: 1024 * 1024 * 100, // Roughtly 100MB
605            network_http_proxy_uri: String::new(),
606            network_https_proxy_uri: String::new(),
607            network_http_no_proxy: String::new(),
608            network_http_cache_size: 5000,
609            network_local_directory_listing_enabled: true,
610            network_use_webpki_roots: false,
611            network_max_content_length: 5 * 1024 * 1024,
612            perf_thread_boost_enabled: true,
613            session_history_max_length: 20,
614            shell_background_color_rgba: [1.0, 1.0, 1.0, 1.0],
615            log_filter: String::new(),
616            thread_pool_workers_max: 4,
617            thread_pool_async_runtime_workers_max: 6,
618            thread_pool_fallback_workers: 3,
619            // <https://github.com/linebender/vello/blob/c95b228e1cf73bf96338e8c8ae0d145553f8f99c/sparse_strips/vello_cpu/examples/basic.rs#L51>
620            // According to this example 2-4 give the best results.
621            thread_pool_canvas_workers: 3,
622            thread_pool_webrender_workers_max: 4,
623            webgl_testing_context_creation_error: false,
624            user_agent: String::new(),
625            viewport_meta_enabled: false,
626            expose_servointernals_globally: false,
627        }
628    }
629
630    /// The amount of time that a half cycle of a text caret blink takes. If blinking is disabled
631    /// this returns `None`.
632    pub fn editing_caret_blink_time(&self) -> Option<Duration> {
633        if self.editing_caret_blink_time > 0 {
634            Some(Duration::from_millis(self.editing_caret_blink_time))
635        } else {
636            None
637        }
638    }
639}
640
641impl Default for Preferences {
642    fn default() -> Self {
643        let mut preferences = Self::const_default();
644        preferences.user_agent = UserAgentPlatform::default().to_user_agent_string();
645        if let Ok(proxy_uri) = std::env::var("http_proxy").or_else(|_| std::env::var("HTTP_PROXY"))
646        {
647            preferences.network_http_proxy_uri = proxy_uri;
648        }
649        if let Ok(proxy_uri) =
650            std::env::var("https_proxy").or_else(|_| std::env::var("HTTPS_PROXY"))
651        {
652            preferences.network_https_proxy_uri = proxy_uri;
653        }
654        if let Ok(no_proxy) = std::env::var("no_proxy").or_else(|_| std::env::var("NO_PROXY")) {
655            preferences.network_http_no_proxy = no_proxy
656        }
657
658        preferences
659    }
660}
661
662pub enum UserAgentPlatform {
663    Desktop,
664    Android,
665    OpenHarmony,
666    Ios,
667}
668
669impl UserAgentPlatform {
670    /// Return the default `UserAgentPlatform` for this platform. This is
671    /// not an implementation of `Default` so that it can be `const`.
672    pub const fn default() -> Self {
673        if cfg!(target_os = "android") {
674            Self::Android
675        } else if cfg!(target_env = "ohos") {
676            Self::OpenHarmony
677        } else if cfg!(target_os = "ios") {
678            Self::Ios
679        } else {
680            Self::Desktop
681        }
682    }
683}
684
685impl UserAgentPlatform {
686    /// Convert this [`UserAgentPlatform`] into its corresponding `String` value, ie the
687    /// default user-agent to use for this platform.
688    pub fn to_user_agent_string(&self) -> String {
689        const SERVO_VERSION: &str = env!("CARGO_PKG_VERSION");
690        match self {
691            UserAgentPlatform::Desktop
692                if cfg!(all(target_os = "windows", target_arch = "x86_64")) =>
693            {
694                format!(
695                    "Mozilla/5.0 (Windows NT 10.0; Win64; {ARCH}; rv:153.0) Servo/{SERVO_VERSION} Firefox/153.0"
696                )
697            },
698            UserAgentPlatform::Desktop if cfg!(target_os = "macos") => {
699                format!(
700                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:153.0) Servo/{SERVO_VERSION} Firefox/153.0"
701                )
702            },
703            UserAgentPlatform::Desktop => {
704                format!(
705                    "Mozilla/5.0 (X11; Linux {ARCH}; rv:153.0) Servo/{SERVO_VERSION} Firefox/153.0"
706                )
707            },
708            UserAgentPlatform::Android => {
709                format!(
710                    "Mozilla/5.0 (Android 10; Mobile; rv:153.0) Servo/{SERVO_VERSION} Firefox/153.0"
711                )
712            },
713            UserAgentPlatform::OpenHarmony => format!(
714                "Mozilla/5.0 (OpenHarmony; Mobile; rv:153.0) Servo/{SERVO_VERSION} Firefox/153.0"
715            ),
716            UserAgentPlatform::Ios => format!(
717                "Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X; rv:153.0) Servo/{SERVO_VERSION} Firefox/153.0"
718            ),
719        }
720    }
721}