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    // 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    /// Maximum number of workers for the main thread pool
333    pub thread_pool_workers_max: u64,
334    /// Number of workers per thread pool, if we fail to detect how much
335    /// parallelism is available at runtime.
336    pub thread_pool_fallback_workers: u64,
337    /// Maximum number of workers for the asynchronous networking runtime thread pool
338    pub thread_pool_async_runtime_workers_max: u64,
339    /// Maximum number of workers for WebRender
340    pub thread_pool_webrender_workers_max: u64,
341    /// The user-agent to use for Servo. This can also be set via [`UserAgentPlatform`] in
342    /// order to set the value to the default value for the given platform.
343    pub user_agent: String,
344    /// Whether or not the viewport meta tag is enabled.
345    pub viewport_meta_enabled: bool,
346    pub log_filter: String,
347    /// Whether the accessibility code is enabled.
348    pub accessibility_enabled: bool,
349}
350
351impl Preferences {
352    const fn const_default() -> Self {
353        Self {
354            css_animations_testing_enabled: false,
355            editing_caret_blink_time: 600,
356            devtools_server_enabled: false,
357            devtools_server_listen_address: String::new(),
358            dom_abort_controller_enabled: true,
359            dom_adoptedstylesheet_enabled: false,
360            dom_allow_preloading_module_descendants: false,
361            dom_allow_scripts_to_close_windows: false,
362            dom_async_clipboard_enabled: false,
363            dom_bluetooth_enabled: false,
364            dom_bluetooth_testing_enabled: false,
365            dom_canvas_capture_enabled: false,
366            dom_canvas_text_enabled: true,
367            dom_canvas_backend: String::new(),
368            dom_clipboardevent_enabled: true,
369            dom_composition_event_enabled: false,
370            dom_cookiestore_enabled: false,
371            dom_credential_management_enabled: false,
372            dom_crypto_subtle_enabled: true,
373            dom_document_dblclick_dist: 1,
374            dom_document_dblclick_timeout: 300,
375            dom_exec_command_enabled: false,
376            dom_fontface_enabled: false,
377            dom_fullscreen_test: false,
378            dom_gamepad_enabled: true,
379            dom_geolocation_enabled: false,
380            dom_wakelock_enabled: false,
381            dom_indexeddb_enabled: false,
382            dom_intersection_observer_enabled: false,
383            dom_microdata_testing_enabled: false,
384            dom_uievent_which_enabled: true,
385            dom_mutation_observer_enabled: true,
386            dom_navigator_protocol_handlers_enabled: false,
387            dom_notification_enabled: false,
388            dom_parallel_css_parsing_enabled: true,
389            dom_offscreen_canvas_enabled: false,
390            dom_permissions_enabled: false,
391            dom_permissions_testing_allowed_in_nonsecure_contexts: false,
392            dom_resize_observer_enabled: true,
393            dom_sanitizer_enabled: false,
394            dom_script_asynch: true,
395            dom_storage_manager_api_enabled: false,
396            dom_serviceworker_enabled: false,
397            dom_serviceworker_timeout_seconds: 60,
398            dom_sharedworker_enabled: false,
399            dom_servo_helpers_enabled: false,
400            dom_servoparser_async_html_tokenizer_enabled: false,
401            dom_testbinding_enabled: false,
402            dom_testbinding_prefcontrolled2_enabled: false,
403            dom_testbinding_prefcontrolled_enabled: false,
404            dom_testbinding_preference_value_falsy: false,
405            dom_testbinding_preference_value_quote_string_test: String::new(),
406            dom_testbinding_preference_value_space_string_test: String::new(),
407            dom_testbinding_preference_value_string_empty: String::new(),
408            dom_testbinding_preference_value_string_test: String::new(),
409            dom_testbinding_preference_value_truthy: false,
410            dom_testing_element_activation_enabled: false,
411            dom_testing_html_input_element_select_files_enabled: false,
412            dom_testperf_enabled: false,
413            dom_testutils_enabled: false,
414            dom_transient_activation_duration_ms: 5000,
415            dom_webgl2_enabled: false,
416            dom_webgpu_enabled: false,
417            dom_webgpu_wgpu_backend: String::new(),
418            dom_webrtc_enabled: false,
419            dom_webrtc_transceiver_enabled: false,
420            dom_webvtt_enabled: false,
421            dom_webxr_enabled: true,
422            dom_webxr_first_person_observer_view: false,
423            dom_webxr_glwindow_cubemap: false,
424            dom_webxr_glwindow_enabled: true,
425            dom_webxr_glwindow_left_right: false,
426            dom_webxr_glwindow_red_cyan: false,
427            dom_webxr_glwindow_spherical: false,
428            dom_webxr_hands_enabled: true,
429            dom_webxr_layers_enabled: false,
430            dom_webxr_openxr_enabled: true,
431            dom_webxr_sessionavailable: false,
432            dom_webxr_test: false,
433            dom_webxr_unsafe_assume_user_intent: false,
434            dom_worklet_blockingsleep_enabled: false,
435            dom_worklet_enabled: false,
436            dom_worklet_testing_enabled: false,
437            dom_worklet_timeout_ms: 10,
438            dom_visual_viewport_enabled: false,
439            accessibility_enabled: false,
440            fonts_default: String::new(),
441            fonts_default_monospace_size: 13,
442            fonts_default_size: 16,
443            fonts_monospace: String::new(),
444            fonts_sans_serif: String::new(),
445            fonts_serif: String::new(),
446            gfx_precache_shaders: false,
447            gfx_text_antialiasing_enabled: true,
448            gfx_subpixel_text_antialiasing_enabled: true,
449            gfx_texture_swizzling_enabled: true,
450            image_key_batch_size: 10,
451            inspector_show_servo_internal_shadow_roots: false,
452            intl_locale_override: String::new(),
453            js_asmjs_enabled: true,
454            js_baseline_interpreter_enabled: true,
455            js_baseline_jit_enabled: true,
456            js_baseline_jit_unsafe_eager_compilation_enabled: false,
457            js_disable_jit: false,
458            js_ion_enabled: true,
459            js_ion_unsafe_eager_compilation_enabled: false,
460            js_mem_gc_compacting_enabled: true,
461            js_mem_gc_empty_chunk_count_min: 1,
462            js_mem_gc_high_frequency_heap_growth_max: 300,
463            js_mem_gc_high_frequency_heap_growth_min: 150,
464            js_mem_gc_high_frequency_high_limit_mb: 500,
465            js_mem_gc_high_frequency_low_limit_mb: 100,
466            js_mem_gc_high_frequency_time_limit_ms: 1000,
467            js_mem_gc_incremental_enabled: true,
468            js_mem_gc_incremental_slice_ms: 10,
469            js_mem_gc_low_frequency_heap_growth: 150,
470            js_mem_gc_per_zone_enabled: false,
471            js_mem_gc_zeal_frequency: 100,
472            js_mem_gc_zeal_level: 0,
473            js_mem_max: -1,
474            js_native_regex_enabled: true,
475            js_offthread_compilation_enabled: true,
476            js_timers_minimum_duration: 1000,
477            js_wasm_baseline_enabled: true,
478            js_wasm_enabled: true,
479            js_wasm_ion_enabled: true,
480            largest_contentful_paint_enabled: false,
481            layout_animations_test_enabled: false,
482            layout_columns_enabled: false,
483            layout_container_queries_enabled: false,
484            layout_css_attr_enabled: false,
485            layout_grid_enabled: false,
486            layout_style_sharing_cache_enabled: true,
487            // TODO(mrobinson): This should likely be based on the number of processors.
488            layout_threads: 3,
489            layout_unimplemented: false,
490            layout_variable_fonts_enabled: false,
491            layout_writing_mode_enabled: false,
492            media_glvideo_enabled: false,
493            media_testing_enabled: false,
494            network_connection_timeout: 15,
495            network_enforce_tls_enabled: false,
496            network_enforce_tls_localhost: false,
497            network_enforce_tls_onion: false,
498            network_http_cache_disabled: false,
499            network_http_proxy_uri: String::new(),
500            network_https_proxy_uri: String::new(),
501            network_http_no_proxy: String::new(),
502            network_http_cache_size: 5000,
503            network_local_directory_listing_enabled: true,
504            network_use_webpki_roots: false,
505            session_history_max_length: 20,
506            shell_background_color_rgba: [1.0, 1.0, 1.0, 1.0],
507            log_filter: String::new(),
508            thread_pool_workers_max: 4,
509            thread_pool_async_runtime_workers_max: 6,
510            thread_pool_fallback_workers: 3,
511            thread_pool_webrender_workers_max: 4,
512            webgl_testing_context_creation_error: false,
513            user_agent: String::new(),
514            viewport_meta_enabled: false,
515        }
516    }
517
518    /// The amount of time that a half cycle of a text caret blink takes. If blinking is disabled
519    /// this returns `None`.
520    pub fn editing_caret_blink_time(&self) -> Option<Duration> {
521        if self.editing_caret_blink_time > 0 {
522            Some(Duration::from_millis(self.editing_caret_blink_time as u64))
523        } else {
524            None
525        }
526    }
527}
528
529impl Default for Preferences {
530    fn default() -> Self {
531        let mut preferences = Self::const_default();
532        preferences.user_agent = UserAgentPlatform::default().to_user_agent_string();
533        if let Ok(proxy_uri) = std::env::var("http_proxy").or_else(|_| std::env::var("HTTP_PROXY"))
534        {
535            preferences.network_http_proxy_uri = proxy_uri;
536        }
537        if let Ok(proxy_uri) =
538            std::env::var("https_proxy").or_else(|_| std::env::var("HTTPS_PROXY"))
539        {
540            preferences.network_https_proxy_uri = proxy_uri;
541        }
542        if let Ok(no_proxy) = std::env::var("no_proxy").or_else(|_| std::env::var("NO_PROXY")) {
543            preferences.network_http_no_proxy = no_proxy
544        }
545
546        preferences
547    }
548}
549
550pub enum UserAgentPlatform {
551    Desktop,
552    Android,
553    OpenHarmony,
554    Ios,
555}
556
557impl UserAgentPlatform {
558    /// Return the default `UserAgentPlatform` for this platform. This is
559    /// not an implementation of `Default` so that it can be `const`.
560    pub const fn default() -> Self {
561        if cfg!(target_os = "android") {
562            Self::Android
563        } else if cfg!(target_env = "ohos") {
564            Self::OpenHarmony
565        } else if cfg!(target_os = "ios") {
566            Self::Ios
567        } else {
568            Self::Desktop
569        }
570    }
571}
572
573impl UserAgentPlatform {
574    /// Convert this [`UserAgentPlatform`] into its corresponding `String` value, ie the
575    /// default user-agent to use for this platform.
576    pub fn to_user_agent_string(&self) -> String {
577        const SERVO_VERSION: &str = env!("CARGO_PKG_VERSION");
578        match self {
579            UserAgentPlatform::Desktop
580                if cfg!(all(target_os = "windows", target_arch = "x86_64")) =>
581            {
582                format!(
583                    "Mozilla/5.0 (Windows NT 10.0; Win64; {ARCH}rv:140.0) Servo/{SERVO_VERSION} Firefox/140.0"
584                )
585            },
586            UserAgentPlatform::Desktop if cfg!(target_os = "macos") => {
587                format!(
588                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Servo/{SERVO_VERSION} Firefox/140.0"
589                )
590            },
591            UserAgentPlatform::Desktop => {
592                format!(
593                    "Mozilla/5.0 (X11; Linux {ARCH}; rv:140.0) Servo/{SERVO_VERSION} Firefox/140.0"
594                )
595            },
596            UserAgentPlatform::Android => {
597                format!(
598                    "Mozilla/5.0 (Android 10; Mobile; rv:140.0) Servo/{SERVO_VERSION} Firefox/140.0"
599                )
600            },
601            UserAgentPlatform::OpenHarmony => format!(
602                "Mozilla/5.0 (OpenHarmony; Mobile; rv:140.0) Servo/{SERVO_VERSION} Firefox/140.0"
603            ),
604            UserAgentPlatform::Ios => format!(
605                "Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X; rv:140.0) Servo/{SERVO_VERSION} Firefox/140.0"
606            ),
607        }
608    }
609}