1use crate::{
2 px, AnyView, AppContext, AvailableSpace, Bounds, Context, Effect, Element, EntityId, FontId,
3 GlyphId, GlyphRasterizationParams, 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<GlyphRasterizationParams>>,
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 = GlyphRasterizationParams {
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(¶ms)?;
193
194 if !raster_bounds.is_zero() {
195 let layer_id = self.current_layer_id();
196 let offset = raster_bounds.origin.map(Into::into);
197 let glyph_origin = glyph_origin.map(|px| px.floor()) + offset;
198 // dbg!(glyph_origin);
199 let bounds = Bounds {
200 origin: glyph_origin,
201 size: raster_bounds.size.map(Into::into),
202 };
203
204 let tile = self
205 .window
206 .glyph_atlas
207 .get_or_insert_with(¶ms, &mut || self.text_system().rasterize_glyph(¶ms))?;
208
209 self.window.scene.insert(
210 layer_id,
211 MonochromeSprite {
212 order,
213 bounds,
214 clip_bounds: bounds,
215 clip_corner_radii: Default::default(),
216 color,
217 tile,
218 },
219 );
220 }
221 Ok(())
222 }
223
224 pub(crate) fn draw(&mut self) -> Result<()> {
225 let unit_entity = self.unit_entity.clone();
226 self.update_entity(&unit_entity, |_, cx| {
227 let mut root_view = cx.window.root_view.take().unwrap();
228 let (root_layout_id, mut frame_state) = root_view.layout(&mut (), cx)?;
229 let available_space = cx.window.content_size.map(Into::into);
230
231 cx.window
232 .layout_engine
233 .compute_layout(root_layout_id, available_space)?;
234 let layout = cx.window.layout_engine.layout(root_layout_id)?;
235
236 root_view.paint(layout, &mut (), &mut frame_state, cx)?;
237 cx.window.root_view = Some(root_view);
238 let scene = cx.window.scene.take();
239
240 let _ = cx.run_on_main(|cx| {
241 cx.window
242 .platform_window
243 .borrow_on_main_thread()
244 .draw(scene);
245 });
246
247 cx.window.dirty = false;
248 Ok(())
249 })
250 }
251}
252
253impl Context for WindowContext<'_, '_> {
254 type EntityContext<'a, 'w, T: 'static + Send + Sync> = ViewContext<'a, 'w, T>;
255 type Result<T> = T;
256
257 fn entity<T: Send + Sync + 'static>(
258 &mut self,
259 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
260 ) -> Handle<T> {
261 let slot = self.app.entities.reserve();
262 let entity = build_entity(&mut ViewContext::mutable(
263 &mut *self.app,
264 &mut self.window,
265 slot.id,
266 ));
267 self.entities.redeem(slot, entity)
268 }
269
270 fn update_entity<T: Send + Sync + 'static, R>(
271 &mut self,
272 handle: &Handle<T>,
273 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
274 ) -> R {
275 let mut entity = self.entities.lease(handle);
276 let result = update(
277 &mut *entity,
278 &mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.id),
279 );
280 self.entities.end_lease(entity);
281 result
282 }
283}
284
285impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
286 type Target = AppContext;
287
288 fn deref(&self) -> &Self::Target {
289 &self.app
290 }
291}
292
293impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> {
294 fn deref_mut(&mut self) -> &mut Self::Target {
295 &mut self.app
296 }
297}
298
299impl<S> StackContext for ViewContext<'_, '_, S> {
300 fn app(&mut self) -> &mut AppContext {
301 &mut *self.window_cx.app
302 }
303
304 fn with_text_style<F, R>(&mut self, style: crate::TextStyleRefinement, f: F) -> R
305 where
306 F: FnOnce(&mut Self) -> R,
307 {
308 self.window_cx.app.push_text_style(style);
309 let result = f(self);
310 self.window_cx.app.pop_text_style();
311 result
312 }
313
314 fn with_state<T: Send + Sync + 'static, F, R>(&mut self, state: T, f: F) -> R
315 where
316 F: FnOnce(&mut Self) -> R,
317 {
318 self.window_cx.app.push_state(state);
319 let result = f(self);
320 self.window_cx.app.pop_state::<T>();
321 result
322 }
323}
324
325pub struct ViewContext<'a, 'w, S> {
326 window_cx: WindowContext<'a, 'w>,
327 entity_type: PhantomData<S>,
328 entity_id: EntityId,
329}
330
331impl<'a, 'w, S: Send + Sync + 'static> ViewContext<'a, 'w, S> {
332 fn mutable(app: &'a mut AppContext, window: &'w mut Window, entity_id: EntityId) -> Self {
333 Self {
334 window_cx: WindowContext::mutable(app, window),
335 entity_id,
336 entity_type: PhantomData,
337 }
338 }
339
340 pub fn handle(&self) -> WeakHandle<S> {
341 self.entities.weak_handle(self.entity_id)
342 }
343
344 pub fn observe<E: Send + Sync + 'static>(
345 &mut self,
346 handle: &Handle<E>,
347 on_notify: impl Fn(&mut S, Handle<E>, &mut ViewContext<'_, '_, S>) + Send + Sync + 'static,
348 ) {
349 let this = self.handle();
350 let handle = handle.downgrade();
351 let window_handle = self.window.handle;
352 self.app
353 .observers
354 .entry(handle.id)
355 .or_default()
356 .push(Arc::new(move |cx| {
357 cx.update_window(window_handle.id, |cx| {
358 if let Some(handle) = handle.upgrade(cx) {
359 this.update(cx, |this, cx| on_notify(this, handle, cx))
360 .is_ok()
361 } else {
362 false
363 }
364 })
365 .unwrap_or(false)
366 }));
367 }
368
369 pub fn notify(&mut self) {
370 self.window_cx.notify();
371 self.window_cx
372 .app
373 .pending_effects
374 .push_back(Effect::Notify(self.entity_id));
375 }
376
377 pub(crate) fn erase_state<R>(&mut self, f: impl FnOnce(&mut ViewContext<()>) -> R) -> R {
378 let entity_id = self.unit_entity.id;
379 let mut cx = ViewContext::mutable(
380 &mut *self.window_cx.app,
381 &mut *self.window_cx.window,
382 entity_id,
383 );
384 f(&mut cx)
385 }
386}
387
388impl<'a, 'w, S> Context for ViewContext<'a, 'w, S> {
389 type EntityContext<'b, 'c, U: 'static + Send + Sync> = ViewContext<'b, 'c, U>;
390 type Result<U> = U;
391
392 fn entity<T2: Send + Sync + 'static>(
393 &mut self,
394 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T2>) -> T2,
395 ) -> Handle<T2> {
396 self.window_cx.entity(build_entity)
397 }
398
399 fn update_entity<U: Send + Sync + 'static, R>(
400 &mut self,
401 handle: &Handle<U>,
402 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
403 ) -> R {
404 self.window_cx.update_entity(handle, update)
405 }
406}
407
408impl<'a, 'w, S: 'static> std::ops::Deref for ViewContext<'a, 'w, S> {
409 type Target = WindowContext<'a, 'w>;
410
411 fn deref(&self) -> &Self::Target {
412 &self.window_cx
413 }
414}
415
416impl<'a, 'w, S: 'static> std::ops::DerefMut for ViewContext<'a, 'w, S> {
417 fn deref_mut(&mut self) -> &mut Self::Target {
418 &mut self.window_cx
419 }
420}
421
422// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
423slotmap::new_key_type! { pub struct WindowId; }
424
425#[derive(PartialEq, Eq)]
426pub struct WindowHandle<S> {
427 id: WindowId,
428 state_type: PhantomData<S>,
429}
430
431impl<S> Copy for WindowHandle<S> {}
432
433impl<S> Clone for WindowHandle<S> {
434 fn clone(&self) -> Self {
435 WindowHandle {
436 id: self.id,
437 state_type: PhantomData,
438 }
439 }
440}
441
442impl<S> WindowHandle<S> {
443 pub fn new(id: WindowId) -> Self {
444 WindowHandle {
445 id,
446 state_type: PhantomData,
447 }
448 }
449}
450
451impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
452 fn into(self) -> AnyWindowHandle {
453 AnyWindowHandle {
454 id: self.id,
455 state_type: TypeId::of::<S>(),
456 }
457 }
458}
459
460#[derive(Copy, Clone, PartialEq, Eq)]
461pub struct AnyWindowHandle {
462 pub(crate) id: WindowId,
463 state_type: TypeId,
464}
465
466#[derive(Clone)]
467pub struct Layout {
468 pub order: u32,
469 pub bounds: Bounds<Pixels>,
470}