Skip to main content

servoshell/
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 core::panic;
6use std::cell::Cell;
7use std::collections::HashMap;
8use std::fs::{self, read_to_string};
9use std::path::{Path, PathBuf};
10use std::rc::Rc;
11use std::str::FromStr;
12#[cfg(any(target_os = "android", target_env = "ohos"))]
13use std::sync::OnceLock;
14use std::{env, fmt};
15
16use bpaf::*;
17use euclid::Size2D;
18use log::warn;
19use serde_json::Value;
20use servo::user_contents::UserStyleSheet;
21use servo::{
22    DeviceIndependentPixel, DiagnosticsLogging, DiagnosticsLoggingOption, Opts, OutputOptions,
23    PrefValue, Preferences,
24};
25use url::Url;
26
27use crate::VERSION;
28
29/// Preferences enabled when servoshell is launched with the `--enable-experimental-web-platform-features` flag.
30///
31/// These preferences are disabled by default but activated in experimental mode.
32/// For more details, see the
33/// [experimental features documentation](https://book.servo.org/design-documentation/experimental-features.html).
34pub(crate) static EXPERIMENTAL_PREFS: &[&str] = &[
35    "dom_async_clipboard_enabled",
36    "dom_entries_api_enabled",
37    "dom_exec_command_enabled",
38    "dom_fontface_enabled",
39    "dom_indexeddb_enabled",
40    "dom_intersection_observer_enabled",
41    "dom_navigator_protocol_handlers_enabled",
42    "dom_notification_enabled",
43    "dom_offscreen_canvas_enabled",
44    "dom_permissions_enabled",
45    "dom_sanitizer_enabled",
46    "dom_storage_manager_api_enabled",
47    "dom_webgl2_enabled",
48    "dom_webgpu_enabled",
49    "layout_css_aspect_ratio_enabled",
50    "layout_css_backdrop_filter_enabled",
51    "layout_css_columns_enabled",
52    "layout_css_container_queries_enabled",
53    "layout_css_ellipse_corners_enabled",
54    "layout_css_font_variations_enabled",
55    "layout_css_writing_mode_enabled",
56];
57
58#[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
59#[derive(Clone)]
60pub(crate) struct ServoShellPreferences {
61    /// A URL to load when starting servoshell.
62    pub url: Option<String>,
63    /// An override value for the device pixel ratio.
64    pub device_pixel_ratio_override: Option<f32>,
65    /// Whether or not to attempt clean shutdown.
66    pub clean_shutdown: bool,
67    /// Enable native window's titlebar and decorations.
68    pub no_native_titlebar: bool,
69    /// URL string of the homepage.
70    pub homepage: String,
71    /// URL string of the search engine page with '%s' standing in for the search term.
72    /// For example <https://duckduckgo.com/html/?q=%s>.
73    pub searchpage: String,
74    /// Whether or not to run servoshell in headless mode. While running in headless
75    /// mode, image output is supported.
76    pub headless: bool,
77    /// Filter directives for our tracing implementation.
78    ///
79    /// Overrides directives specified via `SERVO_TRACING` if set.
80    /// See: <https://docs.rs/tracing-subscriber/0.3.19/tracing_subscriber/filter/struct.EnvFilter.html#directives>
81    pub tracing_filter: Option<String>,
82    /// The initial requested inner size of the window.
83    pub initial_window_size: Size2D<u32, DeviceIndependentPixel>,
84    /// An override for the screen resolution. This is useful for testing behavior on different screen sizes,
85    /// such as the screen of a mobile device.
86    pub screen_size_override: Option<Size2D<u32, DeviceIndependentPixel>>,
87    /// Whether or not to simulate touch events using mouse events.
88    pub simulate_touch_events: bool,
89    /// If not-None, the path to a file to output the default WebView's rendered output
90    /// after waiting for a stable image, this implies `Self::exit_after_load`.
91    pub output_image_path: Option<String>,
92    /// Whether or not to exit after Servo detects a stable output image in all WebViews.
93    pub exit_after_stable_image: bool,
94    /// Where to load userscripts from, if any.
95    /// and if the option isn't passed userscripts won't be loaded.
96    pub userscripts_directory: Option<PathBuf>,
97    /// A set of [`UserStylesheets`] to load for content.
98    pub user_stylesheets: Vec<Rc<UserStyleSheet>>,
99    /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to
100    /// remote WebDriver commands.
101    pub webdriver_port: Cell<Option<u16>>,
102    /// Whether the CLI option to enable experimental prefs was present at startup.
103    pub experimental_preferences_enabled: bool,
104    /// Log filter given in the `log_filter` spec as a String, if any.
105    /// If a filter is passed, the logger should adjust accordingly.
106    #[cfg(target_env = "ohos")]
107    pub log_filter: Option<String>,
108    /// Log also to a file
109    #[cfg(target_env = "ohos")]
110    pub log_to_file: bool,
111    /// Enable memory output if tracing is enabled.
112    #[allow(unused)]
113    pub memory_output: bool,
114}
115
116impl Default for ServoShellPreferences {
117    fn default() -> Self {
118        Self {
119            clean_shutdown: false,
120            device_pixel_ratio_override: None,
121            headless: false,
122            homepage: "https://servo.org".into(),
123            initial_window_size: Size2D::new(1024, 740),
124            no_native_titlebar: true,
125            screen_size_override: None,
126            simulate_touch_events: false,
127            searchpage: "https://duckduckgo.com/html/?q=%s".into(),
128            tracing_filter: None,
129            url: None,
130            output_image_path: None,
131            exit_after_stable_image: false,
132            userscripts_directory: None,
133            user_stylesheets: Default::default(),
134            webdriver_port: Cell::new(None),
135            #[cfg(target_env = "ohos")]
136            log_filter: None,
137            #[cfg(target_env = "ohos")]
138            log_to_file: false,
139            experimental_preferences_enabled: false,
140            memory_output: false,
141        }
142    }
143}
144
145#[cfg(all(
146    unix,
147    not(target_os = "macos"),
148    not(target_os = "ios"),
149    not(target_os = "android"),
150    not(target_env = "ohos")
151))]
152pub fn default_config_dir() -> Option<PathBuf> {
153    let mut config_dir = ::dirs::config_dir().unwrap();
154    config_dir.push("servo");
155    config_dir.push("default");
156    Some(config_dir)
157}
158
159/// Overrides the default preference dir
160#[cfg(any(target_os = "android", target_env = "ohos"))]
161pub(crate) static DEFAULT_CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
162#[cfg(any(target_os = "android", target_env = "ohos"))]
163pub fn default_config_dir() -> Option<PathBuf> {
164    DEFAULT_CONFIG_DIR.get().cloned()
165}
166
167#[cfg(target_os = "macos")]
168pub fn default_config_dir() -> Option<PathBuf> {
169    // FIXME: use `config_dir()` ($HOME/Library/Preferences)
170    // instead of `data_dir()` ($HOME/Library/Application Support) ?
171    let mut config_dir = ::dirs::data_dir().unwrap();
172    config_dir.push("Servo");
173    Some(config_dir)
174}
175
176#[cfg(target_os = "windows")]
177pub fn default_config_dir() -> Option<PathBuf> {
178    let mut config_dir = ::dirs::config_dir().unwrap();
179    config_dir.push("Servo");
180    Some(config_dir)
181}
182
183/// Get a Servo [`Preferences`] to use when initializing Servo by first reading the user
184/// preferences file and then overriding these preferences with the ones from the `--prefs-file`
185/// command-line argument, if given.
186fn get_preferences(prefs_files: &[PathBuf], config_dir: &Option<PathBuf>) -> Preferences {
187    // Do not read any preferences files from the disk when testing as we do not want it
188    // to throw off test results.
189    if cfg!(test) {
190        return Preferences::default();
191    }
192
193    let user_prefs_path = config_dir
194        .clone()
195        .map(|path| path.join("prefs.json"))
196        .filter(|path| path.exists());
197    let user_prefs_hash = user_prefs_path.map(read_prefs_file).unwrap_or_default();
198
199    let apply_preferences =
200        |preferences: &mut Preferences, preferences_hash: HashMap<String, PrefValue>| {
201            for (key, value) in preferences_hash.iter() {
202                preferences.set_value(key, value.clone());
203            }
204        };
205
206    let mut preferences = Preferences::default();
207    apply_preferences(&mut preferences, user_prefs_hash);
208    for pref_file_path in prefs_files.iter() {
209        apply_preferences(&mut preferences, read_prefs_file(pref_file_path))
210    }
211
212    preferences.embedder_name = "servoshell".into();
213
214    preferences
215}
216
217fn read_prefs_file<P: AsRef<Path>>(path: P) -> HashMap<String, PrefValue> {
218    read_prefs_map(&read_to_string(path).expect("Error opening user prefs"))
219}
220
221pub fn read_prefs_map(txt: &str) -> HashMap<String, PrefValue> {
222    let prefs: HashMap<String, Value> = serde_json::from_str(txt)
223        .map_err(|_| panic!("Could not parse preferences JSON"))
224        .unwrap();
225    prefs
226        .into_iter()
227        .map(|(key, value)| {
228            let value = (&value)
229                .try_into()
230                .map_err(|error| panic!("{error}"))
231                .unwrap();
232            (key, value)
233        })
234        .collect()
235}
236
237#[expect(clippy::large_enum_variant)]
238#[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
239pub(crate) enum ArgumentParsingResult {
240    ChromeProcess(Opts, Preferences, ServoShellPreferences),
241    ContentProcess(String),
242    Exit,
243    ErrorParsing,
244}
245
246enum ParseResolutionError {
247    InvalidFormat,
248    ZeroDimension,
249    ParseError(std::num::ParseIntError),
250}
251
252impl fmt::Display for ParseResolutionError {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        match self {
255            ParseResolutionError::InvalidFormat => write!(f, "invalid resolution format"),
256            ParseResolutionError::ZeroDimension => {
257                write!(f, "width and height must be greater than 0")
258            },
259            ParseResolutionError::ParseError(e) => write!(f, "{e}"),
260        }
261    }
262}
263
264/// Parse a resolution string into a Size2D.
265fn parse_resolution_string(
266    string: String,
267) -> Result<Option<Size2D<u32, DeviceIndependentPixel>>, ParseResolutionError> {
268    if string.is_empty() {
269        Ok(None)
270    } else {
271        let (width, height) = string
272            .split_once(['x', 'X'])
273            .ok_or(ParseResolutionError::InvalidFormat)?;
274
275        let width = width.trim();
276        let height = height.trim();
277        if width.is_empty() || height.is_empty() {
278            return Err(ParseResolutionError::InvalidFormat);
279        }
280
281        let width = width.parse().map_err(ParseResolutionError::ParseError)?;
282        let height = height.parse().map_err(ParseResolutionError::ParseError)?;
283        if width == 0 || height == 0 {
284            return Err(ParseResolutionError::ZeroDimension);
285        }
286
287        Ok(Some(Size2D::new(width, height)))
288    }
289}
290
291/// Parse a space or comma-separated list of stylesheet paths into a vector of
292/// [`UserStyleSheet`].
293fn parse_user_stylesheets(string: String) -> Result<Vec<Rc<UserStyleSheet>>, std::io::Error> {
294    let mut results = Vec::new();
295    for path_string in string.split([' ', ',']) {
296        let path = env::current_dir()?.join(path_string);
297        results.push(Rc::new(UserStyleSheet::new(
298            read_to_string(&path)?,
299            Url::from_file_path(&path).unwrap(),
300        )));
301    }
302    Ok(results)
303}
304
305/// This is a helper function that fulfills the following parsing task
306/// check for long/short cmd. If there is the flag with this
307/// If the flag is not there, parse `None``
308/// If the flag is there but no argument, parse `Some(default)`
309/// If the flag is there and an argument parse the argument
310fn flag_with_default_parser<S, T>(
311    short_cmd: Option<char>,
312    long_cmd: &'static str,
313    argument_help: &'static str,
314    help: &'static str,
315    default: T,
316    transform: fn(S) -> T,
317) -> impl Parser<Option<T>>
318where
319    S: FromStr + 'static,
320    <S as FromStr>::Err: fmt::Display,
321    T: Clone + 'static,
322{
323    let just_flag = if let Some(c) = short_cmd {
324        short(c).long(long_cmd)
325    } else {
326        long(long_cmd)
327    }
328    .req_flag(default)
329    .hide();
330
331    let arg = if let Some(c) = short_cmd {
332        short(c).long(long_cmd)
333    } else {
334        long(long_cmd)
335    }
336    .argument::<S>(argument_help)
337    .help(help)
338    .map(transform);
339
340    construct!([arg, just_flag]).optional()
341}
342
343fn profile() -> impl Parser<Option<OutputOptions>> {
344    flag_with_default_parser(
345        Some('p'),
346        "profile",
347        "",
348        "uses 5.0 output as standard if no argument supplied",
349        OutputOptions::Stdout(5.0),
350        |val: String| {
351            if let Ok(float) = val.parse::<f64>() {
352                OutputOptions::Stdout(float)
353            } else {
354                OutputOptions::FileName(val)
355            }
356        },
357    )
358}
359
360fn userscripts() -> impl Parser<Option<PathBuf>> {
361    let arg = long("userscripts")
362        .argument::<String>("your/directory")
363        .help("Uses userscripts in specified full path")
364        .map(PathBuf::from);
365
366    construct!([arg]).optional()
367}
368
369fn webdriver_port() -> impl Parser<Option<u16>> {
370    flag_with_default_parser(
371        None,
372        "webdriver",
373        "7000",
374        "Start remote WebDriver server on port",
375        7000,
376        |val| val,
377    )
378}
379
380fn map_debug_options(arg: String) -> Vec<String> {
381    arg.split(',').map(|s| s.to_owned()).collect()
382}
383
384#[derive(Bpaf, Clone, Debug)]
385#[bpaf(options, version(VERSION), usage("servoshell [OPTIONS] URL"))]
386// Newlines in comments are intentional to have the right formatting for the help message.
387struct CmdArgs {
388    /// Background Hang Monitor enabled.
389    #[bpaf(short('B'), long("bhm"))]
390    background_hang_monitor: bool,
391
392    ///
393    ///  Path to find SSL certificates.
394    #[bpaf(argument("/home/servo/resources/certs"))]
395    certificate_path: Option<PathBuf>,
396
397    /// Do not shutdown until all threads have finished (macos only).
398    #[bpaf(long)]
399    clean_shutdown: bool,
400
401    ///
402    ///  Config directory following xdg spec on linux platform.
403    #[bpaf(argument("~/.config/servo"))]
404    config_dir: Option<PathBuf>,
405
406    ///
407    ///  Run as a content process and connect to the given pipe.
408    #[bpaf(argument("servo-ipc-channel.abcdefg"))]
409    content_process: Option<String>,
410
411    ///
412    ///  A comma-separated string of debug options. Pass help to show available options.
413    #[bpaf(
414        short('Z'),
415        argument("style-tree,flow-tree"),
416        long,
417        map(map_debug_options),
418        fallback(vec![])
419    )]
420    debug: Vec<String>,
421
422    ///
423    ///  Device pixels per px.
424    #[bpaf(argument("1.0"))]
425    device_pixel_ratio: Option<f32>,
426
427    /// Start remote devtools server on port listening on this address. <address>:<port> and <port> are valid values.
428    #[bpaf(argument("127.0.0.1:7000"))]
429    devtools: Option<String>,
430
431    ///
432    ///  Whether or not to enable experimental web platform features.
433    #[bpaf(long)]
434    enable_experimental_web_platform_features: bool,
435
436    // Exit after Servo has loaded the page and detected a stable output image.
437    #[bpaf(short('x'), long)]
438    exit: bool,
439
440    // Use ipc_channel in singleprocess mode.
441    #[bpaf(short('I'), long("force-ipc"))]
442    force_ipc: bool,
443
444    /// Exit on thread failure instead of displaying about:failure.
445    #[bpaf(short('f'), long)]
446    hard_fail: bool,
447
448    /// Headless mode.
449    #[bpaf(short('z'), long)]
450    headless: bool,
451
452    ///
453    /// Path to a hosts file (like `/etc/hosts`).
454    /// Ignored if the `HOST_FILE` environment variable is set.
455    #[bpaf(long("host-file"), argument("/path/to/hosts"))]
456    host_file: Option<PathBuf>,
457
458    ///
459    ///  Whether or not to completely ignore certificate errors.
460    #[bpaf(long)]
461    ignore_certificate_errors: bool,
462
463    /// Number of threads to use for layout.
464    #[bpaf(short('y'), long, argument("1"))]
465    layout_threads: Option<u64>,
466
467    ///
468    ///  Directory root with unminified scripts.
469    #[bpaf(argument("~/.local/share/servo"))]
470    local_script_source: Option<PathBuf>,
471
472    #[cfg(target_env = "ohos")]
473    /// Define a custom filter for logging.
474    #[bpaf(argument("FILTER"))]
475    log_filter: Option<String>,
476
477    #[cfg(target_env = "ohos")]
478    /// Also log to a file (/data/app/el2/100/base/org.servo.servo/cache/servo.log).
479    #[bpaf(long)]
480    log_to_file: bool,
481
482    /// Should we output memory stats after a page load. Only useful if tracing is enabled
483    #[bpaf(long)]
484    memory_output: bool,
485
486    /// Run in multiprocess mode.
487    #[bpaf(short('M'), long)]
488    multiprocess: bool,
489
490    /// Do not use native titlebar.
491    #[bpaf(short('b'), long)]
492    no_native_titlebar: bool,
493
494    /// Path to an output image. The format of the image is determined by the extension.
495    /// Supports all formats that `rust-image` does.
496    #[bpaf(short('o'), argument("test.png"), long)]
497    output: Option<PathBuf>,
498
499    /// Time profiler flag and either a TSV output filename
500    /// OR an interval for output to Stdout (blank for Stdout with interval of 5s).
501    #[bpaf(external)]
502    profile: Option<OutputOptions>,
503
504    ///
505    ///  Path to dump a self-contained HTML timeline of profiler traces.
506    #[bpaf(argument("trace.html"), long)]
507    profiler_trace_path: Option<PathBuf>,
508
509    ///
510    ///  A preference to set.
511    #[bpaf(argument("dom_bluetooth_enabled"), many)]
512    pref: Vec<String>,
513
514    ///
515    ///  Load in additional prefs from a file.
516    #[bpaf(long, argument("/path/to/prefs.json"), many)]
517    prefs_file: Vec<PathBuf>,
518
519    ///
520    ///  Probability of randomly closing a pipeline (for testing constellation hardening).
521    #[bpaf(argument("0.25"))]
522    random_pipeline_closure_probability: Option<f32>,
523
524    /// A fixed seed for repeatbility of random pipeline closure.
525    random_pipeline_closure_seed: Option<usize>,
526
527    /// Run in a sandbox if multiprocess.
528    #[bpaf(short('S'), long)]
529    sandbox: bool,
530
531    /// Shaders will be loaded from the specified directory instead of using the builtin ones.
532    shaders: Option<PathBuf>,
533
534    ///
535    ///  Override the screen resolution in logical (device independent) pixels.
536    #[bpaf(long("screen-size"), argument::<String>("1024x768"),
537        parse(parse_resolution_string), fallback(None))]
538    screen_size_override: Option<Size2D<u32, DeviceIndependentPixel>>,
539
540    /// Use mouse events to simulate touch events. Left button presses will be converted to touch
541    /// and mouse movements while the left button is pressed will be converted to touch movements.
542    #[bpaf(long("simulate-touch-events"))]
543    simulate_touch_events: bool,
544
545    /// Use temporary storage (data on disk will not persist across restarts).
546    #[bpaf(long)]
547    temporary_storage: bool,
548    /// Define a custom filter for traces. Overrides `SERVO_TRACING` if set.
549    #[bpaf(long("tracing-filter"), argument("FILTER"))]
550    tracing_filter: Option<String>,
551
552    /// Unminify Javascript.
553    #[bpaf(long)]
554    unminify_js: bool,
555
556    /// Unminify Css.
557    #[bpaf(long)]
558    unminify_css: bool,
559
560    ///
561    ///  Set custom user agent string (or ios / android / desktop for platform default).
562    #[bpaf(short('u'),long,argument::<String>("NCSA mosaic/1.0 (X11;SunOS 4.1.4 sun4m"))]
563    user_agent: Option<String>,
564
565    ///
566    ///  Uses userscripts in a specified full path.
567    #[bpaf(external)]
568    userscripts: Option<PathBuf>,
569
570    ///
571    /// Add each of the given UTF-8 encoded CSS files in the space or comma-separated
572    /// list as user stylesheet to apply to every page loaded.
573    #[bpaf(argument::<String>("file.css"), parse(parse_user_stylesheets),
574    fallback(vec![]))]
575    user_stylesheet: Vec<Rc<UserStyleSheet>>,
576
577    /// Start remote WebDriver server on port.
578    #[bpaf(external)]
579    webdriver_port: Option<u16>,
580
581    ///
582    ///  Set the initial window size in logical (device independent) pixels.
583    #[bpaf(argument::<String>("1024x740"), parse(parse_resolution_string), fallback(None))]
584    window_size: Option<Size2D<u32, DeviceIndependentPixel>>,
585
586    /// Set js_mem_gc_zeal_level=2 and js_mem_gc_zeal_frequency=1
587    #[bpaf(long)]
588    zealous_gc: bool,
589
590    /// The url we should load.
591    #[bpaf(positional("URL"), fallback(String::from("https://www.servo.org")))]
592    url: String,
593}
594
595fn update_preferences_from_command_line_arguments(
596    preferences: &mut Preferences,
597    cmd_args: &CmdArgs,
598) {
599    #[cfg(feature = "devtools")]
600    if let Some(listen_address) = &cmd_args.devtools {
601        preferences.devtools_server_enabled = true;
602        preferences.devtools_server_listen_address = listen_address.clone();
603    }
604
605    if cmd_args.enable_experimental_web_platform_features {
606        for pref in EXPERIMENTAL_PREFS {
607            preferences.set_value(pref, PrefValue::Bool(true));
608        }
609    }
610
611    for pref in &cmd_args.pref {
612        let split: Vec<&str> = pref.splitn(2, '=').collect();
613        let pref_name = split[0];
614        let pref_value = PrefValue::from_booleanish_str(split.get(1).copied().unwrap_or("true"));
615        preferences.set_value(pref_name, pref_value);
616    }
617
618    if let Some(layout_threads) = cmd_args.layout_threads {
619        preferences.layout_threads = layout_threads;
620    }
621
622    if cmd_args.headless && preferences.media_glvideo_enabled {
623        warn!("GL video rendering is not supported on headless windows.");
624        preferences.media_glvideo_enabled = false;
625    }
626
627    if let Some(user_agent) = cmd_args.user_agent.clone() {
628        preferences.user_agent = user_agent;
629    }
630
631    if cmd_args.webdriver_port.is_some() {
632        preferences.dom_testing_html_input_element_select_files_enabled = true;
633    }
634
635    if cmd_args.zealous_gc {
636        #[cfg(not(feature = "debugmozjs"))]
637        warn!(
638            "The zealous-gc option requires Servo to be compiled with debug-mozjs to take effect."
639        );
640
641        preferences.js_mem_gc_zeal_level = 2;
642        preferences.js_mem_gc_zeal_frequency = 1;
643    }
644}
645
646/// Parse Commandline arguments
647///
648/// Please note that e.g. `env::args` traditionally includes the binary name as the first
649///  argument; However, the binary name must not be included in `args_without_binary`.
650pub(crate) fn parse_command_line_arguments<'a>(
651    args_without_binary: impl Into<Args<'a>>,
652) -> ArgumentParsingResult {
653    parse_arguments_helper(args_without_binary.into())
654}
655fn parse_arguments_helper(args_without_binary: Args) -> ArgumentParsingResult {
656    let cmd_args = cmd_args().run_inner(args_without_binary);
657    let cmd_args = match cmd_args {
658        Ok(cmd_args) => cmd_args,
659        Err(error) => {
660            // Servo will exit after printing the parsing error, which makes the stdout / stderr
661            // redirection via a seperate thread racy, so we log directly to the system logger.
662            if cfg!(target_os = "android") || cfg!(target_env = "ohos") {
663                match &error {
664                    ParseFailure::Stderr(doc) => log::error!("{doc}"),
665                    // '--help' will be parsed by the next one.
666                    ParseFailure::Stdout(doc, _) => log::error!("{doc}"),
667                    ParseFailure::Completion(_) => log::error!("Not supported on these platforms"),
668                }
669            } else {
670                error.print_message(80);
671            }
672
673            return if error.exit_code() == 0 {
674                ArgumentParsingResult::Exit
675            } else {
676                ArgumentParsingResult::ErrorParsing
677            };
678        },
679    };
680
681    // If this is the content process, we'll receive the real options over IPC. So fill in some dummy options for now.
682    if let Some(content_process) = cmd_args.content_process {
683        return ArgumentParsingResult::ContentProcess(content_process);
684    }
685
686    let config_dir = cmd_args
687        .config_dir
688        .clone()
689        .or_else(default_config_dir)
690        .inspect(|config_dir| {
691            if !config_dir.exists() {
692                fs::create_dir_all(config_dir).expect("Could not create config_dir");
693            }
694        });
695    let temporary_storage = cmd_args.temporary_storage;
696    if let Some(ref time_profiler_trace_path) = cmd_args.profiler_trace_path {
697        let mut path = PathBuf::from(time_profiler_trace_path);
698        path.pop();
699        fs::create_dir_all(&path).expect("Error in creating profiler trace path");
700    }
701
702    let mut preferences = get_preferences(&cmd_args.prefs_file, &config_dir);
703
704    update_preferences_from_command_line_arguments(&mut preferences, &cmd_args);
705
706    // FIXME: enable JIT compilation on 32-bit Android after the startup crash issue (#31134) is fixed.
707    if cfg!(target_os = "android") && cfg!(target_pointer_width = "32") {
708        preferences.js_baseline_interpreter_enabled = false;
709        preferences.js_baseline_jit_enabled = false;
710        preferences.js_ion_enabled = false;
711    }
712
713    // Make sure the default window size is not larger than any provided screen size.
714    let default_window_size = Size2D::new(1024, 740);
715    let default_window_size = cmd_args
716        .screen_size_override
717        .map_or(default_window_size, |screen_size_override| {
718            default_window_size.min(screen_size_override)
719        });
720
721    #[cfg(not(all(feature = "tracing", feature = "tracing-hitrace")))]
722    if cmd_args.memory_output {
723        log::error!("Memory reporting only works with tracing and tracing-hitrace enabled.");
724    }
725
726    let servoshell_preferences = ServoShellPreferences {
727        url: Some(cmd_args.url),
728        no_native_titlebar: cmd_args.no_native_titlebar,
729        device_pixel_ratio_override: cmd_args.device_pixel_ratio,
730        clean_shutdown: cmd_args.clean_shutdown,
731        headless: cmd_args.headless,
732        tracing_filter: cmd_args.tracing_filter,
733        initial_window_size: cmd_args.window_size.unwrap_or(default_window_size),
734        screen_size_override: cmd_args.screen_size_override,
735        simulate_touch_events: cmd_args.simulate_touch_events,
736        webdriver_port: Cell::new(cmd_args.webdriver_port),
737        output_image_path: cmd_args.output.map(|p| p.to_string_lossy().into_owned()),
738        exit_after_stable_image: cmd_args.exit,
739        userscripts_directory: cmd_args.userscripts,
740        user_stylesheets: cmd_args.user_stylesheet,
741        experimental_preferences_enabled: cmd_args.enable_experimental_web_platform_features,
742        #[cfg(target_env = "ohos")]
743        log_filter: cmd_args.log_filter.or_else(|| {
744            (!preferences.log_filter.is_empty()).then(|| preferences.log_filter.clone())
745        }),
746        #[cfg(target_env = "ohos")]
747        log_to_file: cmd_args.log_to_file,
748        memory_output: cmd_args.memory_output,
749        ..Default::default()
750    };
751
752    let Ok(debug_options) = parse_diagnostics_logging(cmd_args.debug) else {
753        return ArgumentParsingResult::ErrorParsing;
754    };
755
756    #[cfg(not(feature = "multiprocess"))]
757    if cmd_args.multiprocess || cmd_args.force_ipc {
758        log::error!("IPC was disabled at compile time. IPC and multiprocess modes are disabled");
759    }
760
761    let opts = Opts {
762        debug: debug_options,
763        time_profiling: cmd_args.profile,
764        time_profiler_trace_path: cmd_args
765            .profiler_trace_path
766            .map(|p| p.to_string_lossy().into_owned()),
767        hard_fail: cmd_args.hard_fail,
768        multiprocess: cmd_args.multiprocess,
769        background_hang_monitor: cmd_args.background_hang_monitor,
770        sandbox: cmd_args.sandbox,
771        random_pipeline_closure_probability: cmd_args.random_pipeline_closure_probability,
772        random_pipeline_closure_seed: cmd_args.random_pipeline_closure_seed,
773        config_dir,
774        temporary_storage,
775        shaders_path: cmd_args.shaders,
776        certificate_path: cmd_args
777            .certificate_path
778            .map(|p| p.to_string_lossy().into_owned()),
779        host_file: cmd_args.host_file,
780        ignore_certificate_errors: cmd_args.ignore_certificate_errors,
781        unminify_js: cmd_args.unminify_js,
782        local_script_source: cmd_args
783            .local_script_source
784            .map(|p| p.to_string_lossy().into_owned()),
785        unminify_css: cmd_args.unminify_css,
786        force_ipc: cmd_args.force_ipc,
787    };
788
789    ArgumentParsingResult::ChromeProcess(opts, preferences, servoshell_preferences)
790}
791
792/// Parse the '-Z' command-line flags.
793fn parse_diagnostics_logging(cli_options: Vec<String>) -> Result<DiagnosticsLogging, ()> {
794    fn print_option(name: &str, description: &str) {
795        println!("\t{:<35} {}", name, description);
796    }
797
798    if cli_options.contains(&"help".into()) {
799        // TODO: Remove hardcoded binary name by perhaps receiving this as an argument.
800        println!("Usage: servoshell -Z option,[option,...]\n\twhere options include:");
801        print_option("help", "Show this help message");
802        for option in DiagnosticsLoggingOption::iter() {
803            print_option(option.help_option(), option.help_message())
804        }
805
806        std::process::exit(0);
807    }
808
809    let mut diagnostics_logging = DiagnosticsLogging::new();
810    for cli_option in cli_options.iter() {
811        if let Err(error) = diagnostics_logging.extend_from_string(cli_option) {
812            eprintln!("Could not parse debug logging option: {error}");
813            return Err(());
814        }
815    }
816
817    Ok(diagnostics_logging)
818}
819
820#[cfg(test)]
821fn test_parse_pref(arg: &str) -> Preferences {
822    let args = ["--pref", arg];
823    match parse_command_line_arguments(args.as_slice()) {
824        ArgumentParsingResult::ContentProcess(..) => {
825            unreachable!("No preferences for content process")
826        },
827        ArgumentParsingResult::ChromeProcess(_, preferences, _) => preferences,
828        ArgumentParsingResult::Exit => {
829            panic!("we supplied a --pref argument above which should be parsed")
830        },
831        ArgumentParsingResult::ErrorParsing => {
832            unreachable!("we supplied a --pref argument above which should be parsed")
833        },
834    }
835}
836
837#[test]
838fn test_parse_pref_from_command_line() {
839    // Test with boolean values.
840    let preferences = test_parse_pref("dom_bluetooth_enabled=true");
841    assert!(preferences.dom_bluetooth_enabled);
842
843    let preferences = test_parse_pref("dom_bluetooth_enabled=false");
844    assert!(!preferences.dom_bluetooth_enabled);
845
846    // Test with numbers
847    let preferences = test_parse_pref("layout_threads=42");
848    assert_eq!(preferences.layout_threads, 42);
849
850    // Test with unsigned numbers
851    let preferences = test_parse_pref("network_http_cache_size=50");
852    assert_eq!(preferences.network_http_cache_size, 50);
853    let preferences = test_parse_pref("network_connection_timeout=30");
854    assert_eq!(preferences.network_connection_timeout, 30);
855
856    // Test string.
857    let preferences = test_parse_pref("fonts_default=Lucida");
858    assert_eq!(preferences.fonts_default, "Lucida");
859
860    // Test with no value (defaults to true).
861    let preferences = test_parse_pref("dom_bluetooth_enabled");
862    assert!(preferences.dom_bluetooth_enabled);
863}
864
865#[test]
866fn test_invalid_prefs_from_command_line_panics() {
867    let err_msg = std::panic::catch_unwind(|| {
868        test_parse_pref("doesntexist=true");
869    })
870    .err()
871    .and_then(|a| a.downcast_ref::<String>().cloned())
872    .expect("Should panic");
873    assert_eq!(
874        err_msg, "Unknown preference: \"doesntexist\"",
875        "Message should describe the problem"
876    )
877}
878
879#[test]
880fn test_create_prefs_map() {
881    let json_str = "{
882        \"layout.css.writing-mode.enabled\": true,
883        \"network.mime.sniff\": false,
884        \"shell.homepage\": \"https://servo.org\"
885    }";
886    assert_eq!(read_prefs_map(json_str).len(), 3);
887}
888
889#[cfg(test)]
890fn test_parse(arg: &str) -> (Opts, Preferences, ServoShellPreferences) {
891    // bpaf requires the arguments that are separated by whitespace to be different elements of the vector.
892    let args_split: Vec<&str> = arg.split_whitespace().collect();
893    match parse_command_line_arguments(args_split.as_slice()) {
894        ArgumentParsingResult::ContentProcess(..) => {
895            unreachable!("No preferences for content process")
896        },
897        ArgumentParsingResult::ChromeProcess(opts, preferences, servoshell_preferences) => {
898            (opts, preferences, servoshell_preferences)
899        },
900        ArgumentParsingResult::Exit | ArgumentParsingResult::ErrorParsing => {
901            unreachable!("We always have valid preference in our test cases")
902        },
903    }
904}
905
906#[test]
907fn test_profiling_args() {
908    assert_eq!(
909        test_parse("-p").0.time_profiling.unwrap(),
910        OutputOptions::Stdout(5_f64)
911    );
912
913    assert_eq!(
914        test_parse("-p 10").0.time_profiling.unwrap(),
915        OutputOptions::Stdout(10_f64)
916    );
917
918    assert_eq!(
919        test_parse("-p 10.0").0.time_profiling.unwrap(),
920        OutputOptions::Stdout(10_f64)
921    );
922
923    assert_eq!(
924        test_parse("-p foo.txt").0.time_profiling.unwrap(),
925        OutputOptions::FileName(String::from("foo.txt"))
926    );
927}
928
929#[test]
930fn test_servoshell_cmd() {
931    assert_eq!(
932        test_parse("--screen-size=1000x1000")
933            .2
934            .screen_size_override
935            .unwrap(),
936        Size2D::new(1000, 1000)
937    );
938
939    assert_eq!(
940        test_parse("--certificate-path=/tmp/test")
941            .0
942            .certificate_path
943            .unwrap(),
944        String::from("/tmp/test")
945    );
946
947    assert!({
948        let p = test_parse("--zealous-gc").1;
949        p.js_mem_gc_zeal_level == 2 && p.js_mem_gc_zeal_frequency == 1
950    });
951}