use serde_json::json;
use crate::activity::Activity;
use crate::view::View;
use crate::error::Result;
pub struct WebView {
view: View,
aid: i64,
}
impl WebView {
pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
eprintln!("[DEBUG] WebView::new() - creating WebView...");
let mut params = json!({
"aid": activity.id()
});
if let Some(parent_id) = parent {
params["parent"] = json!(parent_id);
}
eprintln!("[DEBUG] WebView::new() - sending createWebView...");
let response = activity.send_read(&json!({
"method": "createWebView",
"params": params
}))?;
eprintln!("[DEBUG] WebView::new() - got response: {:?}", response);
let id = response
.as_i64()
.ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
Ok(WebView {
view: View::new(id),
aid: activity.id(),
})
}
pub fn id(&self) -> i64 {
self.view.id()
}
pub fn view(&self) -> &View {
&self.view
}
pub fn load_uri(&self, activity: &mut Activity, uri: &str) -> Result<()> {
activity.send(&json!({
"method": "loadURI",
"params": {
"aid": self.aid,
"id": self.view.id(),
"uri": uri
}
}))?;
Ok(())
}
pub fn set_data(&self, activity: &mut Activity, data: &str) -> Result<()> {
let encoded = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, data.as_bytes());
activity.send(&json!({
"method": "setData",
"params": {
"aid": self.aid,
"id": self.view.id(),
"doc": encoded,
"base64": true
}
}))?;
Ok(())
}
pub fn allow_javascript(&self, activity: &mut Activity, allow: bool) -> Result<bool> {
let response = activity.send_read(&json!({
"method": "allowJavascript",
"params": {
"aid": self.aid,
"id": self.view.id(),
"allow": allow
}
}))?;
Ok(response.as_bool().unwrap_or(false))
}
pub fn allow_content_uri(&self, activity: &mut Activity, allow: bool) -> Result<()> {
activity.send(&json!({
"method": "allowContentURI",
"params": {
"aid": self.aid,
"id": self.view.id(),
"allow": allow
}
}))?;
Ok(())
}
pub fn allow_navigation(&self, activity: &mut Activity, allow: bool) -> Result<()> {
activity.send(&json!({
"method": "allowNavigation",
"params": {
"aid": self.aid,
"id": self.view.id(),
"allow": allow
}
}))?;
Ok(())
}
pub fn evaluate_js(&self, activity: &mut Activity, code: &str) -> Result<()> {
activity.send(&json!({
"method": "evaluateJS",
"params": {
"aid": self.aid,
"id": self.view.id(),
"code": code
}
}))?;
Ok(())
}
pub fn go_back(&self, activity: &mut Activity) -> Result<()> {
activity.send(&json!({
"method": "goBack",
"params": {
"aid": self.aid,
"id": self.view.id()
}
}))?;
Ok(())
}
pub fn go_forward(&self, activity: &mut Activity) -> Result<()> {
activity.send(&json!({
"method": "goForward",
"params": {
"aid": self.aid,
"id": self.view.id()
}
}))?;
Ok(())
}
}