window.rs

  1use crate::{
  2    px, AnyView, AppContext, AvailableSpace, Bounds, Context, Effect, Element, EntityId, Handle,
  3    LayoutId, MainThread, MainThreadOnly, Pixels, Platform, PlatformWindow, Point, Reference,
  4    Scene, Size, StackContext, Style, TaffyLayoutEngine, WeakHandle, WindowOptions,
  5};
  6use anyhow::Result;
  7use derive_more::{Deref, DerefMut};
  8use std::{any::TypeId, marker::PhantomData, sync::Arc};
  9use util::ResultExt;
 10
 11pub struct AnyWindow {}
 12
 13pub struct Window {
 14    handle: AnyWindowHandle,
 15    platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
 16    rem_size: Pixels,
 17    content_size: Size<Pixels>,
 18    layout_engine: TaffyLayoutEngine,
 19    pub(crate) root_view: Option<AnyView<()>>,
 20    mouse_position: Point<Pixels>,
 21    pub(crate) scene: Scene,
 22    pub(crate) dirty: bool,
 23}
 24
 25impl Window {
 26    pub fn new(
 27        handle: AnyWindowHandle,
 28        options: WindowOptions,
 29        cx: &mut AppContext<MainThread>,
 30    ) -> Self {
 31        let platform_window = cx.platform().open_window(handle, options);
 32        let mouse_position = platform_window.mouse_position();
 33        let content_size = platform_window.content_size();
 34        let scale_factor = platform_window.scale_factor();
 35        platform_window.on_resize(Box::new({
 36            let handle = handle;
 37            let cx = cx.to_async();
 38            move |content_size, scale_factor| {
 39                cx.update_window(handle, |cx| {
 40                    cx.window.scene = Scene::new(scale_factor);
 41                    cx.window.content_size = content_size;
 42                    cx.window.dirty = true;
 43                })
 44                .log_err();
 45            }
 46        }));
 47
 48        let platform_window =
 49            MainThreadOnly::new(Arc::new(platform_window), cx.platform().dispatcher());
 50
 51        Window {
 52            handle,
 53            platform_window,
 54            rem_size: px(16.),
 55            content_size,
 56            layout_engine: TaffyLayoutEngine::new(),
 57            root_view: None,
 58            mouse_position,
 59            scene: Scene::new(scale_factor),
 60            dirty: true,
 61        }
 62    }
 63}
 64
 65#[derive(Deref, DerefMut)]
 66pub struct WindowContext<'a, 'w, Thread = ()> {
 67    thread: PhantomData<Thread>,
 68    #[deref]
 69    #[deref_mut]
 70    app: Reference<'a, AppContext<Thread>>,
 71    window: Reference<'w, Window>,
 72}
 73
 74impl<'a, 'w> WindowContext<'a, 'w> {
 75    pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
 76        Self {
 77            thread: PhantomData,
 78            app: Reference::Mutable(app),
 79            window: Reference::Mutable(window),
 80        }
 81    }
 82
 83    pub(crate) fn draw(&mut self) -> Result<()> {
 84        let unit_entity = self.unit_entity.clone();
 85        self.update_entity(&unit_entity, |_, cx| {
 86            let mut root_view = cx.window.root_view.take().unwrap();
 87            let (root_layout_id, mut frame_state) = root_view.layout(&mut (), cx)?;
 88            let available_space = cx.window.content_size.map(Into::into);
 89            cx.window
 90                .layout_engine
 91                .compute_layout(root_layout_id, available_space)?;
 92            let layout = cx.window.layout_engine.layout(root_layout_id)?;
 93            root_view.paint(layout, &mut (), &mut frame_state, cx)?;
 94            cx.window.root_view = Some(root_view);
 95            let scene = cx.window.scene.take();
 96            dbg!(&scene);
 97
 98            // todo!
 99            // self.run_on_main(|cx| {
100            //     cx.window
101            //         .platform_window
102            //         .borrow_on_main_thread()
103            //         .draw(scene);
104            // });
105
106            Ok(())
107        })
108    }
109
110    pub fn request_layout(
111        &mut self,
112        style: Style,
113        children: impl IntoIterator<Item = LayoutId>,
114    ) -> Result<LayoutId> {
115        self.app.layout_id_buffer.clear();
116        self.app.layout_id_buffer.extend(children.into_iter());
117        let rem_size = self.rem_size();
118
119        self.window
120            .layout_engine
121            .request_layout(style, rem_size, &self.app.layout_id_buffer)
122    }
123
124    pub fn request_measured_layout<
125        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
126    >(
127        &mut self,
128        style: Style,
129        rem_size: Pixels,
130        measure: F,
131    ) -> Result<LayoutId> {
132        self.window
133            .layout_engine
134            .request_measured_layout(style, rem_size, measure)
135    }
136
137    pub fn layout(&mut self, layout_id: LayoutId) -> Result<Layout> {
138        Ok(self
139            .window
140            .layout_engine
141            .layout(layout_id)
142            .map(Into::into)?)
143    }
144
145    pub fn rem_size(&self) -> Pixels {
146        self.window.rem_size
147    }
148
149    pub fn mouse_position(&self) -> Point<Pixels> {
150        self.window.mouse_position
151    }
152}
153
154impl WindowContext<'_, '_, MainThread> {
155    // todo!("implement other methods that use platform window")
156    fn platform_window(&self) -> &dyn PlatformWindow {
157        self.window.platform_window.borrow_on_main_thread().as_ref()
158    }
159}
160
161impl Context for WindowContext<'_, '_> {
162    type EntityContext<'a, 'w, T: Send + Sync + 'static> = ViewContext<'a, 'w, T>;
163    type Result<T> = T;
164
165    fn entity<T: Send + Sync + 'static>(
166        &mut self,
167        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
168    ) -> Handle<T> {
169        let slot = self.entities.reserve();
170        let entity = build_entity(&mut ViewContext::mutable(
171            &mut *self.app,
172            &mut self.window,
173            slot.id,
174        ));
175        self.entities.redeem(slot, entity)
176    }
177
178    fn update_entity<T: Send + Sync + 'static, R>(
179        &mut self,
180        handle: &Handle<T>,
181        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
182    ) -> R {
183        let mut entity = self.entities.lease(handle);
184        let result = update(
185            &mut *entity,
186            &mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.id),
187        );
188        self.entities.end_lease(entity);
189        result
190    }
191}
192
193impl<S> StackContext for ViewContext<'_, '_, S> {
194    fn app(&mut self) -> &mut AppContext {
195        &mut *self.app
196    }
197
198    fn with_text_style<F, R>(&mut self, style: crate::TextStyleRefinement, f: F) -> R
199    where
200        F: FnOnce(&mut Self) -> R,
201    {
202        self.push_text_style(style);
203        let result = f(self);
204        self.pop_text_style();
205        result
206    }
207
208    fn with_state<T: Send + Sync + 'static, F, R>(&mut self, state: T, f: F) -> R
209    where
210        F: FnOnce(&mut Self) -> R,
211    {
212        self.push_state(state);
213        let result = f(self);
214        self.pop_state::<T>();
215        result
216    }
217}
218
219#[derive(Deref, DerefMut)]
220pub struct ViewContext<'a, 'w, S, Thread = ()> {
221    #[deref]
222    #[deref_mut]
223    window_cx: WindowContext<'a, 'w, Thread>,
224    entity_type: PhantomData<S>,
225    entity_id: EntityId,
226    thread: PhantomData<Thread>,
227}
228
229impl<'a, 'w, S: Send + Sync + 'static> ViewContext<'a, 'w, S> {
230    fn mutable(app: &'a mut AppContext, window: &'w mut Window, entity_id: EntityId) -> Self {
231        Self {
232            window_cx: WindowContext::mutable(app, window),
233            entity_id,
234            entity_type: PhantomData,
235            thread: PhantomData,
236        }
237    }
238
239    pub fn handle(&self) -> WeakHandle<S> {
240        self.entities.weak_handle(self.entity_id)
241    }
242
243    pub fn observe<E: Send + Sync + 'static>(
244        &mut self,
245        handle: &Handle<E>,
246        on_notify: impl Fn(&mut S, Handle<E>, &mut ViewContext<'_, '_, S>) + Send + Sync + 'static,
247    ) {
248        let this = self.handle();
249        let handle = handle.downgrade();
250        let window_handle = self.window.handle;
251        self.app
252            .observers
253            .entry(handle.id)
254            .or_default()
255            .push(Arc::new(move |cx| {
256                cx.update_window(window_handle.id, |cx| {
257                    if let Some(handle) = handle.upgrade(cx) {
258                        this.update(cx, |this, cx| on_notify(this, handle, cx))
259                            .is_ok()
260                    } else {
261                        false
262                    }
263                })
264                .unwrap_or(false)
265            }));
266    }
267
268    pub fn notify(&mut self) {
269        let entity_id = self.entity_id;
270        self.app
271            .pending_effects
272            .push_back(Effect::Notify(entity_id));
273        self.window.dirty = true;
274    }
275
276    pub(crate) fn erase_state<R>(&mut self, f: impl FnOnce(&mut ViewContext<()>) -> R) -> R {
277        let entity_id = self.unit_entity.id;
278        let mut cx = ViewContext::mutable(
279            &mut *self.window_cx.app,
280            &mut *self.window_cx.window,
281            entity_id,
282        );
283        f(&mut cx)
284    }
285}
286
287impl<'a, 'w, S: 'static> Context for ViewContext<'a, 'w, S> {
288    type EntityContext<'b, 'c, U: Send + Sync + 'static> = ViewContext<'b, 'c, U>;
289    type Result<U> = U;
290
291    fn entity<T2: Send + Sync + 'static>(
292        &mut self,
293        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T2>) -> T2,
294    ) -> Handle<T2> {
295        self.window_cx.entity(build_entity)
296    }
297
298    fn update_entity<U: Send + Sync + 'static, R>(
299        &mut self,
300        handle: &Handle<U>,
301        update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
302    ) -> R {
303        self.window_cx.update_entity(handle, update)
304    }
305}
306
307impl<S> ViewContext<'_, '_, S, MainThread> {}
308
309// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
310slotmap::new_key_type! { pub struct WindowId; }
311
312#[derive(PartialEq, Eq)]
313pub struct WindowHandle<S> {
314    id: WindowId,
315    state_type: PhantomData<S>,
316}
317
318impl<S> Copy for WindowHandle<S> {}
319
320impl<S> Clone for WindowHandle<S> {
321    fn clone(&self) -> Self {
322        WindowHandle {
323            id: self.id,
324            state_type: PhantomData,
325        }
326    }
327}
328
329impl<S> WindowHandle<S> {
330    pub fn new(id: WindowId) -> Self {
331        WindowHandle {
332            id,
333            state_type: PhantomData,
334        }
335    }
336}
337
338impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
339    fn into(self) -> AnyWindowHandle {
340        AnyWindowHandle {
341            id: self.id,
342            state_type: TypeId::of::<S>(),
343        }
344    }
345}
346
347#[derive(Copy, Clone, PartialEq, Eq)]
348pub struct AnyWindowHandle {
349    pub(crate) id: WindowId,
350    state_type: TypeId,
351}
352
353#[derive(Clone)]
354pub struct Layout {
355    pub order: u32,
356    pub bounds: Bounds<Pixels>,
357}