use crate::error::Result;
use crate::protocol::{BrowserContext, Page};
use crate::server::channel::Channel;
use crate::server::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
use crate::server::connection::ConnectionExt;
use serde::Deserialize;
use serde_json::Value;
use std::any::Any;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone)]
pub struct Browser {
base: ChannelOwnerImpl,
version: String,
name: String,
is_connected: Arc<AtomicBool>,
}
impl Browser {
pub fn new(
parent: Arc<dyn ChannelOwner>,
type_name: String,
guid: Arc<str>,
initializer: Value,
) -> Result<Self> {
let base = ChannelOwnerImpl::new(
ParentOrConnection::Parent(parent),
type_name,
guid,
initializer.clone(),
);
let version = initializer["version"]
.as_str()
.ok_or_else(|| {
crate::error::Error::ProtocolError(
"Browser initializer missing 'version' field".to_string(),
)
})?
.to_string();
let name = initializer["name"]
.as_str()
.ok_or_else(|| {
crate::error::Error::ProtocolError(
"Browser initializer missing 'name' field".to_string(),
)
})?
.to_string();
Ok(Self {
base,
version,
name,
is_connected: Arc::new(AtomicBool::new(true)),
})
}
pub fn version(&self) -> &str {
&self.version
}
pub fn name(&self) -> &str {
&self.name
}
pub fn is_connected(&self) -> bool {
self.is_connected.load(Ordering::SeqCst)
}
fn channel(&self) -> &Channel {
self.base.channel()
}
pub async fn new_context(&self) -> Result<BrowserContext> {
#[derive(Deserialize)]
struct NewContextResponse {
context: GuidRef,
}
#[derive(Deserialize)]
struct GuidRef {
#[serde(deserialize_with = "crate::server::connection::deserialize_arc_str")]
guid: Arc<str>,
}
let response: NewContextResponse = self
.channel()
.send("newContext", serde_json::json!({}))
.await?;
let context: BrowserContext = self
.connection()
.get_typed::<BrowserContext>(&response.context.guid)
.await?;
Ok(context)
}
pub async fn new_context_with_options(
&self,
mut options: crate::protocol::BrowserContextOptions,
) -> Result<BrowserContext> {
#[derive(Deserialize)]
struct NewContextResponse {
context: GuidRef,
}
#[derive(Deserialize)]
struct GuidRef {
#[serde(deserialize_with = "crate::server::connection::deserialize_arc_str")]
guid: Arc<str>,
}
if let Some(path) = &options.storage_state_path {
let file_content = tokio::fs::read_to_string(path).await.map_err(|e| {
crate::error::Error::ProtocolError(format!(
"Failed to read storage state file '{}': {}",
path, e
))
})?;
let storage_state: crate::protocol::StorageState = serde_json::from_str(&file_content)
.map_err(|e| {
crate::error::Error::ProtocolError(format!(
"Failed to parse storage state file '{}': {}",
path, e
))
})?;
options.storage_state = Some(storage_state);
options.storage_state_path = None; }
let options_json = serde_json::to_value(options).map_err(|e| {
crate::error::Error::ProtocolError(format!(
"Failed to serialize context options: {}",
e
))
})?;
let response: NewContextResponse = self.channel().send("newContext", options_json).await?;
let context: BrowserContext = self
.connection()
.get_typed::<BrowserContext>(&response.context.guid)
.await?;
Ok(context)
}
pub async fn new_page(&self) -> Result<Page> {
let context = self.new_context().await?;
context.new_page().await
}
pub async fn close(&self) -> Result<()> {
let result = self
.channel()
.send_no_result("close", serde_json::json!({}))
.await;
#[cfg(windows)]
{
let is_ci = std::env::var("CI").is_ok() || std::env::var("GITHUB_ACTIONS").is_ok();
if is_ci {
tracing::debug!("[playwright-rust] Adding Windows CI browser cleanup delay");
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
}
result
}
}
impl ChannelOwner for Browser {
fn guid(&self) -> &str {
self.base.guid()
}
fn type_name(&self) -> &str {
self.base.type_name()
}
fn parent(&self) -> Option<Arc<dyn ChannelOwner>> {
self.base.parent()
}
fn connection(&self) -> Arc<dyn crate::server::connection::ConnectionLike> {
self.base.connection()
}
fn initializer(&self) -> &Value {
self.base.initializer()
}
fn channel(&self) -> &Channel {
self.base.channel()
}
fn dispose(&self, reason: crate::server::channel_owner::DisposeReason) {
self.is_connected.store(false, Ordering::SeqCst);
self.base.dispose(reason)
}
fn adopt(&self, child: Arc<dyn ChannelOwner>) {
self.base.adopt(child)
}
fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>) {
self.base.add_child(guid, child)
}
fn remove_child(&self, guid: &str) {
self.base.remove_child(guid)
}
fn on_event(&self, method: &str, params: Value) {
if method == "disconnected" {
self.is_connected.store(false, Ordering::SeqCst);
}
self.base.on_event(method, params)
}
fn was_collected(&self) -> bool {
self.base.was_collected()
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl std::fmt::Debug for Browser {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Browser")
.field("guid", &self.guid())
.field("name", &self.name)
.field("version", &self.version)
.finish()
}
}