| 1 | use std::cell::{Cell, OnceCell}; |
| 2 | use std::path::PathBuf; |
| 3 | use std::rc::Rc; |
| 4 | use std::sync::OnceLock; |
| 5 | |
| 6 | use gpui_kit::*; |
| 7 | use tokio::sync::mpsc::UnboundedReceiver; |
| 8 | use webview::{EmbedBounds, EmbedHost, EmbedSpec, MainEmbed}; |
| 9 | |
| 10 | use crate::{notify, theme}; |
| 11 | |
| 12 | pub use webview::EmbedEvent as NativeEvent; |
| 13 | |
| 14 | static USER_DATA_FOLDER: OnceLock<PathBuf> = OnceLock::new(); |
| 15 | |
| 16 | thread_local! { |
| 17 | static HOST: OnceCell<EmbedHost> = const { OnceCell::new() }; |
| 18 | } |
| 19 | |
| 20 | pub fn configure(user_data_folder: PathBuf) { |
| 21 | let _ = USER_DATA_FOLDER.set(user_data_folder); |
| 22 | } |
| 23 | |
| 24 | pub fn available() -> bool { |
| 25 | USER_DATA_FOLDER.get().is_some() |
| 26 | } |
| 27 | |
| 28 | fn host() -> Option<EmbedHost> { |
| 29 | let folder = USER_DATA_FOLDER.get()?; |
| 30 | Some(HOST.with(|host| host.get_or_init(|| EmbedHost::new(folder.clone())).clone())) |
| 31 | } |
| 32 | |
| 33 | #[derive(Clone)] |
| 34 | pub struct Native { |
| 35 | embed: MainEmbed, |
| 36 | placed: Rc<Cell<Option<(EmbedBounds, bool)>>>, |
| 37 | } |
| 38 | |
| 39 | impl Native { |
| 40 | pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> { |
| 41 | let parent = notify::native_handle(window)?; |
| 42 | let (embed, events) = host()?.open(EmbedSpec { |
| 43 | parent, |
| 44 | url: url.to_owned(), |
| 45 | background: theme::BACKGROUND, |
| 46 | })?; |
| 47 | let native = Native { |
| 48 | embed, |
| 49 | placed: Rc::new(Cell::new(None)), |
| 50 | }; |
| 51 | Some((native, events)) |
| 52 | } |
| 53 | |
| 54 | pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) { |
| 55 | let placement = ( |
| 56 | EmbedBounds::from_logical( |
| 57 | f32::from(bounds.origin.x), |
| 58 | f32::from(bounds.origin.y), |
| 59 | f32::from(bounds.size.width), |
| 60 | f32::from(bounds.size.height), |
| 61 | scale, |
| 62 | ), |
| 63 | visible, |
| 64 | ); |
| 65 | if self.placed.get() == Some(placement) { |
| 66 | return; |
| 67 | } |
| 68 | self.placed.set(Some(placement)); |
| 69 | self.embed.place(placement.0, placement.1); |
| 70 | } |
| 71 | |
| 72 | pub fn close(&self) { |
| 73 | self.embed.close(); |
| 74 | } |
| 75 | } |