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