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