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, Copy, Debug, PartialEq, Eq)]
159pub struct AgentPointer {
160 pub x_px: u32,
161 pub y_px: u32,
162 pub press: bool,
164}
165
166#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
169pub struct Scroll {
170 pub rows: u32,
173 pub fixed_top: u32,
175 pub fixed_bottom: u32,
178}
179
180impl Scroll {
181 pub const MAX_ROWS: u32 = 4096;
183
184 pub const fn rows(rows: u32) -> Self {
186 Self {
187 rows,
188 fixed_top: 0,
189 fixed_bottom: 0,
190 }
191 }
192
193 pub const fn fixed(self, top: u32, bottom: u32) -> Self {
196 Self {
197 fixed_top: top,
198 fixed_bottom: bottom,
199 ..self
200 }
201 }
202}
203
204#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
206pub struct Viewport {
207 pub top: u32,
209 pub rows: u32,
211}
212
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct CommitInfo {
215 pub seq: u32,
217 pub slot: u8,
219 pub dirty: Vec<Rect>,
221 pub full: bool,
223}
224
225#[derive(Debug)]
226enum Backend {
227 Host,
229 Offscreen(Geometry),
231}
232
233#[derive(Debug)]
234struct Binding {
235 layout: RegionLayout,
236 region: Vec<u32>,
238 back: u8,
240}
241
242#[derive(Debug)]
243pub(crate) struct Inner {
244 id: String,
245 model: Model,
246 backend: Backend,
247 binding: Option<Binding>,
248 retired: Option<Vec<u32>>,
251 dirty: DirtyRects,
252 sync: Vec<Rect>,
255 full: bool,
257 seq: u32,
258 error: Option<Error>,
259 last_commit: Option<CommitInfo>,
260 embedded: bool,
263}
264
265instance_local! {
266 fn registry() -> Vec<Weak<RefCell<Inner>>> = Vec::new();
267}
268
269pub(crate) fn rebind_surfaces(id: &str) {
271 let surfaces: Vec<Rc<RefCell<Inner>>> = registry(|registry| {
272 registry.retain(|weak| weak.strong_count() > 0);
273 registry.iter().filter_map(Weak::upgrade).collect()
274 });
275 for surface in surfaces {
276 let mut inner = surface.borrow_mut();
277 if inner.id == id {
278 inner.rebind();
279 }
280 }
281}
282
283fn as_bytes(words: &[u32]) -> &[u8] {
284 unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), words.len() * 4) }
287}
288
289fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] {
290 unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 4) }
292}
293
294impl Inner {
295 fn new(id: String, model: Model, backend: Backend) -> Self {
296 Self {
297 id,
298 model,
299 backend,
300 binding: None,
301 retired: None,
302 dirty: DirtyRects::default(),
303 sync: Vec::new(),
304 full: false,
305 seq: 0,
306 error: None,
307 last_commit: None,
308 embedded: false,
309 }
310 }
311
312 fn rebind(&mut self) {
313 match self.bind() {
314 Ok(_) => self.error = None,
315 Err(error) => self.error = Some(error),
316 }
317 }
318
319 fn bind(&mut self) -> Result<bool> {
322 if self.embedded {
323 if self.binding.take().is_some() && matches!(self.backend, Backend::Host) {
325 host::surface_detach(&self.id)?;
326 }
327 self.retired = None;
328 return Ok(false);
329 }
330 let layout = match &self.backend {
331 Backend::Host => host::surface_layout(&self.id)?,
332 Backend::Offscreen(geometry) => RegionLayout::new(self.model, *geometry),
333 };
334 if layout.model != self.model {
335 return Err(Error::WrongModel {
336 surface: self.id.clone(),
337 expected: self.model,
338 found: layout.model,
339 });
340 }
341 if layout.geometry.is_empty() {
342 return Ok(false);
343 }
344 let mut region = vec![0u32; (layout.len as usize).div_ceil(4)];
345 let g = layout.geometry;
346 region[..HEADER_WORDS].copy_from_slice(&[
347 self.seq,
348 layout.model.word(),
349 g.cols,
350 g.rows,
351 g.px_w,
352 g.px_h,
353 g.cell_px_w,
354 g.cell_px_h,
355 ]);
356 if let Backend::Host = self.backend {
357 host::surface_attach(&self.id, &as_bytes(®ion)[..layout.len as usize])?;
358 }
359 if let Some(previous) = self.binding.take() {
360 if self.retired.is_none() {
364 self.retired = Some(previous.region);
365 }
366 }
367 self.binding = Some(Binding {
368 layout,
369 region,
370 back: 0,
371 });
372 self.full = true;
373 self.dirty.clear();
374 self.sync.clear();
375 Ok(true)
376 }
377
378 fn ensure_bound(&mut self) -> Result<&mut Binding> {
379 if self.binding.is_none() {
380 if let Some(error) = self.error.clone() {
381 return Err(error);
382 }
383 self.bind()?;
384 }
385 let id = &self.id;
386 self.binding.as_mut().ok_or_else(|| Error::NotAttached {
387 surface: id.clone(),
388 })
389 }
390
391 fn extent(&self) -> (u32, u32) {
392 self.binding
393 .as_ref()
394 .map_or((0, 0), |binding| binding.layout.extent())
395 }
396
397 fn apply_sync(&mut self) {
399 let Some(binding) = self.binding.as_mut() else {
400 self.sync.clear();
401 return;
402 };
403 if self.sync.is_empty() {
404 return;
405 }
406 let (width, _) = binding.layout.extent();
407 let unit = binding.layout.model.unit_words();
408 let slot_words = binding.layout.slot_words();
409 let front = HEADER_WORDS + usize::from(binding.back ^ 1) * slot_words;
410 let back = HEADER_WORDS + usize::from(binding.back) * slot_words;
411 for rect in self.sync.drain(..) {
412 for y in rect.y..rect.bottom() {
413 let start = (y as usize * width as usize + rect.x as usize) * unit;
414 let len = rect.w as usize * unit;
415 binding
416 .region
417 .copy_within(front + start..front + start + len, back + start);
418 }
419 }
420 }
421
422 fn back(&mut self) -> Option<(&mut [u32], RegionLayout, &mut DirtyRects)> {
425 self.apply_sync();
426 let binding = self.binding.as_mut()?;
427 let slot_words = binding.layout.slot_words();
428 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
429 Some((
430 &mut binding.region[start..start + slot_words],
431 binding.layout,
432 &mut self.dirty,
433 ))
434 }
435
436 fn back_discard(&mut self) -> Option<(&mut [u32], RegionLayout)> {
439 self.sync.clear();
440 let binding = self.binding.as_mut()?;
441 let (width, height) = binding.layout.extent();
442 self.dirty
443 .add(Rect::new(0, 0, width, height), width, height);
444 let slot_words = binding.layout.slot_words();
445 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
446 Some((
447 &mut binding.region[start..start + slot_words],
448 binding.layout,
449 ))
450 }
451
452 fn mark_dirty(&mut self, rect: Rect) {
453 self.apply_sync();
454 let (width, height) = self.extent();
455 self.dirty.add(rect, width, height);
456 }
457
458 fn commit(&mut self) -> Result<bool> {
459 self.ensure_bound()?;
460 let (width, height) = self.extent();
461 let full = self.full;
462 let rects = if full {
463 self.dirty.clear();
464 if width == 0 || height == 0 {
465 Vec::new()
466 } else {
467 vec![Rect::new(0, 0, width, height)]
468 }
469 } else {
470 self.dirty.take()
471 };
472 if rects.is_empty() {
473 return Ok(false);
474 }
475 let seq = self.seq.wrapping_add(1);
476 let Some(binding) = self.binding.as_mut() else {
477 return Ok(false);
478 };
479 binding.region[0] = seq;
480 let slot = binding.back;
481 if let Backend::Host = self.backend
482 && let Err(error) = host::surface_commit(&self.id, slot, &rects)
483 {
484 for rect in rects {
485 self.dirty.add(rect, width, height);
486 }
487 return Err(error);
488 }
489 binding.back ^= 1;
490 self.seq = seq;
491 self.full = false;
492 self.retired = None;
493 self.sync = rects.clone();
494 self.last_commit = Some(CommitInfo {
495 seq,
496 slot,
497 dirty: rects,
498 full,
499 });
500 Ok(true)
501 }
502}
503
504#[derive(Debug)]
506pub struct Surface<M: SurfaceModel> {
507 inner: Rc<RefCell<Inner>>,
508 model: PhantomData<M>,
509}
510
511impl<M: SurfaceModel> Surface<M> {
512 pub fn new(id: &str) -> Self {
515 let surface = Self::new_unbound(id);
516 surface.inner.borrow_mut().rebind();
517 surface
518 }
519
520 fn new_unbound(id: &str) -> Self {
521 let inner = Rc::new(RefCell::new(Inner::new(id.into(), M::MODEL, Backend::Host)));
522 registry(|registry| registry.push(Rc::downgrade(&inner)));
523 Self {
524 inner,
525 model: PhantomData,
526 }
527 }
528
529 pub fn offscreen(geometry: Geometry) -> Self {
533 let mut inner = Inner::new("offscreen".into(), M::MODEL, Backend::Offscreen(geometry));
534 inner.rebind();
535 Self {
536 inner: Rc::new(RefCell::new(inner)),
537 model: PhantomData,
538 }
539 }
540
541 pub fn resize_offscreen(&mut self, geometry: Geometry) {
545 let mut inner = self.inner.borrow_mut();
546 if let Backend::Offscreen(current) = &mut inner.backend {
547 *current = geometry;
548 inner.rebind();
549 }
550 }
551
552 pub fn id(&self) -> String {
553 self.inner.borrow().id.clone()
554 }
555
556 pub fn geometry(&self) -> Option<Geometry> {
558 let inner = self.inner.borrow();
559 inner
560 .binding
561 .as_ref()
562 .map(|binding| binding.layout.geometry)
563 }
564
565 pub fn size(&self) -> (u32, u32) {
567 self.inner.borrow().extent()
568 }
569
570 pub fn request_size(&self, cols: u32, rows: u32) -> Result<()> {
574 crate::host::surface_request_size(&self.id(), cols, rows)
575 }
576
577 pub fn request_size_px(&self, width: u32, height: u32) -> Result<()> {
581 crate::host::surface_request_size_px(&self.id(), width, height)
582 }
583
584 pub fn set_label(&self, label: Option<&str>) -> Result<()> {
588 crate::host::surface_set_label(&self.id(), label)
589 }
590
591 pub fn copy_text(&self, text: &str) -> Result<()> {
594 crate::host::surface_copy_text(&self.id(), text)
595 }
596
597 pub fn set_caret(&self, caret: Option<(u32, u32)>) -> Result<()> {
601 crate::host::surface_set_caret(&self.id(), caret)
602 }
603
604 pub fn set_scroll(&self, scroll: Option<Scroll>) -> Result<()> {
608 crate::host::surface_set_scroll(&self.id(), scroll)
609 }
610
611 pub fn reveal(&self, first: u32, last: u32) -> Result<()> {
614 crate::host::surface_reveal(&self.id(), first, last)
615 }
616
617 pub fn viewport(&self) -> Result<Option<Viewport>> {
620 crate::host::surface_viewport(&self.id())
621 }
622
623 pub fn set_agent_pointer(&self, pointer: Option<AgentPointer>) -> Result<()> {
626 crate::host::surface_set_agent_pointer(&self.id(), pointer)
627 }
628
629 pub fn is_attached(&self) -> bool {
630 self.inner.borrow().binding.is_some()
631 }
632
633 pub fn is_dirty(&self) -> bool {
636 let inner = self.inner.borrow();
637 inner.binding.is_some() && (inner.full || !inner.dirty.is_empty())
638 }
639
640 pub fn mark_dirty(&mut self, rect: Rect) {
642 self.inner.borrow_mut().mark_dirty(rect);
643 }
644
645 pub fn commit(&mut self) -> Result<bool> {
649 self.inner.borrow_mut().commit()
650 }
651
652 pub fn last_commit(&self) -> Option<CommitInfo> {
654 self.inner.borrow().last_commit.clone()
655 }
656
657 pub fn pending_dirty(&self) -> Vec<Rect> {
660 self.inner.borrow().dirty.rects().to_vec()
661 }
662
663 pub fn detach(&mut self) -> Result<()> {
665 let mut inner = self.inner.borrow_mut();
666 if inner.binding.take().is_some()
667 && let Backend::Host = inner.backend
668 {
669 inner.retired = None;
670 return host::surface_detach(&inner.id);
671 }
672 Ok(())
673 }
674}
675
676impl<M: SurfaceModel> Drop for Surface<M> {
677 fn drop(&mut self) {
678 let _ = self.detach();
681 }
682}
683
684#[derive(Debug)]
690pub struct AnySurface {
691 id: String,
692 surface: Option<AnySurfaceInner>,
693}
694
695#[derive(Debug)]
696enum AnySurfaceInner {
697 Cells(Surface<Cells>),
698 Pixels(Surface<Pixels>),
699}
700
701#[derive(Debug)]
703pub enum AnySurfaceMut<'a> {
704 Cells(&'a mut Surface<Cells>),
705 Pixels(&'a mut Surface<Pixels>),
706}
707
708impl AnySurface {
709 pub fn new(id: &str) -> Self {
711 let mut surface = Self {
712 id: id.into(),
713 surface: None,
714 };
715 surface.sync();
716 surface
717 }
718
719 pub fn id(&self) -> &str {
720 &self.id
721 }
722
723 pub fn model(&self) -> Model {
725 match self.surface {
726 Some(AnySurfaceInner::Pixels(_)) => Model::Pixels,
727 _ => Model::Cells,
728 }
729 }
730
731 fn current_model(&self) -> Option<Model> {
732 let inner = match self.surface.as_ref()? {
733 AnySurfaceInner::Cells(surface) => &surface.inner,
734 AnySurfaceInner::Pixels(surface) => &surface.inner,
735 };
736 let inner = inner.borrow();
737 match &inner.error {
738 Some(Error::WrongModel { found, .. }) => Some(*found),
739 _ => Some(inner.model),
740 }
741 }
742
743 pub fn sync(&mut self) -> bool {
746 let wanted = match self.current_model() {
747 Some(model) => model,
748 None => host::surface_layout(&self.id).map_or(Model::Cells, |layout| layout.model),
749 };
750 if self.surface.is_some() && Some(wanted) == self.surface.as_ref().map(|_| self.model()) {
751 return false;
752 }
753 self.surface = None;
756 self.surface = Some(match wanted {
757 Model::Cells => AnySurfaceInner::Cells(Surface::new(&self.id)),
758 Model::Pixels => AnySurfaceInner::Pixels(Surface::new(&self.id)),
759 });
760 true
761 }
762
763 pub fn get(&mut self) -> AnySurfaceMut<'_> {
765 self.sync();
766 match self.surface.as_mut() {
767 Some(AnySurfaceInner::Pixels(surface)) => AnySurfaceMut::Pixels(surface),
768 Some(AnySurfaceInner::Cells(surface)) => AnySurfaceMut::Cells(surface),
769 None => unreachable!("sync always leaves a surface"),
770 }
771 }
772}
773
774#[derive(Debug)]
781pub struct Instances<M: SurfaceModel> {
782 surface: String,
783 panes: alloc::collections::BTreeMap<String, Surface<M>>,
784}
785
786pub fn instance_pane<'a>(surface: &str, id: &'a str) -> Option<&'a str> {
788 id.strip_prefix(surface)?.strip_prefix('@')
789}
790
791impl<M: SurfaceModel> Instances<M> {
792 pub fn new(surface: &str) -> Self {
794 Self {
795 surface: surface.into(),
796 panes: alloc::collections::BTreeMap::new(),
797 }
798 }
799
800 pub fn event(&mut self, event: &crate::Event) -> Option<String> {
803 let (id, removed) = match event {
804 crate::Event::Resize { surface, geometry } => (surface, geometry.is_empty()),
805 crate::Event::Visibility { surface, .. } => (surface, false),
806 _ => return None,
807 };
808 let pane = String::from(instance_pane(&self.surface, id)?);
809 if removed {
810 self.panes.remove(&pane);
811 } else if !self.panes.contains_key(&pane) {
812 self.panes.insert(pane.clone(), Surface::new(id));
813 }
814 Some(pane)
815 }
816
817 pub fn get_mut(&mut self, pane: &str) -> Option<&mut Surface<M>> {
818 self.panes.get_mut(pane)
819 }
820
821 pub fn instance(&mut self, owner: &str) -> &mut Surface<M> {
826 let surface = &self.surface;
827 self.panes
828 .entry(String::from(owner))
829 .or_insert_with(|| Surface::new(&alloc::format!("{surface}@{owner}")))
830 }
831
832 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Surface<M>)> {
834 self.panes
835 .iter_mut()
836 .map(|(pane, surface)| (pane.as_str(), surface))
837 }
838
839 pub fn len(&self) -> usize {
840 self.panes.len()
841 }
842
843 pub fn is_empty(&self) -> bool {
844 self.panes.is_empty()
845 }
846}
847
848impl Surface<Pixels> {
849 fn embed_bound(&self, bound: bool) {
852 let mut inner = self.inner.borrow_mut();
853 inner.embedded = bound;
854 inner.rebind();
855 }
856
857 pub fn for_embed(id: &str) -> Self {
862 let surface = Self::new_unbound(id);
863 surface.inner.borrow_mut().embedded = true;
864 surface
865 }
866
867 pub fn bind_embed(&self) -> Result<()> {
877 crate::host::surface_bind_embed(&self.id(), true)?;
878 self.embed_bound(true);
879 Ok(())
880 }
881
882 pub fn unbind_embed(&self) -> Result<()> {
885 crate::host::surface_bind_embed(&self.id(), false)?;
886 self.embed_bound(false);
887 Ok(())
888 }
889}