1mod cells;
26mod dirty;
27mod pixels;
28
29use alloc::rc::{Rc, Weak};
30use alloc::string::String;
31use alloc::vec;
32use alloc::vec::Vec;
33use core::cell::RefCell;
34use core::marker::PhantomData;
35
36pub use cells::Cell;
37pub(crate) use cells::write_text_clipped;
38use dirty::DirtyRects;
39pub(crate) use pixels::Canvas;
40
41use crate::error::{Error, Result};
42use crate::geometry::{Geometry, Rect};
43use crate::host;
44use crate::local::instance_local;
45
46pub const HEADER_LEN: u32 = 32;
48pub const CELL_LEN: u32 = 16;
50pub const PIXEL_LEN: u32 = 4;
52
53const HEADER_WORDS: usize = (HEADER_LEN / 4) as usize;
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57pub enum Model {
58 Cells,
59 Pixels,
60}
61
62impl Model {
63 pub fn as_str(self) -> &'static str {
64 match self {
65 Self::Cells => "cells",
66 Self::Pixels => "pixels",
67 }
68 }
69
70 fn word(self) -> u32 {
71 match self {
72 Self::Cells => 0,
73 Self::Pixels => 1,
74 }
75 }
76
77 fn unit_words(self) -> usize {
79 match self {
80 Self::Cells => (CELL_LEN / 4) as usize,
81 Self::Pixels => 1,
82 }
83 }
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub(crate) struct RegionLayout {
89 pub len: u32,
90 pub header_len: u32,
91 pub slot_len: u32,
92 pub model: Model,
93 pub geometry: Geometry,
94}
95
96impl RegionLayout {
97 pub(crate) fn new(model: Model, geometry: Geometry) -> Self {
99 let slot_len = match model {
100 Model::Cells => geometry.cols * geometry.rows * CELL_LEN,
101 Model::Pixels => geometry.px_w * geometry.px_h * PIXEL_LEN,
102 };
103 Self {
104 len: HEADER_LEN + 2 * slot_len,
105 header_len: HEADER_LEN,
106 slot_len,
107 model,
108 geometry,
109 }
110 }
111
112 fn extent(&self) -> (u32, u32) {
114 match self.model {
115 Model::Cells => (self.geometry.cols, self.geometry.rows),
116 Model::Pixels => (self.geometry.px_w, self.geometry.px_h),
117 }
118 }
119
120 fn slot_words(&self) -> usize {
121 (self.slot_len / 4) as usize
122 }
123}
124
125mod sealed {
126 pub trait Sealed {}
127}
128
129pub trait SurfaceModel: sealed::Sealed {
131 const MODEL: Model;
132}
133
134#[derive(Clone, Copy, Debug)]
136pub enum Cells {}
137
138#[derive(Clone, Copy, Debug)]
141pub enum Pixels {}
142
143impl sealed::Sealed for Cells {}
144impl sealed::Sealed for Pixels {}
145
146impl SurfaceModel for Cells {
147 const MODEL: Model = Model::Cells;
148}
149
150impl SurfaceModel for Pixels {
151 const MODEL: Model = Model::Pixels;
152}
153
154#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct CommitInfo {
157 pub seq: u32,
159 pub slot: u8,
161 pub dirty: Vec<Rect>,
163 pub full: bool,
165}
166
167#[derive(Debug)]
168enum Backend {
169 Host,
171 Offscreen(Geometry),
173}
174
175#[derive(Debug)]
176struct Binding {
177 layout: RegionLayout,
178 region: Vec<u32>,
180 back: u8,
182}
183
184#[derive(Debug)]
185pub(crate) struct Inner {
186 id: String,
187 model: Model,
188 backend: Backend,
189 binding: Option<Binding>,
190 retired: Option<Vec<u32>>,
193 dirty: DirtyRects,
194 sync: Vec<Rect>,
197 full: bool,
199 seq: u32,
200 error: Option<Error>,
201 last_commit: Option<CommitInfo>,
202 embedded: bool,
205}
206
207instance_local! {
208 fn registry() -> Vec<Weak<RefCell<Inner>>> = Vec::new();
209}
210
211pub(crate) fn rebind_surfaces(id: &str) {
213 let surfaces: Vec<Rc<RefCell<Inner>>> = registry(|registry| {
214 registry.retain(|weak| weak.strong_count() > 0);
215 registry.iter().filter_map(Weak::upgrade).collect()
216 });
217 for surface in surfaces {
218 let mut inner = surface.borrow_mut();
219 if inner.id == id {
220 inner.rebind();
221 }
222 }
223}
224
225fn as_bytes(words: &[u32]) -> &[u8] {
226 unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), words.len() * 4) }
229}
230
231fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] {
232 unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 4) }
234}
235
236impl Inner {
237 fn new(id: String, model: Model, backend: Backend) -> Self {
238 Self {
239 id,
240 model,
241 backend,
242 binding: None,
243 retired: None,
244 dirty: DirtyRects::default(),
245 sync: Vec::new(),
246 full: false,
247 seq: 0,
248 error: None,
249 last_commit: None,
250 embedded: false,
251 }
252 }
253
254 fn rebind(&mut self) {
255 match self.bind() {
256 Ok(_) => self.error = None,
257 Err(error) => self.error = Some(error),
258 }
259 }
260
261 fn bind(&mut self) -> Result<bool> {
264 if self.embedded {
265 if self.binding.take().is_some() && matches!(self.backend, Backend::Host) {
267 host::surface_detach(&self.id)?;
268 }
269 self.retired = None;
270 return Ok(false);
271 }
272 let layout = match &self.backend {
273 Backend::Host => host::surface_layout(&self.id)?,
274 Backend::Offscreen(geometry) => RegionLayout::new(self.model, *geometry),
275 };
276 if layout.model != self.model {
277 return Err(Error::WrongModel {
278 surface: self.id.clone(),
279 expected: self.model,
280 found: layout.model,
281 });
282 }
283 if layout.geometry.is_empty() {
284 return Ok(false);
285 }
286 let mut region = vec![0u32; (layout.len as usize).div_ceil(4)];
287 let g = layout.geometry;
288 region[..HEADER_WORDS].copy_from_slice(&[
289 self.seq,
290 layout.model.word(),
291 g.cols,
292 g.rows,
293 g.px_w,
294 g.px_h,
295 g.cell_px_w,
296 g.cell_px_h,
297 ]);
298 if let Backend::Host = self.backend {
299 host::surface_attach(&self.id, &as_bytes(®ion)[..layout.len as usize])?;
300 }
301 if let Some(previous) = self.binding.take() {
302 if self.retired.is_none() {
306 self.retired = Some(previous.region);
307 }
308 }
309 self.binding = Some(Binding {
310 layout,
311 region,
312 back: 0,
313 });
314 self.full = true;
315 self.dirty.clear();
316 self.sync.clear();
317 Ok(true)
318 }
319
320 fn ensure_bound(&mut self) -> Result<&mut Binding> {
321 if self.binding.is_none() {
322 if let Some(error) = self.error.clone() {
323 return Err(error);
324 }
325 self.bind()?;
326 }
327 let id = &self.id;
328 self.binding.as_mut().ok_or_else(|| Error::NotAttached {
329 surface: id.clone(),
330 })
331 }
332
333 fn extent(&self) -> (u32, u32) {
334 self.binding
335 .as_ref()
336 .map_or((0, 0), |binding| binding.layout.extent())
337 }
338
339 fn apply_sync(&mut self) {
341 let Some(binding) = self.binding.as_mut() else {
342 self.sync.clear();
343 return;
344 };
345 if self.sync.is_empty() {
346 return;
347 }
348 let (width, _) = binding.layout.extent();
349 let unit = binding.layout.model.unit_words();
350 let slot_words = binding.layout.slot_words();
351 let front = HEADER_WORDS + usize::from(binding.back ^ 1) * slot_words;
352 let back = HEADER_WORDS + usize::from(binding.back) * slot_words;
353 for rect in self.sync.drain(..) {
354 for y in rect.y..rect.bottom() {
355 let start = (y as usize * width as usize + rect.x as usize) * unit;
356 let len = rect.w as usize * unit;
357 binding
358 .region
359 .copy_within(front + start..front + start + len, back + start);
360 }
361 }
362 }
363
364 fn back(&mut self) -> Option<(&mut [u32], RegionLayout, &mut DirtyRects)> {
367 self.apply_sync();
368 let binding = self.binding.as_mut()?;
369 let slot_words = binding.layout.slot_words();
370 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
371 Some((
372 &mut binding.region[start..start + slot_words],
373 binding.layout,
374 &mut self.dirty,
375 ))
376 }
377
378 fn back_discard(&mut self) -> Option<(&mut [u32], RegionLayout)> {
381 self.sync.clear();
382 let binding = self.binding.as_mut()?;
383 let (width, height) = binding.layout.extent();
384 self.dirty
385 .add(Rect::new(0, 0, width, height), width, height);
386 let slot_words = binding.layout.slot_words();
387 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
388 Some((
389 &mut binding.region[start..start + slot_words],
390 binding.layout,
391 ))
392 }
393
394 fn mark_dirty(&mut self, rect: Rect) {
395 self.apply_sync();
396 let (width, height) = self.extent();
397 self.dirty.add(rect, width, height);
398 }
399
400 fn commit(&mut self) -> Result<bool> {
401 self.ensure_bound()?;
402 let (width, height) = self.extent();
403 let full = self.full;
404 let rects = if full {
405 self.dirty.clear();
406 if width == 0 || height == 0 {
407 Vec::new()
408 } else {
409 vec![Rect::new(0, 0, width, height)]
410 }
411 } else {
412 self.dirty.take()
413 };
414 if rects.is_empty() {
415 return Ok(false);
416 }
417 let seq = self.seq.wrapping_add(1);
418 let Some(binding) = self.binding.as_mut() else {
419 return Ok(false);
420 };
421 binding.region[0] = seq;
422 let slot = binding.back;
423 if let Backend::Host = self.backend
424 && let Err(error) = host::surface_commit(&self.id, slot, &rects)
425 {
426 for rect in rects {
427 self.dirty.add(rect, width, height);
428 }
429 return Err(error);
430 }
431 binding.back ^= 1;
432 self.seq = seq;
433 self.full = false;
434 self.retired = None;
435 self.sync = rects.clone();
436 self.last_commit = Some(CommitInfo {
437 seq,
438 slot,
439 dirty: rects,
440 full,
441 });
442 Ok(true)
443 }
444}
445
446#[derive(Debug)]
448pub struct Surface<M: SurfaceModel> {
449 inner: Rc<RefCell<Inner>>,
450 model: PhantomData<M>,
451}
452
453impl<M: SurfaceModel> Surface<M> {
454 pub fn new(id: &str) -> Self {
457 let surface = Self::new_unbound(id);
458 surface.inner.borrow_mut().rebind();
459 surface
460 }
461
462 fn new_unbound(id: &str) -> Self {
463 let inner = Rc::new(RefCell::new(Inner::new(id.into(), M::MODEL, Backend::Host)));
464 registry(|registry| registry.push(Rc::downgrade(&inner)));
465 Self {
466 inner,
467 model: PhantomData,
468 }
469 }
470
471 pub fn offscreen(geometry: Geometry) -> Self {
475 let mut inner = Inner::new("offscreen".into(), M::MODEL, Backend::Offscreen(geometry));
476 inner.rebind();
477 Self {
478 inner: Rc::new(RefCell::new(inner)),
479 model: PhantomData,
480 }
481 }
482
483 pub fn resize_offscreen(&mut self, geometry: Geometry) {
487 let mut inner = self.inner.borrow_mut();
488 if let Backend::Offscreen(current) = &mut inner.backend {
489 *current = geometry;
490 inner.rebind();
491 }
492 }
493
494 pub fn id(&self) -> String {
495 self.inner.borrow().id.clone()
496 }
497
498 pub fn geometry(&self) -> Option<Geometry> {
500 let inner = self.inner.borrow();
501 inner
502 .binding
503 .as_ref()
504 .map(|binding| binding.layout.geometry)
505 }
506
507 pub fn size(&self) -> (u32, u32) {
509 self.inner.borrow().extent()
510 }
511
512 pub fn request_size(&self, cols: u32, rows: u32) -> Result<()> {
516 crate::host::surface_request_size(&self.id(), cols, rows)
517 }
518
519 pub fn request_size_px(&self, width: u32, height: u32) -> Result<()> {
523 crate::host::surface_request_size_px(&self.id(), width, height)
524 }
525
526 pub fn set_label(&self, label: Option<&str>) -> Result<()> {
530 crate::host::surface_set_label(&self.id(), label)
531 }
532
533 pub fn set_caret(&self, caret: Option<(u32, u32)>) -> Result<()> {
537 crate::host::surface_set_caret(&self.id(), caret)
538 }
539
540 pub fn is_attached(&self) -> bool {
541 self.inner.borrow().binding.is_some()
542 }
543
544 pub fn is_dirty(&self) -> bool {
547 let inner = self.inner.borrow();
548 inner.binding.is_some() && (inner.full || !inner.dirty.is_empty())
549 }
550
551 pub fn mark_dirty(&mut self, rect: Rect) {
553 self.inner.borrow_mut().mark_dirty(rect);
554 }
555
556 pub fn commit(&mut self) -> Result<bool> {
560 self.inner.borrow_mut().commit()
561 }
562
563 pub fn last_commit(&self) -> Option<CommitInfo> {
565 self.inner.borrow().last_commit.clone()
566 }
567
568 pub fn pending_dirty(&self) -> Vec<Rect> {
571 self.inner.borrow().dirty.rects().to_vec()
572 }
573
574 pub fn detach(&mut self) -> Result<()> {
576 let mut inner = self.inner.borrow_mut();
577 if inner.binding.take().is_some()
578 && let Backend::Host = inner.backend
579 {
580 inner.retired = None;
581 return host::surface_detach(&inner.id);
582 }
583 Ok(())
584 }
585}
586
587impl<M: SurfaceModel> Drop for Surface<M> {
588 fn drop(&mut self) {
589 let _ = self.detach();
592 }
593}
594
595#[derive(Debug)]
601pub struct AnySurface {
602 id: String,
603 surface: Option<AnySurfaceInner>,
604}
605
606#[derive(Debug)]
607enum AnySurfaceInner {
608 Cells(Surface<Cells>),
609 Pixels(Surface<Pixels>),
610}
611
612#[derive(Debug)]
614pub enum AnySurfaceMut<'a> {
615 Cells(&'a mut Surface<Cells>),
616 Pixels(&'a mut Surface<Pixels>),
617}
618
619impl AnySurface {
620 pub fn new(id: &str) -> Self {
622 let mut surface = Self {
623 id: id.into(),
624 surface: None,
625 };
626 surface.sync();
627 surface
628 }
629
630 pub fn id(&self) -> &str {
631 &self.id
632 }
633
634 pub fn model(&self) -> Model {
636 match self.surface {
637 Some(AnySurfaceInner::Pixels(_)) => Model::Pixels,
638 _ => Model::Cells,
639 }
640 }
641
642 fn current_model(&self) -> Option<Model> {
643 let inner = match self.surface.as_ref()? {
644 AnySurfaceInner::Cells(surface) => &surface.inner,
645 AnySurfaceInner::Pixels(surface) => &surface.inner,
646 };
647 let inner = inner.borrow();
648 match &inner.error {
649 Some(Error::WrongModel { found, .. }) => Some(*found),
650 _ => Some(inner.model),
651 }
652 }
653
654 pub fn sync(&mut self) -> bool {
657 let wanted = match self.current_model() {
658 Some(model) => model,
659 None => host::surface_layout(&self.id).map_or(Model::Cells, |layout| layout.model),
660 };
661 if self.surface.is_some() && Some(wanted) == self.surface.as_ref().map(|_| self.model()) {
662 return false;
663 }
664 self.surface = None;
667 self.surface = Some(match wanted {
668 Model::Cells => AnySurfaceInner::Cells(Surface::new(&self.id)),
669 Model::Pixels => AnySurfaceInner::Pixels(Surface::new(&self.id)),
670 });
671 true
672 }
673
674 pub fn get(&mut self) -> AnySurfaceMut<'_> {
676 self.sync();
677 match self.surface.as_mut() {
678 Some(AnySurfaceInner::Pixels(surface)) => AnySurfaceMut::Pixels(surface),
679 Some(AnySurfaceInner::Cells(surface)) => AnySurfaceMut::Cells(surface),
680 None => unreachable!("sync always leaves a surface"),
681 }
682 }
683}
684
685#[derive(Debug)]
692pub struct Instances<M: SurfaceModel> {
693 surface: String,
694 panes: alloc::collections::BTreeMap<String, Surface<M>>,
695}
696
697pub fn instance_pane<'a>(surface: &str, id: &'a str) -> Option<&'a str> {
699 id.strip_prefix(surface)?.strip_prefix('@')
700}
701
702impl<M: SurfaceModel> Instances<M> {
703 pub fn new(surface: &str) -> Self {
705 Self {
706 surface: surface.into(),
707 panes: alloc::collections::BTreeMap::new(),
708 }
709 }
710
711 pub fn event(&mut self, event: &crate::Event) -> Option<String> {
714 let (id, removed) = match event {
715 crate::Event::Resize { surface, geometry } => (surface, geometry.is_empty()),
716 crate::Event::Visibility { surface, .. } => (surface, false),
717 _ => return None,
718 };
719 let pane = String::from(instance_pane(&self.surface, id)?);
720 if removed {
721 self.panes.remove(&pane);
722 } else if !self.panes.contains_key(&pane) {
723 self.panes.insert(pane.clone(), Surface::new(id));
724 }
725 Some(pane)
726 }
727
728 pub fn get_mut(&mut self, pane: &str) -> Option<&mut Surface<M>> {
729 self.panes.get_mut(pane)
730 }
731
732 pub fn instance(&mut self, owner: &str) -> &mut Surface<M> {
737 let surface = &self.surface;
738 self.panes
739 .entry(String::from(owner))
740 .or_insert_with(|| Surface::new(&alloc::format!("{surface}@{owner}")))
741 }
742
743 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Surface<M>)> {
745 self.panes
746 .iter_mut()
747 .map(|(pane, surface)| (pane.as_str(), surface))
748 }
749
750 pub fn len(&self) -> usize {
751 self.panes.len()
752 }
753
754 pub fn is_empty(&self) -> bool {
755 self.panes.is_empty()
756 }
757}
758
759impl Surface<Pixels> {
760 fn embed_bound(&self, bound: bool) {
763 let mut inner = self.inner.borrow_mut();
764 inner.embedded = bound;
765 inner.rebind();
766 }
767
768 pub fn for_embed(id: &str) -> Self {
773 let surface = Self::new_unbound(id);
774 surface.inner.borrow_mut().embedded = true;
775 surface
776 }
777
778 pub fn bind_embed(&self) -> Result<()> {
788 crate::host::surface_bind_embed(&self.id(), true)?;
789 self.embed_bound(true);
790 Ok(())
791 }
792
793 pub fn unbind_embed(&self) -> Result<()> {
796 crate::host::surface_bind_embed(&self.id(), false)?;
797 self.embed_bound(false);
798 Ok(())
799 }
800}