window.rs

  1use crate::{
  2    px, AnyView, AppContext, AvailableSpace, Bounds, Context, Effect, Element, EntityId, FontId,
  3    GlyphId, GlyphRasterParams, Handle, Hsla, IsZero, LayoutId, MainThread, MainThreadOnly,
  4    MonochromeSprite, Pixels, PlatformAtlas, PlatformWindow, Point, Reference, Scene, Size,
  5    StackContext, StackingOrder, Style, TaffyLayoutEngine, WeakHandle, WindowOptions,
  6    SUBPIXEL_VARIANTS,
  7};
  8use anyhow::Result;
  9use futures::Future;
 10use smallvec::SmallVec;
 11use std::{any::TypeId, marker::PhantomData, mem, sync::Arc};
 12use util::ResultExt;
 13
 14pub struct AnyWindow {}
 15
 16pub struct Window {
 17    handle: AnyWindowHandle,
 18    platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
 19    glyph_atlas: Arc<dyn PlatformAtlas<GlyphRasterParams>>,
 20    rem_size: Pixels,
 21    content_size: Size<Pixels>,
 22    layout_engine: TaffyLayoutEngine,
 23    pub(crate) root_view: Option<AnyView<()>>,
 24    mouse_position: Point<Pixels>,
 25    current_layer_id: StackingOrder,
 26    pub(crate) scene: Scene,
 27    pub(crate) dirty: bool,
 28}
 29
 30impl Window {
 31    pub fn new(
 32        handle: AnyWindowHandle,
 33        options: WindowOptions,
 34        cx: &mut MainThread<AppContext>,
 35    ) -> Self {
 36        let platform_window = cx.platform().open_window(handle, options);
 37        let glyph_atlas = platform_window.glyph_atlas();
 38        let mouse_position = platform_window.mouse_position();
 39        let content_size = platform_window.content_size();
 40        let scale_factor = platform_window.scale_factor();
 41        platform_window.on_resize(Box::new({
 42            let handle = handle;
 43            let cx = cx.to_async();
 44            move |content_size, scale_factor| {
 45                cx.update_window(handle, |cx| {
 46                    cx.window.scene = Scene::new(scale_factor);
 47                    cx.window.content_size = content_size;
 48                    cx.window.dirty = true;
 49                })
 50                .log_err();
 51            }
 52        }));
 53
 54        let platform_window =
 55            MainThreadOnly::new(Arc::new(platform_window), cx.platform().dispatcher());
 56
 57        Window {
 58            handle,
 59            platform_window,
 60            glyph_atlas,
 61            rem_size: px(16.),
 62            content_size,
 63            layout_engine: TaffyLayoutEngine::new(),
 64            root_view: None,
 65            mouse_position,
 66            current_layer_id: SmallVec::new(),
 67            scene: Scene::new(scale_factor),
 68            dirty: true,
 69        }
 70    }
 71}
 72
 73pub struct WindowContext<'a, 'w> {
 74    app: Reference<'a, AppContext>,
 75    window: Reference<'w, Window>,
 76}
 77
 78impl<'a, 'w> WindowContext<'a, 'w> {
 79    pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
 80        Self {
 81            app: Reference::Mutable(app),
 82            window: Reference::Mutable(window),
 83        }
 84    }
 85
 86    pub fn notify(&mut self) {
 87        self.window.dirty = true;
 88    }
 89
 90    pub fn request_layout(
 91        &mut self,
 92        style: Style,
 93        children: impl IntoIterator<Item = LayoutId>,
 94    ) -> Result<LayoutId> {
 95        self.app.layout_id_buffer.clear();
 96        self.app.layout_id_buffer.extend(children.into_iter());
 97        let rem_size = self.rem_size();
 98
 99        self.window
100            .layout_engine
101            .request_layout(style, rem_size, &self.app.layout_id_buffer)
102    }
103
104    pub fn request_measured_layout<
105        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
106    >(
107        &mut self,
108        style: Style,
109        rem_size: Pixels,
110        measure: F,
111    ) -> Result<LayoutId> {
112        self.window
113            .layout_engine
114            .request_measured_layout(style, rem_size, measure)
115    }
116
117    pub fn layout(&mut self, layout_id: LayoutId) -> Result<Layout> {
118        Ok(self
119            .window
120            .layout_engine
121            .layout(layout_id)
122            .map(Into::into)?)
123    }
124
125    pub fn scale_factor(&self) -> f32 {
126        self.window.scene.scale_factor
127    }
128
129    pub fn rem_size(&self) -> Pixels {
130        self.window.rem_size
131    }
132
133    pub fn mouse_position(&self) -> Point<Pixels> {
134        self.window.mouse_position
135    }
136
137    pub fn scene(&mut self) -> &mut Scene {
138        &mut self.window.scene
139    }
140
141    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
142        self.window.current_layer_id.push(order);
143        let result = f(self);
144        self.window.current_layer_id.pop();
145        result
146    }
147
148    pub fn current_layer_id(&self) -> StackingOrder {
149        self.window.current_layer_id.clone()
150    }
151
152    pub fn run_on_main<R>(
153        &self,
154        f: impl FnOnce(&mut MainThread<WindowContext>) -> R + Send + 'static,
155    ) -> impl Future<Output = Result<R>>
156    where
157        R: Send + 'static,
158    {
159        let id = self.window.handle.id;
160        self.app.run_on_main(move |cx| {
161            cx.update_window(id, |cx| {
162                f(unsafe {
163                    mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
164                })
165            })
166        })
167    }
168
169    pub fn paint_glyph(
170        &mut self,
171        origin: Point<Pixels>,
172        order: u32,
173        font_id: FontId,
174        glyph_id: GlyphId,
175        font_size: Pixels,
176        color: Hsla,
177    ) -> Result<()> {
178        let scale_factor = self.scale_factor();
179        let glyph_origin = origin.scale(scale_factor);
180        let subpixel_variant = Point {
181            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
182            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
183        };
184        let params = GlyphRasterParams {
185            font_id,
186            glyph_id,
187            font_size,
188            subpixel_variant,
189            scale_factor,
190        };
191
192        let raster_bounds = self.text_system().raster_bounds(&params)?;
193        if !raster_bounds.is_zero() {
194            let layer_id = self.current_layer_id();
195            let bounds = Bounds {
196                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
197                size: raster_bounds.size.map(Into::into),
198            };
199            let tile = self
200                .window
201                .glyph_atlas
202                .get_or_insert_with(&params, &mut || self.text_system().rasterize_glyph(&params))?;
203
204            self.window.scene.insert(
205                layer_id,
206                MonochromeSprite {
207                    order,
208                    bounds,
209                    clip_bounds: bounds,
210                    clip_corner_radii: Default::default(),
211                    color,
212                    tile,
213                },
214            );
215        }
216        Ok(())
217    }
218
219    pub(crate) fn draw(&mut self) -> Result<()> {
220        let unit_entity = self.unit_entity.clone();
221        self.update_entity(&unit_entity, |_, cx| {
222            let mut root_view = cx.window.root_view.take().unwrap();
223            let (root_layout_id, mut frame_state) = root_view.layout(&mut (), cx)?;
224            let available_space = cx.window.content_size.map(Into::into);
225
226            cx.window
227                .layout_engine
228                .compute_layout(root_layout_id, available_space)?;
229            let layout = cx.window.layout_engine.layout(root_layout_id)?;
230
231            root_view.paint(layout, &mut (), &mut frame_state, cx)?;
232            cx.window.root_view = Some(root_view);
233            let scene = cx.window.scene.take();
234
235            let _ = cx.run_on_main(|cx| {
236                cx.window
237                    .platform_window
238                    .borrow_on_main_thread()
239                    .draw(scene);
240            });
241
242            cx.window.dirty = false;
243            Ok(())
244        })
245    }
246}
247
248impl Context for WindowContext<'_, '_> {
249    type EntityContext<'a, 'w, T: 'static + Send + Sync> = ViewContext<'a, 'w, T>;
250    type Result<T> = T;
251
252    fn entity<T: Send + Sync + 'static>(
253        &mut self,
254        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
255    ) -> Handle<T> {
256        let slot = self.app.entities.reserve();
257        let entity = build_entity(&mut ViewContext::mutable(
258            &mut *self.app,
259            &mut self.window,
260            slot.id,
261        ));
262        self.entities.redeem(slot, entity)
263    }
264
265    fn update_entity<T: Send + Sync + 'static, R>(
266        &mut self,
267        handle: &Handle<T>,
268        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
269    ) -> R {
270        let mut entity = self.entities.lease(handle);
271        let result = update(
272            &mut *entity,
273            &mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.id),
274        );
275        self.entities.end_lease(entity);
276        result
277    }
278}
279
280impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
281    type Target = AppContext;
282
283    fn deref(&self) -> &Self::Target {
284        &self.app
285    }
286}
287
288impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> {
289    fn deref_mut(&mut self) -> &mut Self::Target {
290        &mut self.app
291    }
292}
293
294impl<S> StackContext for ViewContext<'_, '_, S> {
295    fn app(&mut self) -> &mut AppContext {
296        &mut *self.window_cx.app
297    }
298
299    fn with_text_style<F, R>(&mut self, style: crate::TextStyleRefinement, f: F) -> R
300    where
301        F: FnOnce(&mut Self) -> R,
302    {
303        self.window_cx.app.push_text_style(style);
304        let result = f(self);
305        self.window_cx.app.pop_text_style();
306        result
307    }
308
309    fn with_state<T: Send + Sync + 'static, F, R>(&mut self, state: T, f: F) -> R
310    where
311        F: FnOnce(&mut Self) -> R,
312    {
313        self.window_cx.app.push_state(state);
314        let result = f(self);
315        self.window_cx.app.pop_state::<T>();
316        result
317    }
318}
319
320pub struct ViewContext<'a, 'w, S> {
321    window_cx: WindowContext<'a, 'w>,
322    entity_type: PhantomData<S>,
323    entity_id: EntityId,
324}
325
326impl<'a, 'w, S: Send + Sync + 'static> ViewContext<'a, 'w, S> {
327    fn mutable(app: &'a mut AppContext, window: &'w mut Window, entity_id: EntityId) -> Self {
328        Self {
329            window_cx: WindowContext::mutable(app, window),
330            entity_id,
331            entity_type: PhantomData,
332        }
333    }
334
335    pub fn handle(&self) -> WeakHandle<S> {
336        self.entities.weak_handle(self.entity_id)
337    }
338
339    pub fn observe<E: Send + Sync + 'static>(
340        &mut self,
341        handle: &Handle<E>,
342        on_notify: impl Fn(&mut S, Handle<E>, &mut ViewContext<'_, '_, S>) + Send + Sync + 'static,
343    ) {
344        let this = self.handle();
345        let handle = handle.downgrade();
346        let window_handle = self.window.handle;
347        self.app
348            .observers
349            .entry(handle.id)
350            .or_default()
351            .push(Arc::new(move |cx| {
352                cx.update_window(window_handle.id, |cx| {
353                    if let Some(handle) = handle.upgrade(cx) {
354                        this.update(cx, |this, cx| on_notify(this, handle, cx))
355                            .is_ok()
356                    } else {
357                        false
358                    }
359                })
360                .unwrap_or(false)
361            }));
362    }
363
364    pub fn notify(&mut self) {
365        self.window_cx.notify();
366        self.window_cx
367            .app
368            .pending_effects
369            .push_back(Effect::Notify(self.entity_id));
370    }
371
372    pub(crate) fn erase_state<R>(&mut self, f: impl FnOnce(&mut ViewContext<()>) -> R) -> R {
373        let entity_id = self.unit_entity.id;
374        let mut cx = ViewContext::mutable(
375            &mut *self.window_cx.app,
376            &mut *self.window_cx.window,
377            entity_id,
378        );
379        f(&mut cx)
380    }
381}
382
383impl<'a, 'w, S> Context for ViewContext<'a, 'w, S> {
384    type EntityContext<'b, 'c, U: 'static + Send + Sync> = ViewContext<'b, 'c, U>;
385    type Result<U> = U;
386
387    fn entity<T2: Send + Sync + 'static>(
388        &mut self,
389        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T2>) -> T2,
390    ) -> Handle<T2> {
391        self.window_cx.entity(build_entity)
392    }
393
394    fn update_entity<U: Send + Sync + 'static, R>(
395        &mut self,
396        handle: &Handle<U>,
397        update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
398    ) -> R {
399        self.window_cx.update_entity(handle, update)
400    }
401}
402
403impl<'a, 'w, S: 'static> std::ops::Deref for ViewContext<'a, 'w, S> {
404    type Target = WindowContext<'a, 'w>;
405
406    fn deref(&self) -> &Self::Target {
407        &self.window_cx
408    }
409}
410
411impl<'a, 'w, S: 'static> std::ops::DerefMut for ViewContext<'a, 'w, S> {
412    fn deref_mut(&mut self) -> &mut Self::Target {
413        &mut self.window_cx
414    }
415}
416
417// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
418slotmap::new_key_type! { pub struct WindowId; }
419
420#[derive(PartialEq, Eq)]
421pub struct WindowHandle<S> {
422    id: WindowId,
423    state_type: PhantomData<S>,
424}
425
426impl<S> Copy for WindowHandle<S> {}
427
428impl<S> Clone for WindowHandle<S> {
429    fn clone(&self) -> Self {
430        WindowHandle {
431            id: self.id,
432            state_type: PhantomData,
433        }
434    }
435}
436
437impl<S> WindowHandle<S> {
438    pub fn new(id: WindowId) -> Self {
439        WindowHandle {
440            id,
441            state_type: PhantomData,
442        }
443    }
444}
445
446impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
447    fn into(self) -> AnyWindowHandle {
448        AnyWindowHandle {
449            id: self.id,
450            state_type: TypeId::of::<S>(),
451        }
452    }
453}
454
455#[derive(Copy, Clone, PartialEq, Eq)]
456pub struct AnyWindowHandle {
457    pub(crate) id: WindowId,
458    state_type: TypeId,
459}
460
461#[derive(Clone)]
462pub struct Layout {
463    pub order: u32,
464    pub bounds: Bounds<Pixels>,
465}