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