Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting init script through cli #246

Merged
merged 16 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ pub struct CliArgs {
pub resource_dir: Option<PathBuf>,
/// Override the user agent
pub user_agent: Option<String>,
/// Script to run on document started to load
pub init_script: Option<String>,
/// The directory to load userscripts from
pub userscripts_directory: Option<String>,
/// Initial window's zoom level
pub zoom_level: Option<f32>,
}
Expand Down Expand Up @@ -104,6 +108,18 @@ fn parse_cli_args() -> Result<CliArgs, getopts::Fail> {
"Override the user agent",
"'VersoView/1.0'",
);
opts.optopt(
"",
"init-script",
"Script to run on document started to load",
"console.log('hello world')",
);
opts.optopt(
"",
"userscripts-directory",
"The directory to load userscripts from",
"resources/user-agent-js/",
);

opts.optopt(
"w",
Expand Down Expand Up @@ -176,6 +192,8 @@ fn parse_cli_args() -> Result<CliArgs, getopts::Fail> {
};

let user_agent = matches.opt_str("user-agent");
let init_script = matches.opt_str("init-script");
let userscripts_directory = matches.opt_str("userscripts-directory");

let mut window_attributes = winit::window::Window::default_attributes();

Expand Down Expand Up @@ -245,6 +263,8 @@ fn parse_cli_args() -> Result<CliArgs, getopts::Fail> {
devtools_port,
profiler_settings,
user_agent,
init_script,
userscripts_directory,
zoom_level,
})
}
Expand Down Expand Up @@ -273,6 +293,10 @@ impl Config {
opts.time_profiler_trace_path = profiler_settings.trace_path.clone();
}

if let Some(ref userscripts_directory) = args.userscripts_directory {
opts.userscripts = Some(userscripts_directory.clone());
}

let resource_dir = args.resource_dir.clone().unwrap_or(resources_dir_path());

