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