use std::sync::Arc; use common::{model::Id, share::Kind}; use gpui_kit::{ Context, IntoElement, ObjectFit, ParentElement, Render, RenderImage, Styled, StyledImage, Window, canvas, div, img, }; use crate::net::NetworkHandle; const WIDE: f32 = 16. / 9.; const ASPECT_CHANGE: f32 = 0.02; pub(super) struct Surface { frame: Option>, aspect: f32, cover: bool, network: NetworkHandle, source: (Id, Kind), id: u64, } impl Surface { pub(super) fn new( cover: bool, network: NetworkHandle, source: (Id, Kind), cx: &mut Context, ) -> Self { Self { frame: None, aspect: WIDE, cover, network, source, id: cx.entity_id().as_u64(), } } pub(super) fn replace( &mut self, frame: Option>, cx: &mut Context, ) -> Option> { if let Some(frame) = &frame { let size = frame.size(0); let aspect = size.width.0 as f32 / size.height.0.max(1) as f32; if (aspect - self.aspect).abs() > self.aspect * ASPECT_CHANGE { self.aspect = aspect; } } cx.notify(); std::mem::replace(&mut self.frame, frame) } pub(super) fn aspect(&self) -> f32 { self.aspect } pub(super) fn set_cover(&mut self, cover: bool, cx: &mut Context) { if self.cover != cover { self.cover = cover; cx.notify(); } } } impl Drop for Surface { fn drop(&mut self) { let (user_id, kind) = self.source; self.network.show_share(user_id, kind, self.id, None); } } impl Render for Surface { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { let fit = if self.cover { ObjectFit::Cover } else { ObjectFit::Contain }; let network = self.network.clone(); let ((user_id, kind), id) = (self.source, self.id); let aspect = self.aspect; let cover = self.cover; let measure = canvas( move |bounds, window, _| { let (width, height) = (f32::from(bounds.size.width), f32::from(bounds.size.height)); let width = if cover { width.max(height * aspect) } else { width.min(height * aspect) }; let width = (width * window.scale_factor()).round() as u32; network.show_share(user_id, kind, id, Some(width)); }, |_, _, _, _| {}, ) .absolute() .size_full(); div().size_full().relative().child(measure).children( self.frame .clone() .map(|frame| img(frame).absolute().size_full().object_fit(fit)), ) } }