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, Debug, PartialEq, Eq)]
167pub struct CommitInfo {
168 pub seq: u32,
170 pub slot: u8,
172 pub dirty: Vec<Rect>,
174 pub full: bool,
176}
177
178#[derive(Debug)]
179enum Backend {
180 Host,
182 Offscreen(Geometry),
184}
185
186#[derive(Debug)]
187struct Binding {
188 layout: RegionLayout,
189 region: Vec<u32>,
191 back: u8,
193}
194
195#[derive(Debug)]
196pub(crate) struct Inner {
197 id: String,
198 model: Model,
199 backend: Backend,
200 binding: Option<Binding>,
201 retired: Option<Vec<u32>>,
204 dirty: DirtyRects,
205 sync: Vec<Rect>,
208 full: bool,
210 seq: u32,
211 error: Option<Error>,
212 last_commit: Option<CommitInfo>,
213 embedded: bool,
216}
217
218instance_local! {
219 fn registry() -> Vec<Weak<RefCell<Inner>>> = Vec::new();
220}
221
222pub(crate) fn rebind_surfaces(id: &str) {
224 let surfaces: Vec<Rc<RefCell<Inner>>> = registry(|registry| {
225 registry.retain(|weak| weak.strong_count() > 0);
226 registry.iter().filter_map(Weak::upgrade).collect()
227 });
228 for surface in surfaces {
229 let mut inner = surface.borrow_mut();
230 if inner.id == id {
231 inner.rebind();
232 }
233 }
234}
235
236fn as_bytes(words: &[u32]) -> &[u8] {
237 unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), words.len() * 4) }
240}
241
242fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] {
243 unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 4) }
245}
246
247impl Inner {
248 fn new(id: String, model: Model, backend: Backend) -> Self {
249 Self {
250 id,
251 model,
252 backend,
253 binding: None,
254 retired: None,
255 dirty: DirtyRects::default(),
256 sync: Vec::new(),
257 full: false,
258 seq: 0,
259 error: None,
260 last_commit: None,
261 embedded: false,
262 }
263 }
264
265 fn rebind(&mut self) {
266 match self.bind() {
267 Ok(_) => self.error = None,
268 Err(error) => self.error = Some(error),
269 }
270 }
271
272 fn bind(&mut self) -> Result<bool> {
275 if self.embedded {
276 if self.binding.take().is_some() && matches!(self.backend, Backend::Host) {
278 host::surface_detach(&self.id)?;
279 }
280 self.retired = None;
281 return Ok(false);
282 }
283 let layout = match &self.backend {
284 Backend::Host => host::surface_layout(&self.id)?,
285 Backend::Offscreen(geometry) => RegionLayout::new(self.model, *geometry),
286 };
287 if layout.model != self.model {
288 return Err(Error::WrongModel {
289 surface: self.id.clone(),
290 expected: self.model,
291 found: layout.model,
292 });
293 }
294 if layout.geometry.is_empty() {
295 return Ok(false);
296 }
297 let mut region = vec![0u32; (layout.len as usize).div_ceil(4)];
298 let g = layout.geometry;
299 region[..HEADER_WORDS].copy_from_slice(&[
300 self.seq,
301 layout.model.word(),
302 g.cols,
303 g.rows,
304 g.px_w,
305 g.px_h,
306 g.cell_px_w,
307 g.cell_px_h,
308 ]);
309 if let Backend::Host = self.backend {
310 host::surface_attach(&self.id, &as_bytes(®ion)[..layout.len as usize])?;
311 }
312 if let Some(previous) = self.binding.take() {
313 if self.retired.is_none() {
317 self.retired = Some(previous.region);
318 }
319 }
320 self.binding = Some(Binding {
321 layout,
322 region,
323 back: 0,
324 });
325 self.full = true;
326 self.dirty.clear();
327 self.sync.clear();
328 Ok(true)
329 }
330
331 fn ensure_bound(&mut self) -> Result<&mut Binding> {
332 if self.binding.is_none() {
333 if let Some(error) = self.error.clone() {
334 return Err(error);
335 }
336 self.bind()?;
337 }
338 let id = &self.id;
339 self.binding.as_mut().ok_or_else(|| Error::NotAttached {
340 surface: id.clone(),
341 })
342 }
343
344 fn extent(&self) -> (u32, u32) {
345 self.binding
346 .as_ref()
347 .map_or((0, 0), |binding| binding.layout.extent())
348 }
349
350 fn apply_sync(&mut self) {
352 let Some(binding) = self.binding.as_mut() else {
353 self.sync.clear();
354 return;
355 };
356 if self.sync.is_empty() {
357 return;
358 }
359 let (width, _) = binding.layout.extent();
360 let unit = binding.layout.model.unit_words();
361 let slot_words = binding.layout.slot_words();
362 let front = HEADER_WORDS + usize::from(binding.back ^ 1) * slot_words;
363 let back = HEADER_WORDS + usize::from(binding.back) * slot_words;
364 for rect in self.sync.drain(..) {
365 for y in rect.y..rect.bottom() {
366 let start = (y as usize * width as usize + rect.x as usize) * unit;
367 let len = rect.w as usize * unit;
368 binding
369 .region
370 .copy_within(front + start..front + start + len, back + start);
371 }
372 }
373 }
374
375 fn back(&mut self) -> Option<(&mut [u32], RegionLayout, &mut DirtyRects)> {
378 self.apply_sync();
379 let binding = self.binding.as_mut()?;
380 let slot_words = binding.layout.slot_words();
381 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
382 Some((
383 &mut binding.region[start..start + slot_words],
384 binding.layout,
385 &mut self.dirty,
386 ))
387 }
388
389 fn back_discard(&mut self) -> Option<(&mut [u32], RegionLayout)> {
392 self.sync.clear();
393 let binding = self.binding.as_mut()?;
394 let (width, height) = binding.layout.extent();
395 self.dirty
396 .add(Rect::new(0, 0, width, height), width, height);
397 let slot_words = binding.layout.slot_words();
398 let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
399 Some((
400 &mut binding.region[start..start + slot_words],
401 binding.layout,
402 ))
403 }
404
405 fn mark_dirty(&mut self, rect: Rect) {
406 self.apply_sync();
407 let (width, height) = self.extent();
408 self.dirty.add(rect, width, height);
409 }
410
411 fn commit(&mut self) -> Result<bool> {
412 self.ensure_bound()?;
413 let (width, height) = self.extent();
414 let full = self.full;
415 let rects = if full {
416 self.dirty.clear();
417 if width == 0 || height == 0 {
418 Vec::new()
419 } else {
420 vec![Rect::new(0, 0, width, height)]
421 }
422 } else {
423 self.dirty.take()
424 };
425 if rects.is_empty() {
426 return Ok(false);
427 }
428 let seq = self.seq.wrapping_add(1);
429 let Some(binding) = self.binding.as_mut() else {
430 return Ok(false);
431 };
432 binding.region[0] = seq;
433 let slot = binding.back;
434 if let Backend::Host = self.backend
435 && let Err(error) = host::surface_commit(&self.id, slot, &rects)
436 {
437 for rect in rects {
438 self.dirty.add(rect, width, height);
439 }
440 return Err(error);
441 }
442 binding.back ^= 1;
443 self.seq = seq;
444 self.full = false;
445 self.retired = None;
446 self.sync = rects.clone();
447 self.last_commit = Some(CommitInfo {
448 seq,
449 slot,
450 dirty: rects,
451 full,
452 });
453 Ok(true)
454 }
455}
456
457#[derive(Debug)]
459pub struct Surface<M: SurfaceModel> {
460 inner: Rc<RefCell<Inner>>,
461 model: PhantomData<M>,
462}
463
464impl<M: SurfaceModel> Surface<M> {
465 pub fn new(id: &str) -> Self {
468 let surface = Self::new_unbound(id);
469 surface.inner.borrow_mut().rebind();
470 surface
471 }
472
473 fn new_unbound(id: &str) -> Self {
474 let inner = Rc::new(RefCell::new(Inner::new(id.into(), M::MODEL, Backend::Host)));
475 registry(|registry| registry.push(Rc::downgrade(&inner)));
476 Self {
477 inner,
478 model: PhantomData,
479 }
480 }
481
482 pub fn offscreen(geometry: Geometry) -> Self {
486 let mut inner = Inner::new("offscreen".into(), M::MODEL, Backend::Offscreen(geometry));
487 inner.rebind();
488 Self {
489 inner: Rc::new(RefCell::new(inner)),
490 model: PhantomData,
491 }
492 }
493
494 pub fn resize_offscreen(&mut self, geometry: Geometry) {
498 let mut inner = self.inner.borrow_mut();
499 if let Backend::Offscreen(current) = &mut inner.backend {
500 *current = geometry;
501 inner.rebind();
502 }
503 }
504
505 pub fn id(&self) -> String {
506 self.inner.borrow().id.clone()
507 }
508
509 pub fn geometry(&self) -> Option<Geometry> {
511 let inner = self.inner.borrow();
512 inner
513 .binding
514 .as_ref()
515 .map(|binding| binding.layout.geometry)
516 }
517
518 pub fn size(&self) -> (u32, u32) {
520 self.inner.borrow().extent()
521 }
522
523 pub fn request_size(&self, cols: u32, rows: u32) -> Result<()> {
527 crate::host::surface_request_size(&self.id(), cols, rows)
528 }
529
530 pub fn request_size_px(&self, width: u32, height: u32) -> Result<()> {
534 crate::host::surface_request_size_px(&self.id(), width, height)
535 }
536
537 pub fn set_label(&self, label: Option<&str>) -> Result<()> {
541 crate::host::surface_set_label(&self.id(), label)
542 }
543
544 pub fn copy_text(&self, text: &str) -> Result<()> {
547 crate::host::surface_copy_text(&self.id(), text)
548 }
549
550 pub fn set_caret(&self, caret: Option<(u32, u32)>) -> Result<()> {
554 crate::host::surface_set_caret(&self.id(), caret)
555 }
556
557 pub fn set_agent_pointer(&self, pointer: Option<AgentPointer>) -> Result<()> {
560 crate::host::surface_set_agent_pointer(&self.id(), pointer)
561 }
562
563 pub fn is_attached(&self) -> bool {
564 self.inner.borrow().binding.is_some()
565 }
566
567 pub fn is_dirty(&self) -> bool {
570 let inner = self.inner.borrow();
571 inner.binding.is_some() && (inner.full || !inner.dirty.is_empty())
572 }
573
574 pub fn mark_dirty(&mut self, rect: Rect) {
576 self.inner.borrow_mut().mark_dirty(rect);
577 }
578
579 pub fn commit(&mut self) -> Result<bool> {
583 self.inner.borrow_mut().commit()
584 }
585
586 pub fn last_commit(&self) -> Option<CommitInfo> {
588 self.inner.borrow().last_commit.clone()
589 }
590
591 pub fn pending_dirty(&self) -> Vec<Rect> {
594 self.inner.borrow().dirty.rects().to_vec()
595 }
596
597 pub fn detach(&mut self) -> Result<()> {
599 let mut inner = self.inner.borrow_mut();
600 if inner.binding.take().is_some()
601 && let Backend::Host = inner.backend
602 {
603 inner.retired = None;
604 return host::surface_detach(&inner.id);
605 }
606 Ok(())
607 }
608}
609
610impl<M: SurfaceModel> Drop for Surface<M> {
611 fn drop(&mut self) {
612 let _ = self.detach();
615 }
616}
617
618#[derive(Debug)]
624pub struct AnySurface {
625 id: String,
626 surface: Option<AnySurfaceInner>,
627}
628
629#[derive(Debug)]
630enum AnySurfaceInner {
631 Cells(Surface<Cells>),
632 Pixels(Surface<Pixels>),
633}
634
635#[derive(Debug)]
637pub enum AnySurfaceMut<'a> {
638 Cells(&'a mut Surface<Cells>),
639 Pixels(&'a mut Surface<Pixels>),
640}
641
642impl AnySurface {
643 pub fn new(id: &str) -> Self {
645 let mut surface = Self {
646 id: id.into(),
647 surface: None,
648 };
649 surface.sync();
650 surface
651 }
652
653 pub fn id(&self) -> &str {
654 &self.id
655 }
656
657 pub fn model(&self) -> Model {
659 match self.surface {
660 Some(AnySurfaceInner::Pixels(_)) => Model::Pixels,
661 _ => Model::Cells,
662 }
663 }
664
665 fn current_model(&self) -> Option<Model> {
666 let inner = match self.surface.as_ref()? {
667 AnySurfaceInner::Cells(surface) => &surface.inner,
668 AnySurfaceInner::Pixels(surface) => &surface.inner,
669 };
670 let inner = inner.borrow();
671 match &inner.error {
672 Some(Error::WrongModel { found, .. }) => Some(*found),
673 _ => Some(inner.model),
674 }
675 }
676
677 pub fn sync(&mut self) -> bool {
680 let wanted = match self.current_model() {
681 Some(model) => model,
682 None => host::surface_layout(&self.id).map_or(Model::Cells, |layout| layout.model),
683 };
684 if self.surface.is_some() && Some(wanted) == self.surface.as_ref().map(|_| self.model()) {
685 return false;
686 }
687 self.surface = None;
690 self.surface = Some(match wanted {
691 Model::Cells => AnySurfaceInner::Cells(Surface::new(&self.id)),
692 Model::Pixels => AnySurfaceInner::Pixels(Surface::new(&self.id)),
693 });
694 true
695 }
696
697 pub fn get(&mut self) -> AnySurfaceMut<'_> {
699 self.sync();
700 match self.surface.as_mut() {
701 Some(AnySurfaceInner::Pixels(surface)) => AnySurfaceMut::Pixels(surface),
702 Some(AnySurfaceInner::Cells(surface)) => AnySurfaceMut::Cells(surface),
703 None => unreachable!("sync always leaves a surface"),
704 }
705 }
706}
707
708#[derive(Debug)]
715pub struct Instances<M: SurfaceModel> {
716 surface: String,
717 panes: alloc::collections::BTreeMap<String, Surface<M>>,
718}
719
720pub fn instance_pane<'a>(surface: &str, id: &'a str) -> Option<&'a str> {
722 id.strip_prefix(surface)?.strip_prefix('@')
723}
724
725impl<M: SurfaceModel> Instances<M> {
726 pub fn new(surface: &str) -> Self {
728 Self {
729 surface: surface.into(),
730 panes: alloc::collections::BTreeMap::new(),
731 }
732 }
733
734 pub fn event(&mut self, event: &crate::Event) -> Option<String> {
737 let (id, removed) = match event {
738 crate::Event::Resize { surface, geometry } => (surface, geometry.is_empty()),
739 crate::Event::Visibility { surface, .. } => (surface, false),
740 _ => return None,
741 };
742 let pane = String::from(instance_pane(&self.surface, id)?);
743 if removed {
744 self.panes.remove(&pane);
745 } else if !self.panes.contains_key(&pane) {
746 self.panes.insert(pane.clone(), Surface::new(id));
747 }
748 Some(pane)
749 }
750
751 pub fn get_mut(&mut self, pane: &str) -> Option<&mut Surface<M>> {
752 self.panes.get_mut(pane)
753 }
754
755 pub fn instance(&mut self, owner: &str) -> &mut Surface<M> {
760 let surface = &self.surface;
761 self.panes
762 .entry(String::from(owner))
763 .or_insert_with(|| Surface::new(&alloc::format!("{surface}@{owner}")))
764 }
765
766 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Surface<M>)> {
768 self.panes
769 .iter_mut()
770 .map(|(pane, surface)| (pane.as_str(), surface))
771 }
772
773 pub fn len(&self) -> usize {
774 self.panes.len()
775 }
776
777 pub fn is_empty(&self) -> bool {
778 self.panes.is_empty()
779 }
780}
781
782impl Surface<Pixels> {
783 fn embed_bound(&self, bound: bool) {
786 let mut inner = self.inner.borrow_mut();
787 inner.embedded = bound;
788 inner.rebind();
789 }
790
791 pub fn for_embed(id: &str) -> Self {
796 let surface = Self::new_unbound(id);
797 surface.inner.borrow_mut().embedded = true;
798 surface
799 }
800
801 pub fn bind_embed(&self) -> Result<()> {
811 crate::host::surface_bind_embed(&self.id(), true)?;
812 self.embed_bound(true);
813 Ok(())
814 }
815
816 pub fn unbind_embed(&self) -> Result<()> {
819 crate::host::surface_bind_embed(&self.id(), false)?;
820 self.embed_bound(false);
821 Ok(())
822 }
823}