use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use crabshell_reactive::{Signal, untrack};
use crate::capture::Capture;
use crate::geometry::{Affine, Rect, Size};
use crate::prop::{IntoProp, Prop};
use crate::style::Style;
use crate::tree::{Change, NodeId, NodeKind, Tree, borrow, replace};
use crate::widgets::{Common, Element, ElementKind, Fit, Widget, visibility_methods};
use crate::window::Window;
static NEXT_VIEW: AtomicU64 = AtomicU64::new(0);
const MAX_DROPPED: usize = 4096;
thread_local! {
static DROPPED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
}
#[doc(hidden)]
pub fn dropped_captures() -> Vec<u64> {
DROPPED.with(|dropped| std::mem::take(&mut *dropped.borrow_mut()))
}
pub(crate) fn next_id() -> u64 {
NEXT_VIEW.fetch_add(1, Ordering::Relaxed)
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum CaptureSource {
Output(String),
Toplevel(u64),
}
pub(crate) struct ScreencopyProps {
pub(crate) source: Option<Prop<CaptureSource>>,
pub(crate) capture: Option<Capture>,
pub(crate) crop: Option<Prop<Option<Rect>>>,
pub(crate) shown: Option<Signal<bool>>,
pub(crate) live: Option<Prop<bool>>,
pub(crate) paint_cursors: Option<Prop<bool>>,
pub(crate) fit: Option<Prop<Fit>>,
}
pub struct ScreencopyView {
props: ScreencopyProps,
common: Common,
}
impl ScreencopyView {
pub fn new(source: impl IntoProp<CaptureSource>) -> ScreencopyView {
ScreencopyView::with(Some(source.into_prop()), None)
}
pub fn of(capture: Capture) -> ScreencopyView {
ScreencopyView::with(None, Some(capture))
}
fn with(source: Option<Prop<CaptureSource>>, capture: Option<Capture>) -> ScreencopyView {
ScreencopyView {
props: ScreencopyProps {
source,
capture,
crop: None,
shown: None,
live: None,
paint_cursors: None,
fit: None,
},
common: Common::default(),
}
}
pub fn crop(mut self, rect: impl IntoProp<Option<Rect>>) -> ScreencopyView {
self.props.crop = Some(rect.into_prop());
self
}
pub fn shown(mut self, shown: Signal<bool>) -> ScreencopyView {
self.props.shown = Some(shown);
self
}
pub fn live(mut self, live: impl IntoProp<bool>) -> ScreencopyView {
self.props.live = Some(live.into_prop());
self
}
pub fn paint_cursors(mut self, paint: impl IntoProp<bool>) -> ScreencopyView {
self.props.paint_cursors = Some(paint.into_prop());
self
}
pub fn fit(mut self, fit: impl IntoProp<Fit>) -> ScreencopyView {
self.props.fit = Some(fit.into_prop());
self
}
pub fn style(mut self, style: impl IntoProp<Style>) -> ScreencopyView {
self.common.style = Some(style.into_prop());
self
}
visibility_methods!();
}
impl Widget for ScreencopyView {
fn into_element(self: Box<Self>) -> Element {
Element {
name: "ScreencopyView",
common: self.common,
kind: ElementKind::Capture(self.props),
children: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureFrame {
pub width: u32,
pub height: u32,
pub logical_width: u32,
pub logical_height: u32,
pub rgba: Rc<[u8]>,
}
impl CaptureFrame {
#[doc(hidden)]
pub fn drawn_part(&self, crop: Option<Rect>) -> Option<[u32; 4]> {
let pixels = u64::from(self.width) * u64::from(self.height) * 4;
if self.width == 0 || self.height == 0 || self.rgba.len() as u64 != pixels {
return None;
}
let Some(crop) = crop else {
return Some([0, 0, self.width, self.height]);
};
let sides = [crop.x, crop.y, crop.width, crop.height];
if !sides.iter().all(|side| side.is_finite()) {
return None;
}
let (width, height) = (self.width as f32, self.height as f32);
let across = width / self.logical_width.max(1) as f32;
let down = height / self.logical_height.max(1) as f32;
let left = (crop.x * across).round().max(0.0);
let top = (crop.y * down).round().max(0.0);
let right = (crop.right() * across).round().min(width);
let bottom = (crop.bottom() * down).round().min(height);
if right <= left || bottom <= top {
return None;
}
let [left, top, right, bottom] = [left, top, right, bottom].map(|side| side as u32);
Some([left, top, right - left, bottom - top])
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CaptureRequest {
pub id: u64,
pub source: CaptureSource,
pub live: bool,
pub paint_cursors: bool,
pub size: Size,
}
pub(crate) struct CaptureNode {
pub(crate) id: u64,
pub(crate) source: Option<CaptureSource>,
pub(crate) live: bool,
pub(crate) paint_cursors: bool,
pub(crate) fit: Fit,
pub(crate) crop: Option<Rect>,
pub(crate) frame: Option<CaptureFrame>,
pub(crate) shown: Option<Signal<bool>>,
pub(crate) seen: Seen,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Seen {
#[default]
Unseen,
Drawn,
Shown,
}
impl Drop for CaptureNode {
fn drop(&mut self) {
let _ = DROPPED.try_with(|dropped| {
let mut dropped = dropped.borrow_mut();
if dropped.len() < MAX_DROPPED {
dropped.push(self.id);
}
});
}
}
impl CaptureNode {
pub(crate) fn new() -> CaptureNode {
CaptureNode {
id: next_id(),
source: None,
live: false,
paint_cursors: false,
fit: Fit::default(),
crop: None,
frame: None,
shown: None,
seen: Seen::Unseen,
}
}
pub(crate) fn gone(&self) {
if let Some(shown) = self.shown {
write(shown, false);
}
}
fn show(&mut self, frame: Option<CaptureFrame>) -> bool {
if self.frame == frame {
return false;
}
self.frame = frame;
if self.seen == Seen::Shown
&& let Some(shown) = self.shown
{
shown.try_set(false);
}
self.seen = Seen::Unseen;
true
}
}
impl Tree {
pub(crate) fn bind_capture(&mut self, id: NodeId, props: ScreencopyProps) {
self.captures.push(id);
if let Some(shown) = props.shown {
write(shown, false);
self.update_capture(id, |capture| {
capture.shown = Some(shown);
Change::None
});
}
if let Some(capture) = props.capture {
let frame = (move || capture.frame()).into_prop();
self.bind(id, frame, "frame", |tree, id, frame| {
tree.update_capture(id, |capture| match capture.show(frame) {
true => Change::Paint,
false => Change::None,
});
});
}
self.bind_opt(id, props.source, "source", |tree, id, value| {
tree.update_capture(id, |capture| {
if capture.source.as_ref() == Some(&value) {
return Change::None;
}
capture.source = Some(value);
match capture.show(None) {
true => Change::Paint,
false => Change::None,
}
});
});
self.bind_opt(id, props.crop, "crop", |tree, id, value| {
tree.update_capture(id, |capture| match replace(&mut capture.crop, value) {
Change::None => Change::None,
_ => Change::Paint,
});
});
self.bind_opt(id, props.live, "live", |tree, id, value| {
tree.update_capture(id, |capture| {
capture.live = value;
Change::None
});
});
self.bind_opt(
id,
props.paint_cursors,
"paint_cursors",
|tree, id, value| {
tree.update_capture(id, |capture| {
capture.paint_cursors = value;
Change::None
});
},
);
self.bind_opt(id, props.fit, "fit", |tree, id, value| {
tree.update_capture(id, |capture| match replace(&mut capture.fit, value) {
Change::None => Change::None,
_ => Change::Paint,
});
});
}
fn in_sight(&self, id: NodeId) -> bool {
let Some(node) = self.node(id) else {
return false;
};
let mut seen = node.window_painted;
let mut at = id;
while !seen.is_empty()
&& let Some(parent) = self.taffy.parent(at)
{
if let Some(above) = self.node(parent)
&& (above.clips || parent == self.root)
{
seen = seen.intersect(above.window_painted);
}
at = parent;
}
!seen.is_empty()
}
fn zoom(&self, id: NodeId) -> f32 {
let mut linear: Option<Affine> = None;
let mut at = Some(id);
while let Some(node) = at {
if let Some(transform) = self.node(node).and_then(|node| node.transform) {
linear = Some(match linear {
Some(inner) => transform.after(&inner),
None => transform,
});
}
at = self.taffy.parent(node);
}
linear.map_or(1.0, |linear| linear.layer_zoom())
}
fn update_capture(&mut self, id: NodeId, f: impl FnOnce(&mut CaptureNode) -> Change) {
self.update(id, |node| match &mut node.kind {
NodeKind::Capture(capture) => f(capture),
_ => Change::None,
});
}
}
impl Window {
pub fn captures(&self) -> Vec<CaptureRequest> {
let tree = self.tree.borrow();
tree
.captures
.iter()
.filter_map(|&id| {
let node = tree.node(id)?;
let NodeKind::Capture(capture) = &node.kind else {
return None;
};
let content = node.content;
if node.rect.is_none() || content.is_empty() || capture.live && !tree.in_sight(id) {
return None;
}
let zoom = tree.zoom(id);
let size = match capture.crop {
Some(_) => Size::new(f32::INFINITY, f32::INFINITY),
None => Size::new(content.width * zoom, content.height * zoom),
};
Some(CaptureRequest {
id: capture.id,
source: capture.source.clone()?,
live: capture.live,
paint_cursors: capture.paint_cursors,
size,
})
})
.collect()
}
pub fn show_capture(&self, id: u64, frame: CaptureFrame) -> bool {
let mut tree = borrow(&self.tree);
let found = tree.captures.iter().copied().find(|&node| {
matches!(tree.node(node).map(|node| &node.kind),
Some(NodeKind::Capture(capture)) if capture.id == id)
});
let Some(node) = found else {
return false;
};
let mut shown = false;
tree.update_capture(node, |capture| {
shown = capture.show(Some(frame));
match shown {
true => Change::Paint,
false => Change::None,
}
});
shown
}
pub fn frame_committed(&self) {
self.each_view(|capture, placed| match (placed, capture.seen) {
(false, _) => Seen::Unseen,
(true, Seen::Unseen) => Seen::Drawn,
(true, seen) => seen,
});
}
pub fn frame_presented(&self) {
self.each_view(|capture, _| match capture.seen {
Seen::Drawn => Seen::Shown,
seen => seen,
});
}
pub fn unmapped(&self) {
self.each_view(|_, _| Seen::Unseen);
}
fn each_view(&self, mut next: impl FnMut(&CaptureNode, bool) -> Seen) {
let mut writes = Vec::new();
let mut tree = borrow(&self.tree);
let views = tree.captures.clone();
for id in views {
let placed = tree
.node(id)
.is_some_and(|node| node.rect.is_some() && !node.content.is_empty())
&& tree.in_sight(id);
let Some(node) = tree.node_mut(id) else {
continue;
};
let NodeKind::Capture(capture) = &mut node.kind else {
continue;
};
let frame = capture.frame.as_ref();
let picture = frame.is_some_and(|frame| frame.drawn_part(capture.crop).is_some());
let seen = next(capture, placed && picture);
if let Some(shown) = capture.shown
&& (seen == Seen::Shown) != (capture.seen == Seen::Shown)
{
writes.push((shown, seen == Seen::Shown));
}
capture.seen = seen;
}
drop(tree);
for (shown, value) in writes {
write(shown, value);
}
}
}
fn write(signal: Signal<bool>, value: bool) {
if untrack(|| signal.try_get()).is_some_and(|was| was != value) {
signal.try_set(value);
}
}