1mod cells;
26mod dirty;
27mod graphic;
28mod pixels;
29
30use alloc::rc::{Rc, Weak};
31use alloc::string::String;
32use alloc::vec;
33use alloc::vec::Vec;
34use core::cell::RefCell;
35use core::marker::PhantomData;
36
37pub use cells::Cell;
38pub(crate) use cells::write_text_clipped;
39use dirty::DirtyRects;
40use graphic::SentGraphics;
41pub(crate) use pixels::Canvas;
42
43use crate::error::{Error, Result};
44use crate::geometry::{Geometry, Rect};
45use crate::host;
46use crate::local::instance_local;
47
48pub const HEADER_LEN: u32 = 32;
50pub const CELL_LEN: u32 = 16;
52pub const PIXEL_LEN: u32 = 4;
54
55const HEADER_WORDS: usize = (HEADER_LEN / 4) as usize;
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
59pub enum Model {
60 Cells,
61 Pixels,
62}
63
64impl Model {
65 pub fn as_str(self) -> &'static str {
66 match self {
67 Self::Cells => "cells",
68 Self::Pixels => "pixels",
69 }
70 }
71
72 fn word(self) -> u32 {
73 match self {
74 Self::Cells => 0,
75 Self::Pixels => 1,
76 }
77 }
78
79 fn unit_words(self) -> usize {
81 match self {
82 Self::Cells => (CELL_LEN / 4) as usize,
83 Self::Pixels => 1,
84 }
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub(crate) struct RegionLayout {
91 pub len: u32,
92 pub header_len: u32,
93 pub slot_len: u32,
94 pub model: Model,
95 pub geometry: Geometry,
96}
97
98impl RegionLayout {
99 pub(crate) fn new(model: Model, geometry: Geometry) -> Self {
101 let slot_len = match model {
102 Model::Cells => geometry.cols * geometry.rows * CELL_LEN,
103 Model::Pixels => geometry.px_w * geometry.px_h * PIXEL_LEN,
104 };
105 Self {
106 len: HEADER_LEN + 2 * slot_len,
107 header_len: HEADER_LEN,
108 slot_len,
109 model,
110 geometry,
111 }
112 }
113
114 fn extent(&self) -> (u32, u32) {
116 match self.model {
117 Model::Cells => (self.geometry.cols, self.geometry.rows),
118 Model::Pixels => (self.geometry.px_w, self.geometry.px_h),
119 }
120 }
121
122 fn slot_words(&self) -> usize {
123 (self.slot_len / 4) as usize
124 }
125}
126
127mod sealed {
128 pub trait Sealed {}
129}
130
131pub trait SurfaceModel: sealed::Sealed {
133 const MODEL: Model;
134}
135
136#[derive(Clone, Copy, Debug)]
138pub enum Cells {}
139
140#[derive(Clone, Copy, Debug)]
143pub enum Pixels {}
144
145impl sealed::Sealed for Cells {}
146impl sealed::Sealed for Pixels {}
147
148impl SurfaceModel for Cells {
149 const MODEL: Model = Model::Cells;
150}
151
152impl SurfaceModel for Pixels {
153 const MODEL: Model = Model::Pixels;
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161pub struct AgentPointer {
162 pub x_px: u32,
163 pub y_px: u32,
164 pub press: bool,
166}
167
168#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
171pub struct Scroll {
172 pub rows: u32,
175 pub fixed_top: u32,
177 pub fixed_bottom: u32,
180}
181
182impl Scroll {
183 pub const MAX_ROWS: u32 = 4096;
185
186 pub const fn rows(rows: u32) -> Self {
188 Self {
189 rows,
190 fixed_top: 0,
191 fixed_bottom: 0,
192 }
193 }
194
195 pub const fn fixed(self, top: u32, bottom: u32) -> Self {
198 Self {
199 fixed_top: top,
200 fixed_bottom: bottom,
201 ..self
202 }
203 }
204}
205
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
208pub struct Viewport {
209 pub top: u32,
211 pub rows: u32,
213}
214
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct CommitInfo {
217 pub seq: u32,
219 pub slot: u8,
221 pub dirty: Vec<Rect>,
223 pub full: bool,
225}
226
227#[derive(Debug)]
228enum Backend {
229 Host,
231 Offscreen(Geometry),
233}
234
235#[derive(Debug)]
236struct Binding {
237 layout: RegionLayout,
238 region: Vec<u32>,
240 back: u8,
242}
243
244#[derive(Debug)]
245pub(crate) struct Inner {
246 id: String,
247 model: Model,
248 backend: Backend,
249 binding: Option<Binding>,
250 retired: Option<Vec<u32>>,
253 dirty: DirtyRects,
254 sync: Vec<Rect>,
257 full: bool,
259 seq: u32,
260 error: Option<Error>,
261 last_commit: Option<CommitInfo>,
262 embedded: bool,
265 graphics: SentGraphics,
267}
268
269instance_local! {
270 fn registry() -> Vec<Weak<RefCell<Inner>>> = Vec::new();
271}
272
273pub(crate) fn rebind_surfaces(id: &str) {
275 let surfaces: Vec<Rc<RefCell<Inner>>> = registry(|registry| {
276 registry.retain(|weak| weak.strong_count() > 0);
277 registry.iter().filter_map(Weak::upgrade).collect()
278 });
279 for surface in surfaces {
280 let mut inner = surface.borrow_mut();
281 if inner.id == id {
282 inner.rebind();
283 }
284 }
285}
286
287fn as_bytes(words: &[u32]) -> &[u8] {
288 unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), words.len() * 4) }
291}
292
293fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] {
294 unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 4) }
296}
297
298impl Inner {
299 fn new(id: String, model: Model, backend: Backend) -> Self {
300 Self {
301 id,
302 model,
303 backend,
304 binding: None,
305 retired: None,
306 dirty: DirtyRects::default(),
307 sync: Vec::new(),
308 full: false,
309 seq: 0,
310 error: None,
311 last_commit: None,
312 embedded: false,
313 graphics: SentGraphics::default(),
314 }
315 }
316
317 fn rebind(&mut self) {
318 match self.bind() {
319 Ok(_) => self.error = None,
320 Err(error) => self.error = Some(error),
321 }
322 }
323
324 fn bind(&mut self) -> Result<bool> {
327 if self.embedded {
328 if self.binding.take().is_some() && matches!(self.backend, Backend::Host) {
330 host::surface_detach(&self.id)?;
331 }
332 self.retired = None;
333 return Ok(false);
334 }
335 let layout = match &self.backend {
336 Backend::Host => host::surface_layout(&self.id)?,
337 Backend::Offscreen(geometry) => RegionLayout::new(self.model, *geometry),
338 };
339 if layout.model != self.model {
340 return Err(Error::WrongModel {
341 surface: self.id.clone(),
342 expected: self.model,
343 found: layout.model,
344 });
345 }
346 if layout.geometry.is_empty() {
347 return Ok(false);
348 }
349 let mut region = vec![0u32; (layout.len as usize).div_ceil(4)];
350 let g = layout.geometry;
351 region[..HEADER_WORDS].copy_from_slice(&[
352 self.seq,
353 layout.model.word(),
354 g.cols,
355 g.rows,
356 g.px_w,
357 g.px_h,
358 g.cell_px_w,
359 g.cell_px_h,
360 ]);
361 if let Backend::Host = self.backend {
362 host::surface_attach(&self.id, &as_bytes(®ion)[..layout.len as usize])?;
363 }
364 if let Some(previous) = self.binding.take() {
365 if self.retired.is_none() {
369 self.retired = Some(previous.region);
370 }
371 }
372 self.binding = Some(Binding {
373 layout,
374 region,
375 back: 0,
376 });
377 self.full = true;
378 self.dirty.clear();
379 self.sync.clear();
380 self.graphics.rebound(layout.geometry);
382 Ok(true)
383 }
384
385 fn ensure_bound(&mut self) -> Result<&mut Binding> {
386 if self.binding.is_none() {
387 if let Some(error) = self.error.clone() {
388 return Err(error);
389 }
390 self.bind()?;
391 }
392 let id = &self.id;
393 self.binding.as_mut().ok_or_else(|| Error::NotAttached {
394 surface: id.clone(),
395 })
396 }
397
398 fn extent(&self) -> (u32, u32) {
399 self.binding
400 .as_ref()
401 .map_or((0, 0), |binding| binding.layout.extent())
402 }
403
404 fn apply_sync(&mut self) {
406 let Some(binding) = self.binding.as_mut() else {
407 self.sync.clear();
408 return;
409 };
410 if self.sync.is_empty() {
411 return;
412 }
413 let (width, _) = binding.layout.extent();
414 let unit = binding.layout.model.unit_words();
415 let slot_words = binding.layout.slot_words();
416 let front = HEADER_WORDS + usize::from(binding.back ^ 1) * slot_words;
417 let back = HEADER_WORDS + usize::from(binding.back) * slot_words;
418 for rect in self.sync.drain(..) {
419 for y in rect.y..rect.bottom() {
420 let start = (y as usize * width as usize + rect.x as usize) * unit;
421 let len = rect.w as usize * unit;
422 binding
423 .region
424 .copy_within(front + start..front + start + len, back + start);
425 }
426 }
427 }
428
429 fn back(&mut self) -> Option<(&mut [u32], RegionLayout, &mut DirtyRects)> {
432 self.apply_sync();
433 let binding = self.binding.as_mut()?;
434 let slot_words = binding.layout.slot_words();
435 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
436 Some((
437 &mut binding.region[start..start + slot_words],
438 binding.layout,
439 &mut self.dirty,
440 ))
441 }
442
443 fn back_discard(&mut self) -> Option<(&mut [u32], RegionLayout)> {
446 self.sync.clear();
447 let binding = self.binding.as_mut()?;
448 let (width, height) = binding.layout.extent();
449 self.dirty
450 .add(Rect::new(0, 0, width, height), width, height);
451 let slot_words = binding.layout.slot_words();
452 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
453 Some((
454 &mut binding.region[start..start + slot_words],
455 binding.layout,
456 ))
457 }
458
459 fn mark_dirty(&mut self, rect: Rect) {
460 self.apply_sync();
461 let (width, height) = self.extent();
462 self.dirty.add(rect, width, height);
463 }
464
465 fn commit(&mut self) -> Result<bool> {
466 self.ensure_bound()?;
467 let (width, height) = self.extent();
468 let full = self.full;
469 let rects = if full {
470 self.dirty.clear();
471 if width == 0 || height == 0 {
472 Vec::new()
473 } else {
474 vec![Rect::new(0, 0, width, height)]
475 }
476 } else {
477 self.dirty.take()
478 };
479 if let Backend::Host = self.backend {
480 self.graphics.remove_undrawn(&self.id)?;
481 }
482 if rects.is_empty() {
483 return self.commit_graphics();
484 }
485 let seq = self.seq.wrapping_add(1);
486 let Some(binding) = self.binding.as_mut() else {
487 return Ok(false);
488 };
489 binding.region[0] = seq;
490 let slot = binding.back;
491 if let Backend::Host = self.backend
492 && let Err(error) = host::surface_commit(&self.id, slot, &rects)
493 {
494 for rect in rects {
495 self.dirty.add(rect, width, height);
496 }
497 return Err(error);
498 }
499 binding.back ^= 1;
500 self.graphics.published();
501 self.seq = seq;
502 self.full = false;
503 self.retired = None;
504 self.sync = rects.clone();
505 self.last_commit = Some(CommitInfo {
506 seq,
507 slot,
508 dirty: rects,
509 full,
510 });
511 Ok(true)
512 }
513
514 fn commit_graphics(&mut self) -> Result<bool> {
517 let Some(binding) = self.binding.as_ref() else {
518 return Ok(false);
519 };
520 if !self.graphics.changed() || !matches!(self.backend, Backend::Host) {
521 return Ok(false);
522 }
523 host::surface_commit(&self.id, binding.back, &[])?;
524 self.graphics.published();
525 Ok(true)
526 }
527}
528
529#[derive(Debug)]
531pub struct Surface<M: SurfaceModel> {
532 inner: Rc<RefCell<Inner>>,
533 model: PhantomData<M>,
534}
535
536impl<M: SurfaceModel> Surface<M> {
537 pub fn new(id: &str) -> Self {
540 let surface = Self::new_unbound(id);
541 surface.inner.borrow_mut().rebind();
542 surface
543 }
544
545 fn new_unbound(id: &str) -> Self {
546 let inner = Rc::new(RefCell::new(Inner::new(id.into(), M::MODEL, Backend::Host)));
547 registry(|registry| registry.push(Rc::downgrade(&inner)));
548 Self {
549 inner,
550 model: PhantomData,
551 }
552 }
553
554 pub fn offscreen(geometry: Geometry) -> Self {
558 let mut inner = Inner::new("offscreen".into(), M::MODEL, Backend::Offscreen(geometry));
559 inner.rebind();
560 Self {
561 inner: Rc::new(RefCell::new(inner)),
562 model: PhantomData,
563 }
564 }
565
566 pub fn resize_offscreen(&mut self, geometry: Geometry) {
570 let mut inner = self.inner.borrow_mut();
571 if let Backend::Offscreen(current) = &mut inner.backend {
572 *current = geometry;
573 inner.rebind();
574 }
575 }
576
577 pub fn id(&self) -> String {
578 self.inner.borrow().id.clone()
579 }
580
581 pub fn geometry(&self) -> Option<Geometry> {
583 let inner = self.inner.borrow();
584 inner
585 .binding
586 .as_ref()
587 .map(|binding| binding.layout.geometry)
588 }
589
590 pub fn size(&self) -> (u32, u32) {
592 self.inner.borrow().extent()
593 }
594
595 pub fn request_size(&self, cols: u32, rows: u32) -> Result<()> {
599 crate::host::surface_request_size(&self.id(), cols, rows)
600 }
601
602 pub fn request_size_px(&self, width: u32, height: u32) -> Result<()> {
606 crate::host::surface_request_size_px(&self.id(), width, height)
607 }
608
609 pub fn set_label(&self, label: Option<&str>) -> Result<()> {
613 crate::host::surface_set_label(&self.id(), label)
614 }
615
616 pub fn copy_text(&self, text: &str) -> Result<()> {
619 crate::host::surface_copy_text(&self.id(), text)
620 }
621
622 pub fn set_caret(&self, caret: Option<(u32, u32)>) -> Result<()> {
626 crate::host::surface_set_caret(&self.id(), caret)
627 }
628
629 pub fn set_scroll(&self, scroll: Option<Scroll>) -> Result<()> {
633 crate::host::surface_set_scroll(&self.id(), scroll)
634 }
635
636 pub fn reveal(&self, first: u32, last: u32) -> Result<()> {
639 crate::host::surface_reveal(&self.id(), first, last)
640 }
641
642 pub fn viewport(&self) -> Result<Option<Viewport>> {
645 crate::host::surface_viewport(&self.id())
646 }
647
648 pub fn set_agent_pointer(&self, pointer: Option<AgentPointer>) -> Result<()> {
651 crate::host::surface_set_agent_pointer(&self.id(), pointer)
652 }
653
654 pub fn is_attached(&self) -> bool {
655 self.inner.borrow().binding.is_some()
656 }
657
658 pub fn is_dirty(&self) -> bool {
661 let inner = self.inner.borrow();
662 inner.binding.is_some() && (inner.full || !inner.dirty.is_empty())
663 }
664
665 pub fn mark_dirty(&mut self, rect: Rect) {
667 self.inner.borrow_mut().mark_dirty(rect);
668 }
669
670 pub fn commit(&mut self) -> Result<bool> {
674 self.inner.borrow_mut().commit()
675 }
676
677 pub fn last_commit(&self) -> Option<CommitInfo> {
679 self.inner.borrow().last_commit.clone()
680 }
681
682 pub fn pending_dirty(&self) -> Vec<Rect> {
685 self.inner.borrow().dirty.rects().to_vec()
686 }
687
688 pub fn detach(&mut self) -> Result<()> {
690 let mut inner = self.inner.borrow_mut();
691 inner.graphics = SentGraphics::default();
692 if inner.binding.take().is_some()
693 && let Backend::Host = inner.backend
694 {
695 inner.retired = None;
696 return host::surface_detach(&inner.id);
697 }
698 Ok(())
699 }
700}
701
702impl<M: SurfaceModel> Drop for Surface<M> {
703 fn drop(&mut self) {
704 let _ = self.detach();
707 }
708}
709
710#[derive(Debug)]
716pub struct AnySurface {
717 id: String,
718 surface: Option<AnySurfaceInner>,
719}
720
721#[derive(Debug)]
722enum AnySurfaceInner {
723 Cells(Surface<Cells>),
724 Pixels(Surface<Pixels>),
725}
726
727#[derive(Debug)]
729pub enum AnySurfaceMut<'a> {
730 Cells(&'a mut Surface<Cells>),
731 Pixels(&'a mut Surface<Pixels>),
732}
733
734impl AnySurface {
735 pub fn new(id: &str) -> Self {
737 let mut surface = Self {
738 id: id.into(),
739 surface: None,
740 };
741 surface.sync();
742 surface
743 }
744
745 pub fn id(&self) -> &str {
746 &self.id
747 }
748
749 pub fn model(&self) -> Model {
751 match self.surface {
752 Some(AnySurfaceInner::Pixels(_)) => Model::Pixels,
753 _ => Model::Cells,
754 }
755 }
756
757 fn current_model(&self) -> Option<Model> {
758 let inner = match self.surface.as_ref()? {
759 AnySurfaceInner::Cells(surface) => &surface.inner,
760 AnySurfaceInner::Pixels(surface) => &surface.inner,
761 };
762 let inner = inner.borrow();
763 match &inner.error {
764 Some(Error::WrongModel { found, .. }) => Some(*found),
765 _ => Some(inner.model),
766 }
767 }
768
769 pub fn sync(&mut self) -> bool {
772 let wanted = match self.current_model() {
773 Some(model) => model,
774 None => host::surface_layout(&self.id).map_or(Model::Cells, |layout| layout.model),
775 };
776 if self.surface.is_some() && Some(wanted) == self.surface.as_ref().map(|_| self.model()) {
777 return false;
778 }
779 self.surface = None;
782 self.surface = Some(match wanted {
783 Model::Cells => AnySurfaceInner::Cells(Surface::new(&self.id)),
784 Model::Pixels => AnySurfaceInner::Pixels(Surface::new(&self.id)),
785 });
786 true
787 }
788
789 pub fn get(&mut self) -> AnySurfaceMut<'_> {
791 self.sync();
792 match self.surface.as_mut() {
793 Some(AnySurfaceInner::Pixels(surface)) => AnySurfaceMut::Pixels(surface),
794 Some(AnySurfaceInner::Cells(surface)) => AnySurfaceMut::Cells(surface),
795 None => unreachable!("sync always leaves a surface"),
796 }
797 }
798}
799
800#[derive(Debug)]
807pub struct Instances<M: SurfaceModel> {
808 surface: String,
809 panes: alloc::collections::BTreeMap<String, Surface<M>>,
810}
811
812pub fn instance_pane<'a>(surface: &str, id: &'a str) -> Option<&'a str> {
814 id.strip_prefix(surface)?.strip_prefix('@')
815}
816
817impl<M: SurfaceModel> Instances<M> {
818 pub fn new(surface: &str) -> Self {
820 Self {
821 surface: surface.into(),
822 panes: alloc::collections::BTreeMap::new(),
823 }
824 }
825
826 pub fn event(&mut self, event: &crate::Event) -> Option<String> {
829 let (id, removed) = match event {
830 crate::Event::Resize { surface, geometry } => (surface, geometry.is_empty()),
831 crate::Event::Visibility { surface, .. } => (surface, false),
832 _ => return None,
833 };
834 let pane = String::from(instance_pane(&self.surface, id)?);
835 if removed {
836 self.panes.remove(&pane);
837 } else if !self.panes.contains_key(&pane) {
838 self.panes.insert(pane.clone(), Surface::new(id));
839 }
840 Some(pane)
841 }
842
843 pub fn get_mut(&mut self, pane: &str) -> Option<&mut Surface<M>> {
844 self.panes.get_mut(pane)
845 }
846
847 pub fn instance(&mut self, owner: &str) -> &mut Surface<M> {
852 let surface = &self.surface;
853 self.panes
854 .entry(String::from(owner))
855 .or_insert_with(|| Surface::new(&alloc::format!("{surface}@{owner}")))
856 }
857
858 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Surface<M>)> {
860 self.panes
861 .iter_mut()
862 .map(|(pane, surface)| (pane.as_str(), surface))
863 }
864
865 pub fn len(&self) -> usize {
866 self.panes.len()
867 }
868
869 pub fn is_empty(&self) -> bool {
870 self.panes.is_empty()
871 }
872}
873
874impl Surface<Pixels> {
875 fn embed_bound(&self, bound: bool) {
878 let mut inner = self.inner.borrow_mut();
879 inner.embedded = bound;
880 inner.rebind();
881 }
882
883 pub fn for_embed(id: &str) -> Self {
888 let surface = Self::new_unbound(id);
889 surface.inner.borrow_mut().embedded = true;
890 surface
891 }
892
893 pub fn bind_embed(&self) -> Result<()> {
903 crate::host::surface_bind_embed(&self.id(), true)?;
904 self.embed_bound(true);
905 Ok(())
906 }
907
908 pub fn unbind_embed(&self) -> Result<()> {
911 crate::host::surface_bind_embed(&self.id(), false)?;
912 self.embed_bound(false);
913 Ok(())
914 }
915}