Allow setting userscripts directly without the need of files (#35388)

* Allow settings userscripts through preferences

Signed-off-by: Tony <legendmastertony@gmail.com>

* mach fmt instead of cargo fmt

Signed-off-by: Tony <legendmastertony@gmail.com>

* Fix pref loading not working for array values

Signed-off-by: Tony <legendmastertony@gmail.com>

* Use pref! in userscripts instead

Signed-off-by: Tony <legendmastertony@gmail.com>

* Implement the model jdm suggested
- Remove userscripts from all places and move it to servoshell
- Add in `UserContentManager` struct and passing it through `Servo::new`
all the way down to script thread

Signed-off-by: Tony <legendmastertony@gmail.com>

* Apply suggestions from code review and format

Signed-off-by: Tony <legendmastertony@gmail.com>

* Revert unrelated change

Signed-off-by: Tony <legendmastertony@gmail.com>

---------

Signed-off-by: Tony <legendmastertony@gmail.com>
Signed-off-by: Tony <68118705+Legend-Master@users.noreply.github.com>
This commit is contained in:
Tony 2025-03-27 11:00:08 +08:00 committed by GitHub
parent 53a2e61fec
commit 5a76906d64
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 143 additions and 51 deletions

View file

@ -6,6 +6,7 @@
use std::cell::Cell;
use std::collections::HashMap;
use std::path::Path;
use std::rc::Rc;
use std::time::Instant;
use std::{env, fs};
@ -16,6 +17,7 @@ use servo::config::opts::Opts;
use servo::config::prefs::Preferences;
use servo::servo_config::pref;
use servo::servo_url::ServoUrl;
use servo::user_content_manager::{UserContentManager, UserScript};
use servo::webxr::glwindow::GlWindowDiscovery;
#[cfg(target_os = "windows")]
use servo::webxr::openxr::{AppInfo, OpenXrDiscovery};
@ -146,6 +148,13 @@ impl App {
}
}
let mut user_content_manager = UserContentManager::new();
for script in load_userscripts(self.servoshell_preferences.userscripts_directory.as_deref())
.expect("Loading userscripts failed")
{
user_content_manager.add_script(script);
}
let servo = Servo::new(
self.opts.clone(),
self.preferences.clone(),
@ -153,6 +162,7 @@ impl App {
embedder,
Rc::new(UpcastedWindow(window.clone())),
self.servoshell_preferences.user_agent.clone(),
user_content_manager,
);
servo.setup_logging();
@ -442,3 +452,20 @@ impl ApplicationHandler<WakerEvent> for App {
self.suspended.set(true);
}
}
fn load_userscripts(userscripts_directory: Option<&Path>) -> std::io::Result<Vec<UserScript>> {
let mut userscripts = Vec::new();
if let Some(userscripts_directory) = &userscripts_directory {
let mut files = std::fs::read_dir(userscripts_directory)?
.map(|e| e.map(|entry| entry.path()))
.collect::<Result<Vec<_>, _>>()?;
files.sort();
for file in files {
userscripts.push(UserScript {
script: std::fs::read_to_string(&file)?,
source_file: Some(file),
});
}
}
Ok(userscripts)
}