Self {
Expand Down
3 changes: 3 additions & 0 deletions src/verso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ impl Verso {
.clone()
.unwrap_or_else(|| default_user_agent_string().to_string())
.into();
let init_script = config.args.init_script.clone();
let zoom_level = config.args.zoom_level;

config.init();
Expand Down Expand Up @@ -389,6 +390,8 @@ impl Verso {
window.create_tab(&constellation_sender, initial_url.into());
}

window.set_init_script(init_script);

let mut windows = HashMap::new();
windows.insert(window.id(), (window, webrender_document));

Expand Down
2 changes: 1 addition & 1 deletion src/webview/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod webview;
/// WebView
pub use webview::{Panel, WebView};
pub use webview::{execute_script, Panel, WebView};
/// Context Menu
pub mod context_menu;
/// Prompt Dialog
Expand Down
85 changes: 57 additions & 28 deletions src/webview/webview.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
use arboard::Clipboard;
use base::id::{BrowsingContextId, WebViewId};
use base::id::WebViewId;
use compositing_traits::ConstellationMsg;
use crossbeam_channel::Sender;
use embedder_traits::{
CompositorEventVariant, EmbedderMsg, PermissionPrompt, PermissionRequest,
PromptCredentialsInput, PromptDefinition, PromptResult, TraversalDirection,
};
use ipc_channel::ipc;
use script_traits::{
webdriver_msg::{WebDriverJSResult, WebDriverScriptCommand},
WebDriverCommandMsg,
};
use script_traits::webdriver_msg::{WebDriverJSResult, WebDriverScriptCommand};
use servo_url::ServoUrl;
use url::Url;
use versoview_messages::ToControllerMessage;
Expand All @@ -37,7 +34,7 @@ pub struct WebView {
}

impl WebView {
/// Create a web view from Winit window.
/// Create a web view.
pub fn new(webview_id: WebViewId, rect: DeviceIntRect) -> Self {
Self { webview_id, rect }
}
Expand Down Expand Up @@ -79,8 +76,7 @@ impl Window {
) {
log::trace!("Verso WebView {webview_id:?} is handling Embedder message: {message:?}",);
match message {
EmbedderMsg::LoadStart(_)
| EmbedderMsg::HeadParsed(_)
EmbedderMsg::HeadParsed(_)
| EmbedderMsg::WebViewOpened(_)
| EmbedderMsg::WebViewClosed(_) => {
// Most WebView messages are ignored because it's done by compositor.
Expand All @@ -98,6 +94,11 @@ impl Window {
w
);
}
EmbedderMsg::LoadStart(_) => {
if let Some(init_script) = &self.init_script {
execute_script_async(&sender, &webview_id, init_script);
}
}
EmbedderMsg::LoadComplete(_webview_id) => {
self.window.request_redraw();
send_to_constellation(sender, ConstellationMsg::FocusWebView(webview_id));
Expand All @@ -115,16 +116,7 @@ impl Window {
serde_json::to_string(&webview_id).unwrap(),
title.as_str()
);

let (tx, rx) = ipc::channel::<WebDriverJSResult>().unwrap();
send_to_constellation(
sender,
ConstellationMsg::WebDriverCommand(WebDriverCommandMsg::ScriptCommand(
BrowsingContextId::from(panel.webview.webview_id),
WebDriverScriptCommand::ExecuteScript(script, tx),
)),
);
let _ = rx.recv();
let _ = execute_script(sender, &panel.webview.webview_id, script);
}
}
EmbedderMsg::AllowNavigationRequest(_webview_id, id, url) => {
Expand Down Expand Up @@ -183,18 +175,11 @@ impl Window {
.set_history(webview_id, list.clone(), index);
let url = list.get(index).unwrap();
if let Some(panel) = self.panel.as_ref() {
let (tx, rx) = ipc::channel::<WebDriverJSResult>().unwrap();
send_to_constellation(
let _ = execute_script(
sender,
ConstellationMsg::WebDriverCommand(WebDriverCommandMsg::ScriptCommand(
BrowsingContextId::from(panel.webview.webview_id),
WebDriverScriptCommand::ExecuteScript(
format!("window.navbar.setNavbarUrl('{}')", url.as_str()),
tx,
),
)),
&panel.webview.webview_id,
format!("window.navbar.setNavbarUrl('{}')", url.as_str()),
);
let _ = rx.recv();
}
}
EmbedderMsg::EventDelivered(_webview_id, event) => {
Expand Down Expand Up @@ -637,3 +622,47 @@ impl Window {
false
}
}

/// Blocking execute a script on this webview
pub fn execute_script(
constellation_sender: &Sender<ConstellationMsg>,
webview: &WebViewId,
js: impl ToString,
) -> WebDriverJSResult {
let (result_sender, result_receiver) = ipc::channel::<WebDriverJSResult>().unwrap();
send_to_constellation(
constellation_sender,
ConstellationMsg::WebDriverCommand(script_traits::WebDriverCommandMsg::ScriptCommand(
webview.0,
WebDriverScriptCommand::ExecuteScript(js.to_string(), result_sender),
)),
);
result_receiver.recv().unwrap()
}

/// Execute a script asynchronous on this webview
pub fn execute_script_async(
constellation_sender: &Sender<ConstellationMsg>,
webview: &WebViewId,
js: impl ToString,
) {
execute_script_async_with_callback(constellation_sender, webview, js, |_| {})
}

/// Execute a script asynchronous on this webview with a callback processing the result
pub fn execute_script_async_with_callback(
constellation_sender: &Sender<ConstellationMsg>,
webview: &WebViewId,
js: impl ToString,
callback: impl FnOnce(WebDriverJSResult) + Send + 'static,
) {
let (result_sender, result_receiver) = ipc::channel::<WebDriverJSResult>().unwrap();
send_to_constellation(
constellation_sender,
ConstellationMsg::WebDriverCommand(script_traits::WebDriverCommandMsg::ScriptCommand(
webview.0,
WebDriverScriptCommand::ExecuteAsyncScript(js.to_string(), result_sender),
)),
);
std::thread::spawn(move || callback(result_receiver.recv().unwrap()));
}
51 changes: 25 additions & 26 deletions src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,13 @@ use glutin::{
surface::{Surface, WindowSurface},
};
use glutin_winit::DisplayBuilder;
use ipc_channel::ipc;
use ipc_channel::ipc::IpcSender;
use keyboard_types::{Code, KeyState, KeyboardEvent, Modifiers};
#[cfg(any(target_os = "macos", target_os = "windows"))]
use muda::{Menu as MudaMenu, MenuEvent, MenuEventReceiver, MenuItem};
#[cfg(any(target_os = "macos", target_os = "windows"))]
use raw_window_handle::HasWindowHandle;
use script_traits::{
webdriver_msg::{WebDriverJSResult, WebDriverJSValue, WebDriverScriptCommand},
WebDriverCommandMsg,
};
use script_traits::webdriver_msg::WebDriverJSValue;
use servo_url::ServoUrl;
use versoview_messages::ToControllerMessage;
use webrender_api::{
Expand All @@ -47,6 +44,7 @@ use crate::{
verso::send_to_constellation,
webview::{
context_menu::{ContextMenu, Menu},
execute_script,
prompt::PromptSender,
Panel, WebView,
},
Expand All @@ -73,6 +71,8 @@ pub struct Window {
pub(crate) panel: Option<Panel>,
/// The WebView of this window.
// pub(crate) webview: Option<WebView>,
/// Script to run on document started to load
pub(crate) init_script: Option<String>,
/// Event listeners registered from the webview controller
pub(crate) event_listeners: EventListeners,
/// The mouse physical position in the web view.
Expand Down Expand Up @@ -135,6 +135,7 @@ impl Window {
window,
surface,
panel: None,
init_script: None,
event_listeners: Default::default(),
mouse_position: Default::default(),
modifiers_state: Cell::new(ModifiersState::default()),
Expand Down Expand Up @@ -179,6 +180,7 @@ impl Window {
surface,
panel: None,
// webview: None,
init_script: None,
event_listeners: Default::default(),
mouse_position: Default::default(),
modifiers_state: Cell::new(ModifiersState::default()),
Expand Down Expand Up @@ -252,20 +254,13 @@ impl Window {
webview.set_size(content_size);

if let Some(panel) = &self.panel {
let (tx, rx) = ipc::channel::<WebDriverJSResult>().unwrap();
let cmd: String = format!(
"window.navbar.addTab('{}', {})",
serde_json::to_string(&webview.webview_id).unwrap(),
true,
);
send_to_constellation(
constellation_sender,
ConstellationMsg::WebDriverCommand(WebDriverCommandMsg::ScriptCommand(
panel.webview.webview_id.into(),
WebDriverScriptCommand::ExecuteScript(cmd, tx),
)),
);
let _ = rx.recv();

let _ = execute_script(constellation_sender, &panel.webview.webview_id, cmd);
}

self.tab_manager.append_tab(webview, true);
Expand All @@ -279,31 +274,30 @@ impl Window {

/// Close a tab
pub fn close_tab(&mut self, compositor: &mut IOCompositor, tab_id: WebViewId) {
let sender = compositor.constellation_chan.clone();
// if there are more than 2 tabs, we need to ask for the new active tab after tab is closed
if self.tab_manager.count() > 1 {
if let Some(panel) = &self.panel {
let (tx, rx) = ipc::channel::<WebDriverJSResult>().unwrap();
let cmd: String = format!(
"window.navbar.closeTab('{}')",
serde_json::to_string(&tab_id).unwrap()
);
send_to_constellation(
&sender,
ConstellationMsg::WebDriverCommand(WebDriverCommandMsg::ScriptCommand(
panel.webview.webview_id.into(),
WebDriverScriptCommand::ExecuteScript(cmd, tx),
)),
);
let active_tab_id = execute_script(
&compositor.constellation_chan,
&panel.webview.webview_id,
cmd,
)
.unwrap();

let active_tab_id = rx.recv().unwrap().unwrap();
if let WebDriverJSValue::String(resp) = active_tab_id {
let active_id: WebViewId = serde_json::from_str(&resp).unwrap();
self.activate_tab(compositor, active_id, self.tab_manager.count() > 2);
}
}
}
send_to_constellation(&sender, ConstellationMsg::CloseWebView(tab_id));
send_to_constellation(
&compositor.constellation_chan,
ConstellationMsg::CloseWebView(tab_id),
);
}

/// Activate a tab
Expand Down Expand Up @@ -341,6 +335,11 @@ impl Window {
}
}

/// Set the init script that runs on document started to load.
pub fn set_init_script(&mut self, init_script: Option<String>) {
self.init_script = init_script;
}

/// Handle Winit window event and return a boolean to indicate if the compositor should repaint immediately.
pub fn handle_winit_window_event(
&mut self,
Expand Down Expand Up @@ -604,7 +603,7 @@ impl Window {
webview_id: WebViewId,
message: EmbedderMsg,
sender: &Sender<ConstellationMsg>,
to_controller_sender: &Option<ipc::IpcSender<ToControllerMessage>>,
to_controller_sender: &Option<IpcSender<ToControllerMessage>>,
clipboard: Option<&mut Clipboard>,
compositor: &mut IOCompositor,
) -> bool {
Expand Down