1use std::collections::{BTreeMap, BTreeSet};
12use std::fmt;
13
14use ftui_core::geometry::{Rect, Sides};
15use serde::{Deserialize, Serialize};
16use smallvec::{SmallVec, smallvec};
17
18pub const PANE_TREE_SCHEMA_VERSION: u16 = 1;
20
21pub const PANE_TREE_MAX_DEPTH: usize = 512;
33
34pub const PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION: u16 = 1;
40
41pub const PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION: u16 = 1;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48#[serde(transparent)]
49pub struct PaneId(u64);
50
51impl PaneId {
52 pub const MIN: Self = Self(1);
54
55 pub fn new(raw: u64) -> Result<Self, PaneModelError> {
57 if raw == 0 {
58 return Err(PaneModelError::ZeroPaneId);
59 }
60 Ok(Self(raw))
61 }
62
63 #[must_use]
65 pub const fn get(self) -> u64 {
66 self.0
67 }
68
69 pub fn checked_next(self) -> Result<Self, PaneModelError> {
71 let Some(next) = self.0.checked_add(1) else {
72 return Err(PaneModelError::PaneIdOverflow { current: self });
73 };
74 Self::new(next)
75 }
76}
77
78impl Default for PaneId {
79 fn default() -> Self {
80 Self::MIN
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum SplitAxis {
88 Horizontal,
89 Vertical,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
97pub struct PaneSplitRatio {
98 numerator: u32,
99 denominator: u32,
100}
101
102impl PaneSplitRatio {
103 pub fn new(numerator: u32, denominator: u32) -> Result<Self, PaneModelError> {
105 if numerator == 0 || denominator == 0 {
106 return Err(PaneModelError::InvalidSplitRatio {
107 numerator,
108 denominator,
109 });
110 }
111 let gcd = gcd_u32(numerator, denominator);
112 Ok(Self {
113 numerator: numerator / gcd,
114 denominator: denominator / gcd,
115 })
116 }
117
118 #[must_use]
120 pub const fn numerator(self) -> u32 {
121 if self.numerator == 0 {
122 1
123 } else {
124 self.numerator
125 }
126 }
127
128 #[must_use]
130 pub const fn denominator(self) -> u32 {
131 if self.denominator == 0 {
132 1
133 } else {
134 self.denominator
135 }
136 }
137}
138
139impl Default for PaneSplitRatio {
140 fn default() -> Self {
141 Self {
142 numerator: 1,
143 denominator: 1,
144 }
145 }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150pub struct PaneConstraints {
151 pub min_width: u16,
152 pub min_height: u16,
153 pub max_width: Option<u16>,
154 pub max_height: Option<u16>,
155 pub collapsible: bool,
156 #[serde(default)]
157 pub margin: Option<u16>,
158 #[serde(default)]
159 pub padding: Option<u16>,
160}
161
162impl PaneConstraints {
163 pub fn validate(self, node_id: PaneId) -> Result<(), PaneModelError> {
165 if let Some(max_width) = self.max_width
166 && max_width < self.min_width
167 {
168 return Err(PaneModelError::InvalidConstraint {
169 node_id,
170 axis: "width",
171 min: self.min_width,
172 max: max_width,
173 });
174 }
175 if let Some(max_height) = self.max_height
176 && max_height < self.min_height
177 {
178 return Err(PaneModelError::InvalidConstraint {
179 node_id,
180 axis: "height",
181 min: self.min_height,
182 max: max_height,
183 });
184 }
185 Ok(())
186 }
187}
188
189impl Default for PaneConstraints {
190 fn default() -> Self {
191 Self {
192 min_width: 1,
193 min_height: 1,
194 max_width: None,
195 max_height: None,
196 collapsible: false,
197 margin: Some(PANE_DEFAULT_MARGIN_CELLS),
198 padding: Some(PANE_DEFAULT_PADDING_CELLS),
199 }
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205pub struct PaneLeaf {
206 pub surface_key: String,
208 #[serde(
210 default,
211 rename = "leaf_extensions",
212 skip_serializing_if = "BTreeMap::is_empty"
213 )]
214 pub extensions: BTreeMap<String, String>,
215}
216
217impl PaneLeaf {
218 #[must_use]
220 pub fn new(surface_key: impl Into<String>) -> Self {
221 Self {
222 surface_key: surface_key.into(),
223 extensions: BTreeMap::new(),
224 }
225 }
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct PaneSplit {
231 pub axis: SplitAxis,
232 pub ratio: PaneSplitRatio,
233 pub first: PaneId,
234 pub second: PaneId,
235}
236
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(tag = "kind", rename_all = "snake_case")]
240pub enum PaneNodeKind {
241 Leaf(PaneLeaf),
242 Split(PaneSplit),
243}
244
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247pub struct PaneNodeRecord {
248 pub id: PaneId,
249 #[serde(default)]
250 pub parent: Option<PaneId>,
251 #[serde(default)]
252 pub constraints: PaneConstraints,
253 #[serde(flatten)]
254 pub kind: PaneNodeKind,
255 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
257 pub extensions: BTreeMap<String, String>,
258}
259
260impl PaneNodeRecord {
261 #[must_use]
263 pub fn leaf(id: PaneId, parent: Option<PaneId>, leaf: PaneLeaf) -> Self {
264 Self {
265 id,
266 parent,
267 constraints: PaneConstraints::default(),
268 kind: PaneNodeKind::Leaf(leaf),
269 extensions: BTreeMap::new(),
270 }
271 }
272
273 #[must_use]
275 pub fn split(id: PaneId, parent: Option<PaneId>, split: PaneSplit) -> Self {
276 Self {
277 id,
278 parent,
279 constraints: PaneConstraints::default(),
280 kind: PaneNodeKind::Split(split),
281 extensions: BTreeMap::new(),
282 }
283 }
284}
285
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290pub struct PaneTreeSnapshot {
291 #[serde(default = "default_schema_version")]
292 pub schema_version: u16,
293 pub root: PaneId,
294 pub next_id: PaneId,
295 pub nodes: Vec<PaneNodeRecord>,
296 #[serde(default)]
297 pub extensions: BTreeMap<String, String>,
298}
299
300fn default_schema_version() -> u16 {
301 PANE_TREE_SCHEMA_VERSION
302}
303
304impl PaneTreeSnapshot {
305 pub fn canonicalize(&mut self) {
307 self.nodes.sort_by_key(|node| node.id);
308 }
309
310 #[must_use]
312 pub fn state_hash(&self) -> u64 {
313 snapshot_state_hash(self)
314 }
315
316 #[must_use]
318 pub fn invariant_report(&self) -> PaneInvariantReport {
319 build_invariant_report(self)
320 }
321
322 pub fn repair_safe(self) -> Result<PaneRepairOutcome, PaneRepairError> {
327 repair_snapshot_safe(self)
328 }
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
333#[serde(rename_all = "snake_case")]
334pub enum PaneInvariantSeverity {
335 Error,
336 Warning,
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
341#[serde(rename_all = "snake_case")]
342pub enum PaneInvariantCode {
343 UnsupportedSchemaVersion,
344 DuplicateNodeId,
345 MissingRoot,
346 RootHasParent,
347 MissingParent,
348 MissingChild,
349 MultipleParents,
350 ParentMismatch,
351 SelfReferentialSplit,
352 DuplicateSplitChildren,
353 InvalidSplitRatio,
354 InvalidConstraint,
355 CycleDetected,
356 UnreachableNode,
357 NextIdNotGreaterThanExisting,
358}
359
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct PaneInvariantIssue {
363 pub code: PaneInvariantCode,
364 pub severity: PaneInvariantSeverity,
365 pub repairable: bool,
366 pub node_id: Option<PaneId>,
367 pub related_node: Option<PaneId>,
368 pub message: String,
369}
370
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373pub struct PaneInvariantReport {
374 pub snapshot_hash: u64,
375 pub issues: Vec<PaneInvariantIssue>,
376}
377
378impl PaneInvariantReport {
379 #[must_use]
381 pub fn has_errors(&self) -> bool {
382 self.issues
383 .iter()
384 .any(|issue| issue.severity == PaneInvariantSeverity::Error)
385 }
386
387 #[must_use]
389 pub fn has_unrepairable_errors(&self) -> bool {
390 self.issues
391 .iter()
392 .any(|issue| issue.severity == PaneInvariantSeverity::Error && !issue.repairable)
393 }
394}
395
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
398#[serde(tag = "action", rename_all = "snake_case")]
399pub enum PaneRepairAction {
400 ReparentNode {
401 node_id: PaneId,
402 before_parent: Option<PaneId>,
403 after_parent: Option<PaneId>,
404 },
405 NormalizeRatio {
406 node_id: PaneId,
407 before_numerator: u32,
408 before_denominator: u32,
409 after_numerator: u32,
410 after_denominator: u32,
411 },
412 RemoveOrphanNode {
413 node_id: PaneId,
414 },
415 BumpNextId {
416 before: PaneId,
417 after: PaneId,
418 },
419}
420
421#[derive(Debug, Clone, PartialEq, Eq)]
423pub struct PaneRepairOutcome {
424 pub before_hash: u64,
425 pub after_hash: u64,
426 pub report_before: PaneInvariantReport,
427 pub report_after: PaneInvariantReport,
428 pub actions: Vec<PaneRepairAction>,
429 pub tree: PaneTree,
430}
431
432#[derive(Debug, Clone, PartialEq, Eq)]
434pub enum PaneRepairFailure {
435 UnsafeIssuesPresent { codes: Vec<PaneInvariantCode> },
436 ValidationFailed { error: PaneModelError },
437}
438
439impl fmt::Display for PaneRepairFailure {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 match self {
442 Self::UnsafeIssuesPresent { codes } => {
443 write!(f, "snapshot contains unsafe invariant issues: {codes:?}")
444 }
445 Self::ValidationFailed { error } => {
446 write!(f, "repaired snapshot failed validation: {error}")
447 }
448 }
449 }
450}
451
452impl std::error::Error for PaneRepairFailure {
453 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
454 if let Self::ValidationFailed { error } = self {
455 return Some(error);
456 }
457 None
458 }
459}
460
461#[derive(Debug, Clone, PartialEq, Eq)]
463pub struct PaneRepairError {
464 pub before_hash: u64,
465 pub report: PaneInvariantReport,
466 pub reason: PaneRepairFailure,
467}
468
469impl fmt::Display for PaneRepairError {
470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
471 write!(
472 f,
473 "pane repair failed: {} (before_hash={:#x}, issues={})",
474 self.reason,
475 self.before_hash,
476 self.report.issues.len()
477 )
478 }
479}
480
481impl std::error::Error for PaneRepairError {
482 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
483 Some(&self.reason)
484 }
485}
486
487#[derive(Debug, Clone, PartialEq, Eq)]
489pub struct PaneLayout {
490 pub area: Rect,
491 rects: BTreeMap<PaneId, Rect>,
492}
493
494impl PaneLayout {
495 #[must_use]
497 pub fn rect(&self, node_id: PaneId) -> Option<Rect> {
498 self.rects.get(&node_id).copied()
499 }
500
501 pub fn iter(&self) -> impl Iterator<Item = (PaneId, Rect)> + '_ {
503 self.rects.iter().map(|(node_id, rect)| (*node_id, *rect))
504 }
505
506 #[must_use]
508 pub fn classify_resize_grip(
509 &self,
510 node_id: PaneId,
511 pointer: PanePointerPosition,
512 inset_cells: f64,
513 ) -> Option<PaneResizeGrip> {
514 let rect = self.rect(node_id)?;
515 classify_resize_grip(rect, pointer, inset_cells)
516 }
517
518 #[must_use]
523 pub fn visual_rect(&self, node_id: PaneId) -> Option<Rect> {
524 let rect = self.rect(node_id)?;
525 let with_margin = rect.inner(Sides::all(PANE_DEFAULT_MARGIN_CELLS));
526 let with_padding = with_margin.inner(Sides::all(PANE_DEFAULT_PADDING_CELLS));
527 if with_padding.width == 0 || with_padding.height == 0 {
528 Some(with_margin)
529 } else {
530 Some(with_padding)
531 }
532 }
533
534 #[must_use]
536 pub fn visual_rect_with_constraints(
537 &self,
538 node_id: PaneId,
539 constraints: &PaneConstraints,
540 ) -> Option<Rect> {
541 let rect = self.rect(node_id)?;
542 let margin = constraints.margin.unwrap_or(PANE_DEFAULT_MARGIN_CELLS);
543 let padding = constraints.padding.unwrap_or(PANE_DEFAULT_PADDING_CELLS);
544 let with_margin = rect.inner(Sides::all(margin));
545 let with_padding = with_margin.inner(Sides::all(padding));
546 if with_padding.width == 0 || with_padding.height == 0 {
547 Some(with_margin)
548 } else {
549 Some(with_padding)
550 }
551 }
552
553 #[must_use]
555 pub fn cluster_bounds(&self, nodes: &BTreeSet<PaneId>) -> Option<Rect> {
556 if nodes.is_empty() {
557 return None;
558 }
559 let mut min_x: Option<u16> = None;
560 let mut min_y: Option<u16> = None;
561 let mut max_x: Option<u16> = None;
562 let mut max_y: Option<u16> = None;
563
564 for node_id in nodes {
565 let rect = self.rect(*node_id)?;
566 min_x = Some(min_x.map_or(rect.x, |v| v.min(rect.x)));
567 min_y = Some(min_y.map_or(rect.y, |v| v.min(rect.y)));
568 let right = rect.x.saturating_add(rect.width);
569 let bottom = rect.y.saturating_add(rect.height);
570 max_x = Some(max_x.map_or(right, |v| v.max(right)));
571 max_y = Some(max_y.map_or(bottom, |v| v.max(bottom)));
572 }
573
574 let left = min_x?;
575 let top = min_y?;
576 let right = max_x?;
577 let bottom = max_y?;
578 Some(Rect::new(
579 left,
580 top,
581 right.saturating_sub(left).max(1),
582 bottom.saturating_sub(top).max(1),
583 ))
584 }
585}
586
587pub const PANE_MAGNETIC_FIELD_CELLS: f64 = 6.0;
589
590pub const PANE_EDGE_GRIP_INSET_CELLS: f64 = 1.5;
592
593pub const PANE_DEFAULT_MARGIN_CELLS: u16 = 1;
595
596pub const PANE_DEFAULT_PADDING_CELLS: u16 = 1;
598
599#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
601#[serde(rename_all = "snake_case")]
602pub enum PaneDockZone {
603 Left,
604 Right,
605 Top,
606 Bottom,
607 Center,
608}
609
610#[derive(Debug, Clone, Copy, PartialEq)]
612pub struct PaneDockPreview {
613 pub target: PaneId,
614 pub zone: PaneDockZone,
615 pub score: f64,
617 pub ghost_rect: Rect,
619}
620
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
623#[serde(rename_all = "snake_case")]
624pub enum PaneResizeGrip {
625 Left,
626 Right,
627 Top,
628 Bottom,
629 TopLeft,
630 TopRight,
631 BottomLeft,
632 BottomRight,
633}
634
635impl PaneResizeGrip {
636 #[must_use]
637 const fn horizontal_edge(self) -> Option<bool> {
638 match self {
639 Self::Left | Self::TopLeft | Self::BottomLeft => Some(false),
640 Self::Right | Self::TopRight | Self::BottomRight => Some(true),
641 Self::Top | Self::Bottom => None,
642 }
643 }
644
645 #[must_use]
646 const fn vertical_edge(self) -> Option<bool> {
647 match self {
648 Self::Top | Self::TopLeft | Self::TopRight => Some(false),
649 Self::Bottom | Self::BottomLeft | Self::BottomRight => Some(true),
650 Self::Left | Self::Right => None,
651 }
652 }
653}
654
655#[derive(Debug, Clone, Copy, PartialEq)]
657pub struct PaneMotionVector {
658 pub delta_x: i32,
659 pub delta_y: i32,
660 pub speed: f64,
662 pub direction_changes: u16,
664}
665
666impl PaneMotionVector {
667 #[must_use]
668 pub fn from_delta(delta_x: i32, delta_y: i32, elapsed_ms: u32, direction_changes: u16) -> Self {
669 let elapsed = f64::from(elapsed_ms.max(1)) / 1_000.0;
670 let dx = f64::from(delta_x);
671 let dy = f64::from(delta_y);
672 let distance = (dx * dx + dy * dy).sqrt();
673 Self {
674 delta_x,
675 delta_y,
676 speed: distance / elapsed,
677 direction_changes,
678 }
679 }
680}
681
682#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
684pub struct PaneInertialThrow {
685 pub velocity_x: f64,
686 pub velocity_y: f64,
687 pub damping: f64,
689 pub horizon_ms: u16,
691}
692
693impl PaneInertialThrow {
694 #[must_use]
695 pub fn from_motion(motion: PaneMotionVector) -> Self {
696 let dx = f64::from(motion.delta_x);
697 let dy = f64::from(motion.delta_y);
698 let magnitude = (dx * dx + dy * dy).sqrt();
699 let direction_x = if magnitude <= f64::EPSILON {
700 0.0
701 } else {
702 dx / magnitude
703 };
704 let direction_y = if magnitude <= f64::EPSILON {
705 0.0
706 } else {
707 dy / magnitude
708 };
709 let speed = motion.speed.clamp(0.0, 220.0);
710 let speed_curve = (speed / 220.0).clamp(0.0, 1.0).powf(0.72);
711 let noise_penalty = (f64::from(motion.direction_changes) / 10.0).clamp(0.0, 1.0);
712 let coherence = (1.0 - 0.55 * noise_penalty).clamp(0.35, 1.0);
713 let projected_velocity = (10.0 + speed * 0.55) * coherence;
714 Self {
715 velocity_x: direction_x * projected_velocity,
716 velocity_y: direction_y * projected_velocity,
717 damping: (9.2 - speed_curve * 4.0 + noise_penalty * 2.4).clamp(4.8, 10.5),
718 horizon_ms: (140.0 + speed_curve * 220.0).round().clamp(120.0, 380.0) as u16,
719 }
720 }
721
722 #[must_use]
723 pub fn projected_pointer(self, start: PanePointerPosition) -> PanePointerPosition {
724 let dt = f64::from(self.horizon_ms) / 1_000.0;
725 let attenuation = (-self.damping * dt).exp();
726 let gain = if self.damping <= f64::EPSILON {
727 dt
728 } else {
729 (1.0 - attenuation) / self.damping
730 };
731 let projected_x = f64::from(start.x) + self.velocity_x * gain;
732 let projected_y = f64::from(start.y) + self.velocity_y * gain;
733 PanePointerPosition::new(round_f64_to_i32(projected_x), round_f64_to_i32(projected_y))
734 }
735}
736
737pub const PANE_AFFORDANCE_EMPHASIS_FULL_BPS: u16 = 10_000;
739
740#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub struct PaneAffordanceMotion {
764 pub reduced_motion: bool,
767 pub fade_in_frames: u16,
770 pub pulse_period_frames: u16,
773 pub pulse_floor_bps: u16,
776}
777
778impl Default for PaneAffordanceMotion {
779 fn default() -> Self {
780 Self {
781 reduced_motion: false,
782 fade_in_frames: 6,
783 pulse_period_frames: 48,
784 pulse_floor_bps: 8_000,
785 }
786 }
787}
788
789impl PaneAffordanceMotion {
790 #[must_use]
793 pub fn reduced() -> Self {
794 Self {
795 reduced_motion: true,
796 ..Self::default()
797 }
798 }
799
800 #[must_use]
803 pub fn with_reduced_motion(mut self, reduced_motion: bool) -> Self {
804 self.reduced_motion = reduced_motion;
805 self
806 }
807
808 #[must_use]
815 pub fn hover_emphasis_bps(&self, elapsed_frames: u16) -> u16 {
816 if self.reduced_motion || self.fade_in_frames == 0 {
817 return PANE_AFFORDANCE_EMPHASIS_FULL_BPS;
818 }
819 affordance_ease_out_bps(elapsed_frames.min(self.fade_in_frames), self.fade_in_frames)
820 }
821
822 #[must_use]
829 pub fn active_pulse_bps(&self, phase_frames: u64) -> u16 {
830 if self.reduced_motion || self.pulse_period_frames == 0 {
831 return PANE_AFFORDANCE_EMPHASIS_FULL_BPS;
832 }
833 let period = self.pulse_period_frames;
834 let half = period / 2;
835 let p = (phase_frames % u64::from(period)) as u16;
836 let ramp = if p < half {
838 affordance_ease_out_bps(p, half)
839 } else {
840 affordance_ease_out_bps(period - p, period - half)
841 };
842 let span = PANE_AFFORDANCE_EMPHASIS_FULL_BPS - self.pulse_floor_bps;
843 self.pulse_floor_bps + ((u32::from(ramp) * u32::from(span)) / 10_000) as u16
844 }
845}
846
847fn affordance_ease_out_bps(t: u16, total: u16) -> u16 {
852 if total == 0 {
853 return PANE_AFFORDANCE_EMPHASIS_FULL_BPS;
854 }
855 let t = t.min(total);
856 let remaining = u64::from(total - t);
857 let total2 = u64::from(total) * u64::from(total);
858 let drop = (10_000u64 * remaining * remaining) / total2;
859 (10_000 - drop) as u16
860}
861
862#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
864pub struct PanePressureSnapProfile {
865 pub strength_bps: u16,
867 pub hysteresis_bps: u16,
869}
870
871impl PanePressureSnapProfile {
872 #[must_use]
877 pub fn from_motion(motion: PaneMotionVector) -> Self {
878 let abs_dx = f64::from(motion.delta_x.unsigned_abs());
879 let abs_dy = f64::from(motion.delta_y.unsigned_abs());
880 let axis_dominance = (abs_dx.max(abs_dy) / (abs_dx + abs_dy).max(1.0)).clamp(0.5, 1.0);
881 let speed_factor = (motion.speed / 70.0).clamp(0.0, 1.0).powf(0.78);
882 let noise_penalty = (f64::from(motion.direction_changes) / 7.0).clamp(0.0, 1.0);
883 let confidence =
884 (speed_factor * (0.65 + axis_dominance * 0.35) * (1.0 - noise_penalty * 0.72))
885 .clamp(0.0, 1.0);
886 let strength = (1_500.0 + confidence.powf(0.85) * 8_500.0).round() as u16;
887 let hysteresis = (60.0 + confidence * 500.0).round() as u16;
888 Self {
889 strength_bps: strength.min(10_000),
890 hysteresis_bps: hysteresis.min(2_000),
891 }
892 }
893
894 #[must_use]
895 pub fn apply_to_tuning(self, base: PaneSnapTuning) -> PaneSnapTuning {
896 let scaled_step = ((u32::from(base.step_bps) * (11_000 - u32::from(self.strength_bps)))
897 / 10_000)
898 .clamp(100, 10_000);
899 PaneSnapTuning {
900 step_bps: scaled_step as u16,
901 hysteresis_bps: self.hysteresis_bps.max(base.hysteresis_bps),
902 }
903 }
904}
905
906#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
908pub struct PaneEdgeResizePlan {
909 pub leaf: PaneId,
910 pub grip: PaneResizeGrip,
911 pub operations: Vec<PaneOperation>,
912}
913
914#[derive(Debug, Clone, PartialEq)]
916pub struct PaneReflowMovePlan {
917 pub source: PaneId,
918 pub pointer: PanePointerPosition,
919 pub projected_pointer: PanePointerPosition,
920 pub preview: PaneDockPreview,
921 pub snap_profile: PanePressureSnapProfile,
922 pub operations: Vec<PaneOperation>,
923}
924
925#[derive(Debug, Clone, PartialEq, Eq)]
927pub enum PaneEdgeResizePlanError {
928 MissingLeaf { leaf: PaneId },
929 NodeNotLeaf { node: PaneId },
930 MissingLayoutRect { node: PaneId },
931 NoAxisSplit { leaf: PaneId, axis: SplitAxis },
932 InvalidRatio { numerator: u32, denominator: u32 },
933}
934
935impl fmt::Display for PaneEdgeResizePlanError {
936 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
937 match self {
938 Self::MissingLeaf { leaf } => write!(f, "pane leaf {} not found", leaf.get()),
939 Self::NodeNotLeaf { node } => write!(f, "node {} is not a leaf", node.get()),
940 Self::MissingLayoutRect { node } => {
941 write!(f, "layout missing rectangle for node {}", node.get())
942 }
943 Self::NoAxisSplit { leaf, axis } => {
944 write!(
945 f,
946 "no ancestor split on {axis:?} axis for leaf {}",
947 leaf.get()
948 )
949 }
950 Self::InvalidRatio {
951 numerator,
952 denominator,
953 } => write!(
954 f,
955 "invalid planned ratio {numerator}/{denominator} for edge resize"
956 ),
957 }
958 }
959}
960
961impl std::error::Error for PaneEdgeResizePlanError {}
962
963#[derive(Debug, Clone, Copy, PartialEq, Eq)]
970pub enum PaneSplitterResizePlanError {
971 MissingSplit { split: PaneId },
973 NotASplit { node: PaneId },
975 AxisMismatch {
977 split: PaneId,
978 expected: SplitAxis,
979 actual: SplitAxis,
980 },
981 MissingLayoutRect { node: PaneId },
983 InvalidRatio { numerator: u32, denominator: u32 },
985}
986
987impl fmt::Display for PaneSplitterResizePlanError {
988 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989 match self {
990 Self::MissingSplit { split } => {
991 write!(f, "splitter target {} not found", split.get())
992 }
993 Self::NotASplit { node } => write!(f, "node {} is a leaf, not a split", node.get()),
994 Self::AxisMismatch {
995 split,
996 expected,
997 actual,
998 } => write!(
999 f,
1000 "split {} has axis {actual:?} but target requested {expected:?}",
1001 split.get()
1002 ),
1003 Self::MissingLayoutRect { node } => {
1004 write!(f, "layout missing rectangle for split {}", node.get())
1005 }
1006 Self::InvalidRatio {
1007 numerator,
1008 denominator,
1009 } => write!(
1010 f,
1011 "invalid planned ratio {numerator}/{denominator} for splitter resize"
1012 ),
1013 }
1014 }
1015}
1016
1017impl std::error::Error for PaneSplitterResizePlanError {}
1018
1019#[derive(Debug, Clone, PartialEq, Eq)]
1021pub enum PaneReflowPlanError {
1022 MissingSource { source: PaneId },
1023 NoDockTarget,
1024 SourceCannotMoveRoot { source: PaneId },
1025 InvalidRatio { numerator: u32, denominator: u32 },
1026}
1027
1028impl fmt::Display for PaneReflowPlanError {
1029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1030 match self {
1031 Self::MissingSource { source } => write!(f, "source node {} not found", source.get()),
1032 Self::NoDockTarget => write!(f, "no magnetic docking target available"),
1033 Self::SourceCannotMoveRoot { source } => {
1034 write!(
1035 f,
1036 "source node {} is root and cannot be reflow-moved",
1037 source.get()
1038 )
1039 }
1040 Self::InvalidRatio {
1041 numerator,
1042 denominator,
1043 } => write!(f, "invalid reflow ratio {numerator}/{denominator}"),
1044 }
1045 }
1046}
1047
1048impl std::error::Error for PaneReflowPlanError {}
1049
1050#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1052pub struct PaneSelectionState {
1053 pub anchor: Option<PaneId>,
1054 pub selected: BTreeSet<PaneId>,
1055}
1056
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1059pub struct PaneGroupTransformPlan {
1060 pub members: Vec<PaneId>,
1061 pub operations: Vec<PaneOperation>,
1062}
1063
1064impl PaneSelectionState {
1065 pub fn shift_toggle(&mut self, pane_id: PaneId) {
1067 if self.selected.contains(&pane_id) {
1068 let _ = self.selected.remove(&pane_id);
1069 if self.anchor == Some(pane_id) {
1070 self.anchor = self.selected.iter().next().copied();
1071 }
1072 } else {
1073 let _ = self.selected.insert(pane_id);
1074 if self.anchor.is_none() {
1075 self.anchor = Some(pane_id);
1076 }
1077 }
1078 }
1079
1080 #[must_use]
1081 pub fn as_sorted_vec(&self) -> Vec<PaneId> {
1082 self.selected.iter().copied().collect()
1083 }
1084
1085 #[must_use]
1086 pub fn is_empty(&self) -> bool {
1087 self.selected.is_empty()
1088 }
1089}
1090
1091#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1093#[serde(rename_all = "snake_case")]
1094pub enum PaneLayoutIntelligenceMode {
1095 Focus,
1096 Compare,
1097 Monitor,
1098 Compact,
1099}
1100
1101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1103pub struct PaneInteractionTimelineEntry {
1104 pub sequence: u64,
1105 pub operation_id: u64,
1106 pub operation: PaneOperation,
1107 pub before_hash: u64,
1108 pub after_hash: u64,
1109}
1110
1111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1113pub struct PaneInteractionTimelineCheckpoint {
1114 pub applied_len: usize,
1115 pub snapshot: PaneTreeSnapshot,
1116}
1117
1118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1120pub struct PaneInteractionTimelineReplayDiagnostics {
1121 pub entry_count: usize,
1122 pub cursor: usize,
1123 pub checkpoint_count: usize,
1124 pub checkpoint_interval: usize,
1125 pub checkpoint_hit: bool,
1126 pub replay_start_idx: usize,
1127 pub replay_depth: usize,
1128}
1129
1130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1132pub struct PaneInteractionTimelineCheckpointDecision {
1133 pub checkpoint_interval: usize,
1134 pub estimated_snapshot_cost_ns: u128,
1135 pub estimated_replay_step_cost_ns: u128,
1136 pub estimated_replay_depth_ns: u128,
1137}
1138
1139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1145pub struct PaneInteractionTimelineRetentionDiagnostics {
1146 pub entry_count: usize,
1147 pub cursor: usize,
1148 pub redo_entry_count: usize,
1149 pub checkpoint_count: usize,
1150 pub checkpoint_interval: usize,
1151 pub max_entries: usize,
1152 pub baseline_present: bool,
1153 pub retained_snapshot_count: usize,
1154 pub baseline_node_count: usize,
1155 pub checkpoint_node_count: usize,
1156 pub retained_snapshot_node_count: usize,
1157 pub retained_leaf_payload_bytes: usize,
1158 pub retained_extension_entry_count: usize,
1159 pub retained_extension_payload_bytes: usize,
1160 pub retained_operation_payload_bytes: usize,
1161 pub estimated_entry_struct_bytes: usize,
1162 pub estimated_checkpoint_struct_bytes: usize,
1163 pub estimated_snapshot_struct_bytes: usize,
1164 pub estimated_total_retained_bytes: usize,
1165}
1166
1167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1169pub struct PaneInteractionTimeline {
1170 pub baseline: Option<PaneTreeSnapshot>,
1172 pub entries: Vec<PaneInteractionTimelineEntry>,
1174 pub cursor: usize,
1176 pub checkpoints: Vec<PaneInteractionTimelineCheckpoint>,
1178 pub checkpoint_interval: usize,
1180 #[serde(default = "default_pane_timeline_max_entries")]
1182 pub max_entries: usize,
1183}
1184
1185const DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL: usize = 16;
1186const DEFAULT_PANE_TIMELINE_MAX_ENTRIES: usize = 4096;
1187
1188fn default_pane_timeline_max_entries() -> usize {
1189 DEFAULT_PANE_TIMELINE_MAX_ENTRIES
1190}
1191
1192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1193enum PaneValidationStrategy {
1194 FullTree,
1195 LocalClosure,
1196}
1197
1198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1206enum PaneValidationMode {
1207 #[default]
1208 Adaptive,
1209 AlwaysFull,
1210}
1211
1212impl Default for PaneInteractionTimeline {
1213 fn default() -> Self {
1214 Self {
1215 baseline: None,
1216 entries: Vec::new(),
1217 cursor: 0,
1218 checkpoints: Vec::new(),
1219 checkpoint_interval: DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL,
1220 max_entries: DEFAULT_PANE_TIMELINE_MAX_ENTRIES,
1221 }
1222 }
1223}
1224
1225#[derive(Debug, Clone, PartialEq, Eq)]
1227pub enum PaneInteractionTimelineError {
1228 MissingBaseline,
1229 BaselineInvalid { source: PaneModelError },
1230 ApplyFailed { source: PaneOperationError },
1231}
1232
1233impl fmt::Display for PaneInteractionTimelineError {
1234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1235 match self {
1236 Self::MissingBaseline => write!(f, "timeline baseline is not set"),
1237 Self::BaselineInvalid { source } => {
1238 write!(f, "failed to restore timeline baseline: {source}")
1239 }
1240 Self::ApplyFailed { source } => write!(f, "timeline replay operation failed: {source}"),
1241 }
1242 }
1243}
1244
1245impl std::error::Error for PaneInteractionTimelineError {
1246 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1247 match self {
1248 Self::BaselineInvalid { source } => Some(source),
1249 Self::ApplyFailed { source } => Some(source),
1250 Self::MissingBaseline => None,
1251 }
1252 }
1253}
1254
1255#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1257#[serde(rename_all = "snake_case")]
1258pub enum PanePlacement {
1259 ExistingFirst,
1260 IncomingFirst,
1261}
1262
1263impl PanePlacement {
1264 fn ordered(self, existing: PaneId, incoming: PaneId) -> (PaneId, PaneId) {
1265 match self {
1266 Self::ExistingFirst => (existing, incoming),
1267 Self::IncomingFirst => (incoming, existing),
1268 }
1269 }
1270}
1271
1272#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1274#[serde(rename_all = "snake_case")]
1275pub enum PanePointerButton {
1276 Primary,
1277 Secondary,
1278 Middle,
1279}
1280
1281#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1283pub struct PanePointerPosition {
1284 pub x: i32,
1285 pub y: i32,
1286}
1287
1288impl PanePointerPosition {
1289 #[must_use]
1290 pub const fn new(x: i32, y: i32) -> Self {
1291 Self { x, y }
1292 }
1293}
1294
1295#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1297pub struct PaneModifierSnapshot {
1298 pub shift: bool,
1299 pub alt: bool,
1300 pub ctrl: bool,
1301 pub meta: bool,
1302}
1303
1304impl PaneModifierSnapshot {
1305 #[must_use]
1306 pub const fn none() -> Self {
1307 Self {
1308 shift: false,
1309 alt: false,
1310 ctrl: false,
1311 meta: false,
1312 }
1313 }
1314}
1315
1316impl Default for PaneModifierSnapshot {
1317 fn default() -> Self {
1318 Self::none()
1319 }
1320}
1321
1322#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1324pub struct PaneResizeTarget {
1325 pub split_id: PaneId,
1326 pub axis: SplitAxis,
1327}
1328
1329#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1331#[serde(rename_all = "snake_case")]
1332pub enum PaneResizeDirection {
1333 Increase,
1334 Decrease,
1335}
1336
1337#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1339#[serde(rename_all = "snake_case")]
1340pub enum PaneCancelReason {
1341 EscapeKey,
1342 PointerCancel,
1343 FocusLost,
1344 Blur,
1345 Programmatic,
1346 ContextLost,
1347 RenderStalled,
1348}
1349
1350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1352#[serde(tag = "event", rename_all = "snake_case")]
1353pub enum PaneSemanticInputEventKind {
1354 PointerDown {
1355 target: PaneResizeTarget,
1356 pointer_id: u32,
1357 button: PanePointerButton,
1358 position: PanePointerPosition,
1359 },
1360 PointerMove {
1361 target: PaneResizeTarget,
1362 pointer_id: u32,
1363 position: PanePointerPosition,
1364 delta_x: i32,
1365 delta_y: i32,
1366 },
1367 PointerUp {
1368 target: PaneResizeTarget,
1369 pointer_id: u32,
1370 button: PanePointerButton,
1371 position: PanePointerPosition,
1372 },
1373 WheelNudge {
1374 target: PaneResizeTarget,
1375 lines: i16,
1376 },
1377 KeyboardResize {
1378 target: PaneResizeTarget,
1379 direction: PaneResizeDirection,
1380 units: u16,
1381 },
1382 Cancel {
1383 target: Option<PaneResizeTarget>,
1384 reason: PaneCancelReason,
1385 },
1386 Blur {
1387 target: Option<PaneResizeTarget>,
1388 },
1389}
1390
1391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1394pub struct PaneSemanticInputEvent {
1395 #[serde(default = "default_pane_semantic_input_event_schema_version")]
1396 pub schema_version: u16,
1397 pub sequence: u64,
1398 #[serde(default)]
1399 pub modifiers: PaneModifierSnapshot,
1400 #[serde(flatten)]
1401 pub kind: PaneSemanticInputEventKind,
1402 #[serde(default)]
1403 pub extensions: BTreeMap<String, String>,
1404}
1405
1406fn default_pane_semantic_input_event_schema_version() -> u16 {
1407 PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION
1408}
1409
1410impl PaneSemanticInputEvent {
1411 #[must_use]
1413 pub fn new(sequence: u64, kind: PaneSemanticInputEventKind) -> Self {
1414 Self {
1415 schema_version: PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION,
1416 sequence,
1417 modifiers: PaneModifierSnapshot::default(),
1418 kind,
1419 extensions: BTreeMap::new(),
1420 }
1421 }
1422
1423 pub fn validate(&self) -> Result<(), PaneSemanticInputEventError> {
1425 if self.schema_version != PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION {
1426 return Err(PaneSemanticInputEventError::UnsupportedSchemaVersion {
1427 version: self.schema_version,
1428 expected: PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION,
1429 });
1430 }
1431 if self.sequence == 0 {
1432 return Err(PaneSemanticInputEventError::ZeroSequence);
1433 }
1434
1435 match self.kind {
1436 PaneSemanticInputEventKind::PointerDown { pointer_id, .. }
1437 | PaneSemanticInputEventKind::PointerMove { pointer_id, .. }
1438 | PaneSemanticInputEventKind::PointerUp { pointer_id, .. } => {
1439 if pointer_id == 0 {
1440 return Err(PaneSemanticInputEventError::ZeroPointerId);
1441 }
1442 }
1443 PaneSemanticInputEventKind::WheelNudge { lines, .. } => {
1444 if lines == 0 {
1445 return Err(PaneSemanticInputEventError::ZeroWheelLines);
1446 }
1447 }
1448 PaneSemanticInputEventKind::KeyboardResize { units, .. } => {
1449 if units == 0 {
1450 return Err(PaneSemanticInputEventError::ZeroResizeUnits);
1451 }
1452 }
1453 PaneSemanticInputEventKind::Cancel { .. } | PaneSemanticInputEventKind::Blur { .. } => {
1454 }
1455 }
1456
1457 Ok(())
1458 }
1459}
1460
1461#[derive(Debug, Clone, PartialEq, Eq)]
1463pub enum PaneSemanticInputEventError {
1464 UnsupportedSchemaVersion { version: u16, expected: u16 },
1465 ZeroSequence,
1466 ZeroPointerId,
1467 ZeroWheelLines,
1468 ZeroResizeUnits,
1469}
1470
1471impl fmt::Display for PaneSemanticInputEventError {
1472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1473 match self {
1474 Self::UnsupportedSchemaVersion { version, expected } => write!(
1475 f,
1476 "unsupported pane semantic input schema version {version} (expected {expected})"
1477 ),
1478 Self::ZeroSequence => write!(f, "semantic pane input event sequence must be non-zero"),
1479 Self::ZeroPointerId => {
1480 write!(
1481 f,
1482 "semantic pane pointer events require non-zero pointer_id"
1483 )
1484 }
1485 Self::ZeroWheelLines => write!(f, "semantic pane wheel nudge must be non-zero"),
1486 Self::ZeroResizeUnits => {
1487 write!(f, "semantic pane keyboard resize units must be non-zero")
1488 }
1489 }
1490 }
1491}
1492
1493impl std::error::Error for PaneSemanticInputEventError {}
1494
1495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1497pub struct PaneSemanticInputTraceMetadata {
1498 #[serde(default = "default_pane_semantic_input_trace_schema_version")]
1499 pub schema_version: u16,
1500 pub seed: u64,
1501 pub start_unix_ms: u64,
1502 #[serde(default)]
1503 pub host: String,
1504 pub checksum: u64,
1505}
1506
1507fn default_pane_semantic_input_trace_schema_version() -> u16 {
1508 PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION
1509}
1510
1511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1513pub struct PaneSemanticInputTrace {
1514 pub metadata: PaneSemanticInputTraceMetadata,
1515 #[serde(default)]
1516 pub events: Vec<PaneSemanticInputEvent>,
1517}
1518
1519impl PaneSemanticInputTrace {
1520 pub fn new(
1522 seed: u64,
1523 start_unix_ms: u64,
1524 host: impl Into<String>,
1525 events: Vec<PaneSemanticInputEvent>,
1526 ) -> Result<Self, PaneSemanticInputTraceError> {
1527 let mut trace = Self {
1528 metadata: PaneSemanticInputTraceMetadata {
1529 schema_version: PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
1530 seed,
1531 start_unix_ms,
1532 host: host.into(),
1533 checksum: 0,
1534 },
1535 events,
1536 };
1537 trace.metadata.checksum = trace.recompute_checksum();
1538 trace.validate()?;
1539 Ok(trace)
1540 }
1541
1542 #[must_use]
1544 pub fn recompute_checksum(&self) -> u64 {
1545 pane_semantic_input_trace_checksum_payload(&self.metadata, &self.events)
1546 }
1547
1548 pub fn validate(&self) -> Result<(), PaneSemanticInputTraceError> {
1550 if self.metadata.schema_version != PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION {
1551 return Err(PaneSemanticInputTraceError::UnsupportedSchemaVersion {
1552 version: self.metadata.schema_version,
1553 expected: PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
1554 });
1555 }
1556 if self.events.is_empty() {
1557 return Err(PaneSemanticInputTraceError::EmptyEvents);
1558 }
1559
1560 let mut previous_sequence = 0_u64;
1561 for (index, event) in self.events.iter().enumerate() {
1562 event
1563 .validate()
1564 .map_err(|source| PaneSemanticInputTraceError::InvalidEvent { index, source })?;
1565
1566 if index > 0 && event.sequence <= previous_sequence {
1567 return Err(PaneSemanticInputTraceError::SequenceOutOfOrder {
1568 index,
1569 previous: previous_sequence,
1570 current: event.sequence,
1571 });
1572 }
1573 previous_sequence = event.sequence;
1574 }
1575
1576 let computed = self.recompute_checksum();
1577 if self.metadata.checksum != computed {
1578 return Err(PaneSemanticInputTraceError::ChecksumMismatch {
1579 recorded: self.metadata.checksum,
1580 computed,
1581 });
1582 }
1583
1584 Ok(())
1585 }
1586
1587 pub fn replay(
1589 &self,
1590 machine: &mut PaneDragResizeMachine,
1591 ) -> Result<PaneSemanticReplayOutcome, PaneSemanticReplayError> {
1592 self.validate()
1593 .map_err(PaneSemanticReplayError::InvalidTrace)?;
1594
1595 let mut transitions = Vec::with_capacity(self.events.len());
1596 for event in &self.events {
1597 let transition = machine
1598 .apply_event(event)
1599 .map_err(PaneSemanticReplayError::Machine)?;
1600 transitions.push(transition);
1601 }
1602
1603 Ok(PaneSemanticReplayOutcome {
1604 trace_checksum: self.metadata.checksum,
1605 transitions,
1606 final_state: machine.state(),
1607 })
1608 }
1609}
1610
1611#[derive(Debug, Clone, PartialEq, Eq)]
1613pub enum PaneSemanticInputTraceError {
1614 UnsupportedSchemaVersion {
1615 version: u16,
1616 expected: u16,
1617 },
1618 EmptyEvents,
1619 SequenceOutOfOrder {
1620 index: usize,
1621 previous: u64,
1622 current: u64,
1623 },
1624 InvalidEvent {
1625 index: usize,
1626 source: PaneSemanticInputEventError,
1627 },
1628 ChecksumMismatch {
1629 recorded: u64,
1630 computed: u64,
1631 },
1632}
1633
1634impl fmt::Display for PaneSemanticInputTraceError {
1635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1636 match self {
1637 Self::UnsupportedSchemaVersion { version, expected } => write!(
1638 f,
1639 "unsupported pane semantic input trace schema version {version} (expected {expected})"
1640 ),
1641 Self::EmptyEvents => write!(
1642 f,
1643 "semantic pane input trace must contain at least one event"
1644 ),
1645 Self::SequenceOutOfOrder {
1646 index,
1647 previous,
1648 current,
1649 } => write!(
1650 f,
1651 "semantic pane input trace sequence out of order at index {index} ({current} <= {previous})"
1652 ),
1653 Self::InvalidEvent { index, source } => {
1654 write!(
1655 f,
1656 "semantic pane input trace contains invalid event at index {index}: {source}"
1657 )
1658 }
1659 Self::ChecksumMismatch { recorded, computed } => write!(
1660 f,
1661 "semantic pane input trace checksum mismatch (recorded={recorded:#x}, computed={computed:#x})"
1662 ),
1663 }
1664 }
1665}
1666
1667impl std::error::Error for PaneSemanticInputTraceError {}
1668
1669#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1671pub struct PaneSemanticReplayOutcome {
1672 pub trace_checksum: u64,
1673 pub transitions: Vec<PaneDragResizeTransition>,
1674 pub final_state: PaneDragResizeState,
1675}
1676
1677#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1679#[serde(rename_all = "snake_case")]
1680pub enum PaneSemanticReplayDiffKind {
1681 TransitionMismatch,
1682 MissingExpectedTransition,
1683 UnexpectedTransition,
1684 FinalStateMismatch,
1685}
1686
1687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1689pub struct PaneSemanticReplayDiffArtifact {
1690 pub kind: PaneSemanticReplayDiffKind,
1691 pub index: Option<usize>,
1692 pub expected_transition: Option<PaneDragResizeTransition>,
1693 pub actual_transition: Option<PaneDragResizeTransition>,
1694 pub expected_final_state: Option<PaneDragResizeState>,
1695 pub actual_final_state: Option<PaneDragResizeState>,
1696}
1697
1698#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1700pub struct PaneSemanticReplayConformanceArtifact {
1701 pub trace_checksum: u64,
1702 pub passed: bool,
1703 pub diffs: Vec<PaneSemanticReplayDiffArtifact>,
1704}
1705
1706impl PaneSemanticReplayConformanceArtifact {
1707 #[must_use]
1709 pub fn compare(
1710 outcome: &PaneSemanticReplayOutcome,
1711 expected_transitions: &[PaneDragResizeTransition],
1712 expected_final_state: PaneDragResizeState,
1713 ) -> Self {
1714 let mut diffs = Vec::new();
1715 let max_len = expected_transitions.len().max(outcome.transitions.len());
1716
1717 for index in 0..max_len {
1718 let expected = expected_transitions.get(index);
1719 let actual = outcome.transitions.get(index);
1720
1721 match (expected, actual) {
1722 (Some(expected_transition), Some(actual_transition))
1723 if expected_transition != actual_transition =>
1724 {
1725 diffs.push(PaneSemanticReplayDiffArtifact {
1726 kind: PaneSemanticReplayDiffKind::TransitionMismatch,
1727 index: Some(index),
1728 expected_transition: Some(expected_transition.clone()),
1729 actual_transition: Some(actual_transition.clone()),
1730 expected_final_state: None,
1731 actual_final_state: None,
1732 });
1733 }
1734 (Some(expected_transition), None) => {
1735 diffs.push(PaneSemanticReplayDiffArtifact {
1736 kind: PaneSemanticReplayDiffKind::MissingExpectedTransition,
1737 index: Some(index),
1738 expected_transition: Some(expected_transition.clone()),
1739 actual_transition: None,
1740 expected_final_state: None,
1741 actual_final_state: None,
1742 });
1743 }
1744 (None, Some(actual_transition)) => {
1745 diffs.push(PaneSemanticReplayDiffArtifact {
1746 kind: PaneSemanticReplayDiffKind::UnexpectedTransition,
1747 index: Some(index),
1748 expected_transition: None,
1749 actual_transition: Some(actual_transition.clone()),
1750 expected_final_state: None,
1751 actual_final_state: None,
1752 });
1753 }
1754 (Some(_), Some(_)) | (None, None) => {}
1755 }
1756 }
1757
1758 if outcome.final_state != expected_final_state {
1759 diffs.push(PaneSemanticReplayDiffArtifact {
1760 kind: PaneSemanticReplayDiffKind::FinalStateMismatch,
1761 index: None,
1762 expected_transition: None,
1763 actual_transition: None,
1764 expected_final_state: Some(expected_final_state),
1765 actual_final_state: Some(outcome.final_state),
1766 });
1767 }
1768
1769 Self {
1770 trace_checksum: outcome.trace_checksum,
1771 passed: diffs.is_empty(),
1772 diffs,
1773 }
1774 }
1775}
1776
1777#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1779pub struct PaneSemanticReplayFixture {
1780 pub trace: PaneSemanticInputTrace,
1781 #[serde(default)]
1782 pub expected_transitions: Vec<PaneDragResizeTransition>,
1783 pub expected_final_state: PaneDragResizeState,
1784}
1785
1786impl PaneSemanticReplayFixture {
1787 pub fn run(
1789 &self,
1790 machine: &mut PaneDragResizeMachine,
1791 ) -> Result<PaneSemanticReplayConformanceArtifact, PaneSemanticReplayError> {
1792 let outcome = self.trace.replay(machine)?;
1793 Ok(PaneSemanticReplayConformanceArtifact::compare(
1794 &outcome,
1795 &self.expected_transitions,
1796 self.expected_final_state,
1797 ))
1798 }
1799}
1800
1801#[derive(Debug, Clone, PartialEq, Eq)]
1803pub enum PaneSemanticReplayError {
1804 InvalidTrace(PaneSemanticInputTraceError),
1805 Machine(PaneDragResizeMachineError),
1806}
1807
1808impl fmt::Display for PaneSemanticReplayError {
1809 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1810 match self {
1811 Self::InvalidTrace(source) => write!(f, "invalid semantic replay trace: {source}"),
1812 Self::Machine(source) => write!(f, "pane drag/resize machine replay failed: {source}"),
1813 }
1814 }
1815}
1816
1817impl std::error::Error for PaneSemanticReplayError {}
1818
1819fn pane_semantic_input_trace_checksum_payload(
1820 metadata: &PaneSemanticInputTraceMetadata,
1821 events: &[PaneSemanticInputEvent],
1822) -> u64 {
1823 const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
1824 const PRIME: u64 = 0x0000_0001_0000_01b3;
1825
1826 fn mix(hash: &mut u64, byte: u8) {
1827 *hash ^= u64::from(byte);
1828 *hash = hash.wrapping_mul(PRIME);
1829 }
1830
1831 fn mix_bytes(hash: &mut u64, bytes: &[u8]) {
1832 for byte in bytes {
1833 mix(hash, *byte);
1834 }
1835 }
1836
1837 fn mix_u16(hash: &mut u64, value: u16) {
1838 mix_bytes(hash, &value.to_le_bytes());
1839 }
1840
1841 fn mix_u32(hash: &mut u64, value: u32) {
1842 mix_bytes(hash, &value.to_le_bytes());
1843 }
1844
1845 fn mix_i32(hash: &mut u64, value: i32) {
1846 mix_bytes(hash, &value.to_le_bytes());
1847 }
1848
1849 fn mix_u64(hash: &mut u64, value: u64) {
1850 mix_bytes(hash, &value.to_le_bytes());
1851 }
1852
1853 fn mix_i16(hash: &mut u64, value: i16) {
1854 mix_bytes(hash, &value.to_le_bytes());
1855 }
1856
1857 fn mix_bool(hash: &mut u64, value: bool) {
1858 mix(hash, u8::from(value));
1859 }
1860
1861 fn mix_str(hash: &mut u64, value: &str) {
1862 mix_u64(hash, value.len() as u64);
1863 mix_bytes(hash, value.as_bytes());
1864 }
1865
1866 fn mix_extensions(hash: &mut u64, extensions: &BTreeMap<String, String>) {
1867 mix_u64(hash, extensions.len() as u64);
1868 for (key, value) in extensions {
1869 mix_str(hash, key);
1870 mix_str(hash, value);
1871 }
1872 }
1873
1874 fn mix_target(hash: &mut u64, target: PaneResizeTarget) {
1875 mix_u64(hash, target.split_id.get());
1876 let axis = match target.axis {
1877 SplitAxis::Horizontal => 1,
1878 SplitAxis::Vertical => 2,
1879 };
1880 mix(hash, axis);
1881 }
1882
1883 fn mix_position(hash: &mut u64, position: PanePointerPosition) {
1884 mix_i32(hash, position.x);
1885 mix_i32(hash, position.y);
1886 }
1887
1888 fn mix_optional_target(hash: &mut u64, target: Option<PaneResizeTarget>) {
1889 match target {
1890 Some(target) => {
1891 mix(hash, 1);
1892 mix_target(hash, target);
1893 }
1894 None => mix(hash, 0),
1895 }
1896 }
1897
1898 fn mix_pointer_button(hash: &mut u64, button: PanePointerButton) {
1899 let value = match button {
1900 PanePointerButton::Primary => 1,
1901 PanePointerButton::Secondary => 2,
1902 PanePointerButton::Middle => 3,
1903 };
1904 mix(hash, value);
1905 }
1906
1907 fn mix_resize_direction(hash: &mut u64, direction: PaneResizeDirection) {
1908 let value = match direction {
1909 PaneResizeDirection::Increase => 1,
1910 PaneResizeDirection::Decrease => 2,
1911 };
1912 mix(hash, value);
1913 }
1914
1915 fn mix_cancel_reason(hash: &mut u64, reason: PaneCancelReason) {
1916 let value = match reason {
1917 PaneCancelReason::EscapeKey => 1,
1918 PaneCancelReason::PointerCancel => 2,
1919 PaneCancelReason::FocusLost => 3,
1920 PaneCancelReason::Blur => 4,
1921 PaneCancelReason::Programmatic => 5,
1922 PaneCancelReason::ContextLost => 6,
1923 PaneCancelReason::RenderStalled => 7,
1924 };
1925 mix(hash, value);
1926 }
1927
1928 let mut hash = OFFSET_BASIS;
1929 mix_u16(&mut hash, metadata.schema_version);
1930 mix_u64(&mut hash, metadata.seed);
1931 mix_u64(&mut hash, metadata.start_unix_ms);
1932 mix_str(&mut hash, &metadata.host);
1933 mix_u64(&mut hash, events.len() as u64);
1934
1935 for event in events {
1936 mix_u16(&mut hash, event.schema_version);
1937 mix_u64(&mut hash, event.sequence);
1938 mix_bool(&mut hash, event.modifiers.shift);
1939 mix_bool(&mut hash, event.modifiers.alt);
1940 mix_bool(&mut hash, event.modifiers.ctrl);
1941 mix_bool(&mut hash, event.modifiers.meta);
1942 mix_extensions(&mut hash, &event.extensions);
1943
1944 match event.kind {
1945 PaneSemanticInputEventKind::PointerDown {
1946 target,
1947 pointer_id,
1948 button,
1949 position,
1950 } => {
1951 mix(&mut hash, 1);
1952 mix_target(&mut hash, target);
1953 mix_u32(&mut hash, pointer_id);
1954 mix_pointer_button(&mut hash, button);
1955 mix_position(&mut hash, position);
1956 }
1957 PaneSemanticInputEventKind::PointerMove {
1958 target,
1959 pointer_id,
1960 position,
1961 delta_x,
1962 delta_y,
1963 } => {
1964 mix(&mut hash, 2);
1965 mix_target(&mut hash, target);
1966 mix_u32(&mut hash, pointer_id);
1967 mix_position(&mut hash, position);
1968 mix_i32(&mut hash, delta_x);
1969 mix_i32(&mut hash, delta_y);
1970 }
1971 PaneSemanticInputEventKind::PointerUp {
1972 target,
1973 pointer_id,
1974 button,
1975 position,
1976 } => {
1977 mix(&mut hash, 3);
1978 mix_target(&mut hash, target);
1979 mix_u32(&mut hash, pointer_id);
1980 mix_pointer_button(&mut hash, button);
1981 mix_position(&mut hash, position);
1982 }
1983 PaneSemanticInputEventKind::WheelNudge { target, lines } => {
1984 mix(&mut hash, 4);
1985 mix_target(&mut hash, target);
1986 mix_i16(&mut hash, lines);
1987 }
1988 PaneSemanticInputEventKind::KeyboardResize {
1989 target,
1990 direction,
1991 units,
1992 } => {
1993 mix(&mut hash, 5);
1994 mix_target(&mut hash, target);
1995 mix_resize_direction(&mut hash, direction);
1996 mix_u16(&mut hash, units);
1997 }
1998 PaneSemanticInputEventKind::Cancel { target, reason } => {
1999 mix(&mut hash, 6);
2000 mix_optional_target(&mut hash, target);
2001 mix_cancel_reason(&mut hash, reason);
2002 }
2003 PaneSemanticInputEventKind::Blur { target } => {
2004 mix(&mut hash, 7);
2005 mix_optional_target(&mut hash, target);
2006 }
2007 }
2008 }
2009
2010 hash
2011}
2012
2013#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2015pub struct PaneScaleFactor {
2016 numerator: u32,
2017 denominator: u32,
2018}
2019
2020impl PaneScaleFactor {
2021 pub const ONE: Self = Self {
2023 numerator: 1,
2024 denominator: 1,
2025 };
2026
2027 pub fn new(numerator: u32, denominator: u32) -> Result<Self, PaneCoordinateNormalizationError> {
2029 if numerator == 0 || denominator == 0 {
2030 return Err(PaneCoordinateNormalizationError::InvalidScaleFactor {
2031 field: "scale_factor",
2032 numerator,
2033 denominator,
2034 });
2035 }
2036 let gcd = gcd_u32(numerator, denominator);
2037 Ok(Self {
2038 numerator: numerator / gcd,
2039 denominator: denominator / gcd,
2040 })
2041 }
2042
2043 fn validate(self, field: &'static str) -> Result<(), PaneCoordinateNormalizationError> {
2044 if self.numerator == 0 || self.denominator == 0 {
2045 return Err(PaneCoordinateNormalizationError::InvalidScaleFactor {
2046 field,
2047 numerator: self.numerator,
2048 denominator: self.denominator,
2049 });
2050 }
2051 Ok(())
2052 }
2053
2054 #[must_use]
2055 pub const fn numerator(self) -> u32 {
2056 if self.numerator == 0 {
2057 1
2058 } else {
2059 self.numerator
2060 }
2061 }
2062
2063 #[must_use]
2064 pub const fn denominator(self) -> u32 {
2065 if self.denominator == 0 {
2066 1
2067 } else {
2068 self.denominator
2069 }
2070 }
2071}
2072
2073impl Default for PaneScaleFactor {
2074 fn default() -> Self {
2075 Self::ONE
2076 }
2077}
2078
2079#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
2081#[serde(rename_all = "snake_case")]
2082pub enum PaneCoordinateRoundingPolicy {
2083 #[default]
2085 TowardNegativeInfinity,
2086 NearestHalfTowardNegativeInfinity,
2088}
2089
2090#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2092#[serde(tag = "source", rename_all = "snake_case")]
2093pub enum PaneInputCoordinate {
2094 CssPixels { position: PanePointerPosition },
2096 DevicePixels { position: PanePointerPosition },
2098 Cell { position: PanePointerPosition },
2100}
2101
2102#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2104pub struct PaneNormalizedCoordinate {
2105 pub global_cell: PanePointerPosition,
2107 pub local_cell: PanePointerPosition,
2109 pub local_css: PanePointerPosition,
2111}
2112
2113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2115pub struct PaneCoordinateNormalizer {
2116 pub viewport_origin_css: PanePointerPosition,
2117 pub viewport_origin_cells: PanePointerPosition,
2118 pub cell_width_css: u16,
2119 pub cell_height_css: u16,
2120 pub dpr: PaneScaleFactor,
2121 pub zoom: PaneScaleFactor,
2122 #[serde(default)]
2123 pub rounding: PaneCoordinateRoundingPolicy,
2124}
2125
2126impl PaneCoordinateNormalizer {
2127 pub fn new(
2129 viewport_origin_css: PanePointerPosition,
2130 viewport_origin_cells: PanePointerPosition,
2131 cell_width_css: u16,
2132 cell_height_css: u16,
2133 dpr: PaneScaleFactor,
2134 zoom: PaneScaleFactor,
2135 rounding: PaneCoordinateRoundingPolicy,
2136 ) -> Result<Self, PaneCoordinateNormalizationError> {
2137 if cell_width_css == 0 || cell_height_css == 0 {
2138 return Err(PaneCoordinateNormalizationError::InvalidCellSize {
2139 width: cell_width_css,
2140 height: cell_height_css,
2141 });
2142 }
2143 dpr.validate("dpr")?;
2144 zoom.validate("zoom")?;
2145
2146 Ok(Self {
2147 viewport_origin_css,
2148 viewport_origin_cells,
2149 cell_width_css,
2150 cell_height_css,
2151 dpr,
2152 zoom,
2153 rounding,
2154 })
2155 }
2156
2157 pub fn normalize(
2159 &self,
2160 input: PaneInputCoordinate,
2161 ) -> Result<PaneNormalizedCoordinate, PaneCoordinateNormalizationError> {
2162 let (local_css_x, local_css_y) = match input {
2163 PaneInputCoordinate::CssPixels { position } => (
2164 i64::from(position.x) - i64::from(self.viewport_origin_css.x),
2165 i64::from(position.y) - i64::from(self.viewport_origin_css.y),
2166 ),
2167 PaneInputCoordinate::DevicePixels { position } => {
2168 let css_x = scale_div_round(
2169 i64::from(position.x),
2170 i64::from(self.dpr.denominator()),
2171 i64::from(self.dpr.numerator()),
2172 self.rounding,
2173 )?;
2174 let css_y = scale_div_round(
2175 i64::from(position.y),
2176 i64::from(self.dpr.denominator()),
2177 i64::from(self.dpr.numerator()),
2178 self.rounding,
2179 )?;
2180 (
2181 css_x - i64::from(self.viewport_origin_css.x),
2182 css_y - i64::from(self.viewport_origin_css.y),
2183 )
2184 }
2185 PaneInputCoordinate::Cell { position } => {
2186 let local_css_x = i64::from(position.x)
2187 .checked_mul(i64::from(self.cell_width_css))
2188 .ok_or(PaneCoordinateNormalizationError::CoordinateOverflow)?;
2189 let local_css_y = i64::from(position.y)
2190 .checked_mul(i64::from(self.cell_height_css))
2191 .ok_or(PaneCoordinateNormalizationError::CoordinateOverflow)?;
2192 let global_cell_x = i64::from(position.x) + i64::from(self.viewport_origin_cells.x);
2193 let global_cell_y = i64::from(position.y) + i64::from(self.viewport_origin_cells.y);
2194
2195 return Ok(PaneNormalizedCoordinate {
2196 global_cell: PanePointerPosition::new(
2197 to_i32(global_cell_x)?,
2198 to_i32(global_cell_y)?,
2199 ),
2200 local_cell: position,
2201 local_css: PanePointerPosition::new(to_i32(local_css_x)?, to_i32(local_css_y)?),
2202 });
2203 }
2204 };
2205
2206 let unzoomed_css_x = scale_div_round(
2207 local_css_x,
2208 i64::from(self.zoom.denominator()),
2209 i64::from(self.zoom.numerator()),
2210 self.rounding,
2211 )?;
2212 let unzoomed_css_y = scale_div_round(
2213 local_css_y,
2214 i64::from(self.zoom.denominator()),
2215 i64::from(self.zoom.numerator()),
2216 self.rounding,
2217 )?;
2218
2219 let local_cell_x = div_round(
2220 unzoomed_css_x,
2221 i64::from(self.cell_width_css),
2222 self.rounding,
2223 )?;
2224 let local_cell_y = div_round(
2225 unzoomed_css_y,
2226 i64::from(self.cell_height_css),
2227 self.rounding,
2228 )?;
2229
2230 let global_cell_x = local_cell_x + i64::from(self.viewport_origin_cells.x);
2231 let global_cell_y = local_cell_y + i64::from(self.viewport_origin_cells.y);
2232
2233 Ok(PaneNormalizedCoordinate {
2234 global_cell: PanePointerPosition::new(to_i32(global_cell_x)?, to_i32(global_cell_y)?),
2235 local_cell: PanePointerPosition::new(to_i32(local_cell_x)?, to_i32(local_cell_y)?),
2236 local_css: PanePointerPosition::new(to_i32(unzoomed_css_x)?, to_i32(unzoomed_css_y)?),
2237 })
2238 }
2239}
2240
2241#[derive(Debug, Clone, PartialEq, Eq)]
2243pub enum PaneCoordinateNormalizationError {
2244 InvalidCellSize {
2245 width: u16,
2246 height: u16,
2247 },
2248 InvalidScaleFactor {
2249 field: &'static str,
2250 numerator: u32,
2251 denominator: u32,
2252 },
2253 CoordinateOverflow,
2254}
2255
2256impl fmt::Display for PaneCoordinateNormalizationError {
2257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2258 match self {
2259 Self::InvalidCellSize { width, height } => {
2260 write!(
2261 f,
2262 "invalid pane cell dimensions width={width} height={height} (must be > 0)"
2263 )
2264 }
2265 Self::InvalidScaleFactor {
2266 field,
2267 numerator,
2268 denominator,
2269 } => {
2270 write!(
2271 f,
2272 "invalid pane scale factor for {field}: {numerator}/{denominator} (must be > 0)"
2273 )
2274 }
2275 Self::CoordinateOverflow => {
2276 write!(f, "coordinate conversion overflowed representable range")
2277 }
2278 }
2279 }
2280}
2281
2282impl std::error::Error for PaneCoordinateNormalizationError {}
2283
2284fn scale_div_round(
2285 value: i64,
2286 numerator: i64,
2287 denominator: i64,
2288 rounding: PaneCoordinateRoundingPolicy,
2289) -> Result<i64, PaneCoordinateNormalizationError> {
2290 if denominator <= 0 {
2291 return Err(PaneCoordinateNormalizationError::CoordinateOverflow);
2292 }
2293
2294 let scaled = (value as i128) * (numerator as i128);
2295 let den = denominator as i128;
2296
2297 let floor = scaled.div_euclid(den);
2298 let remainder = scaled.rem_euclid(den);
2299
2300 let mut result = floor;
2301
2302 if remainder != 0 {
2303 match rounding {
2304 PaneCoordinateRoundingPolicy::TowardNegativeInfinity => {}
2305 PaneCoordinateRoundingPolicy::NearestHalfTowardNegativeInfinity => {
2306 let twice_remainder = remainder * 2;
2307 if twice_remainder > den {
2308 result += 1;
2309 }
2310 }
2313 }
2314 }
2315
2316 result
2317 .try_into()
2318 .map_err(|_| PaneCoordinateNormalizationError::CoordinateOverflow)
2319}
2320
2321fn div_round(
2322 value: i64,
2323 denominator: i64,
2324 rounding: PaneCoordinateRoundingPolicy,
2325) -> Result<i64, PaneCoordinateNormalizationError> {
2326 scale_div_round(value, 1, denominator, rounding)
2327}
2328
2329fn to_i32(value: i64) -> Result<i32, PaneCoordinateNormalizationError> {
2330 i32::try_from(value).map_err(|_| PaneCoordinateNormalizationError::CoordinateOverflow)
2331}
2332
2333pub const PANE_DRAG_RESIZE_DEFAULT_THRESHOLD: u16 = 2;
2336
2337pub const PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS: u16 = 2;
2340
2341pub const PANE_SNAP_DEFAULT_STEP_BPS: u16 = 500;
2343
2344pub const PANE_SNAP_DEFAULT_HYSTERESIS_BPS: u16 = 125;
2346
2347#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2349#[serde(rename_all = "snake_case")]
2350pub enum PanePrecisionMode {
2351 Normal,
2352 Fine,
2353 Coarse,
2354}
2355
2356#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2358pub struct PanePrecisionPolicy {
2359 pub mode: PanePrecisionMode,
2360 pub axis_lock: Option<SplitAxis>,
2361 pub scale: PaneScaleFactor,
2362}
2363
2364impl PanePrecisionPolicy {
2365 #[must_use]
2367 pub fn from_modifiers(modifiers: PaneModifierSnapshot, target_axis: SplitAxis) -> Self {
2368 let mode = if modifiers.alt {
2369 PanePrecisionMode::Fine
2370 } else if modifiers.ctrl {
2371 PanePrecisionMode::Coarse
2372 } else {
2373 PanePrecisionMode::Normal
2374 };
2375 let axis_lock = modifiers.shift.then_some(target_axis);
2376 let scale = match mode {
2377 PanePrecisionMode::Normal => PaneScaleFactor::ONE,
2378 PanePrecisionMode::Fine => PaneScaleFactor {
2379 numerator: 1,
2380 denominator: 2,
2381 },
2382 PanePrecisionMode::Coarse => PaneScaleFactor {
2383 numerator: 2,
2384 denominator: 1,
2385 },
2386 };
2387 Self {
2388 mode,
2389 axis_lock,
2390 scale,
2391 }
2392 }
2393
2394 pub fn apply_delta(
2396 &self,
2397 raw_delta_x: i32,
2398 raw_delta_y: i32,
2399 ) -> Result<(i32, i32), PaneInteractionPolicyError> {
2400 let (locked_x, locked_y) = match self.axis_lock {
2401 Some(SplitAxis::Horizontal) => (raw_delta_x, 0),
2402 Some(SplitAxis::Vertical) => (0, raw_delta_y),
2403 None => (raw_delta_x, raw_delta_y),
2404 };
2405
2406 let scaled_x = scale_delta_by_factor(locked_x, self.scale)?;
2407 let scaled_y = scale_delta_by_factor(locked_y, self.scale)?;
2408 Ok((scaled_x, scaled_y))
2409 }
2410}
2411
2412#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2414pub struct PaneSnapTuning {
2415 pub step_bps: u16,
2416 pub hysteresis_bps: u16,
2417}
2418
2419impl PaneSnapTuning {
2420 pub fn new(step_bps: u16, hysteresis_bps: u16) -> Result<Self, PaneInteractionPolicyError> {
2421 let tuning = Self {
2422 step_bps,
2423 hysteresis_bps,
2424 };
2425 tuning.validate()?;
2426 Ok(tuning)
2427 }
2428
2429 pub fn validate(self) -> Result<(), PaneInteractionPolicyError> {
2430 if self.step_bps == 0 || self.step_bps > 10_000 {
2431 return Err(PaneInteractionPolicyError::InvalidSnapTuning {
2432 step_bps: self.step_bps,
2433 hysteresis_bps: self.hysteresis_bps,
2434 });
2435 }
2436 Ok(())
2437 }
2438
2439 #[must_use]
2441 pub fn decide(self, ratio_bps: u16, previous_snap: Option<u16>) -> PaneSnapDecision {
2442 let step = u32::from(self.step_bps).max(1);
2443 let ratio = u32::from(ratio_bps).min(10_000);
2444 let low = ((ratio / step) * step).min(10_000);
2445 let high = (low + step).min(10_000);
2446
2447 let distance_low = ratio.abs_diff(low);
2448 let distance_high = ratio.abs_diff(high);
2449
2450 let (nearest, nearest_distance) = if distance_low <= distance_high {
2451 (low as u16, distance_low as u16)
2452 } else {
2453 (high as u16, distance_high as u16)
2454 };
2455
2456 if let Some(previous) = previous_snap {
2457 let distance_previous = ratio.abs_diff(u32::from(previous));
2458 if distance_previous <= u32::from(self.hysteresis_bps) {
2459 return PaneSnapDecision {
2460 input_ratio_bps: ratio_bps,
2461 snapped_ratio_bps: Some(previous),
2462 nearest_ratio_bps: nearest,
2463 nearest_distance_bps: nearest_distance,
2464 reason: PaneSnapReason::RetainedPrevious,
2465 };
2466 }
2467 }
2468
2469 if nearest_distance <= self.hysteresis_bps {
2470 PaneSnapDecision {
2471 input_ratio_bps: ratio_bps,
2472 snapped_ratio_bps: Some(nearest),
2473 nearest_ratio_bps: nearest,
2474 nearest_distance_bps: nearest_distance,
2475 reason: PaneSnapReason::SnappedNearest,
2476 }
2477 } else {
2478 PaneSnapDecision {
2479 input_ratio_bps: ratio_bps,
2480 snapped_ratio_bps: None,
2481 nearest_ratio_bps: nearest,
2482 nearest_distance_bps: nearest_distance,
2483 reason: PaneSnapReason::UnsnapOutsideWindow,
2484 }
2485 }
2486 }
2487}
2488
2489impl Default for PaneSnapTuning {
2490 fn default() -> Self {
2491 Self {
2492 step_bps: PANE_SNAP_DEFAULT_STEP_BPS,
2493 hysteresis_bps: PANE_SNAP_DEFAULT_HYSTERESIS_BPS,
2494 }
2495 }
2496}
2497
2498#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2500pub struct PaneDragBehaviorTuning {
2501 pub activation_threshold: u16,
2502 pub update_hysteresis: u16,
2503 pub snap: PaneSnapTuning,
2504}
2505
2506impl PaneDragBehaviorTuning {
2507 pub fn new(
2508 activation_threshold: u16,
2509 update_hysteresis: u16,
2510 snap: PaneSnapTuning,
2511 ) -> Result<Self, PaneInteractionPolicyError> {
2512 if activation_threshold == 0 {
2513 return Err(PaneInteractionPolicyError::InvalidThreshold {
2514 field: "activation_threshold",
2515 value: activation_threshold,
2516 });
2517 }
2518 if update_hysteresis == 0 {
2519 return Err(PaneInteractionPolicyError::InvalidThreshold {
2520 field: "update_hysteresis",
2521 value: update_hysteresis,
2522 });
2523 }
2524 snap.validate()?;
2525 Ok(Self {
2526 activation_threshold,
2527 update_hysteresis,
2528 snap,
2529 })
2530 }
2531
2532 #[must_use]
2533 pub fn should_start_drag(
2534 self,
2535 origin: PanePointerPosition,
2536 current: PanePointerPosition,
2537 ) -> bool {
2538 crossed_drag_threshold(origin, current, self.activation_threshold)
2539 }
2540
2541 #[must_use]
2542 pub fn should_emit_drag_update(
2543 self,
2544 previous: PanePointerPosition,
2545 current: PanePointerPosition,
2546 ) -> bool {
2547 crossed_drag_threshold(previous, current, self.update_hysteresis)
2548 }
2549}
2550
2551impl Default for PaneDragBehaviorTuning {
2552 fn default() -> Self {
2553 Self {
2554 activation_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
2555 update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
2556 snap: PaneSnapTuning::default(),
2557 }
2558 }
2559}
2560
2561#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2563#[serde(rename_all = "snake_case")]
2564pub enum PaneSnapReason {
2565 RetainedPrevious,
2566 SnappedNearest,
2567 UnsnapOutsideWindow,
2568}
2569
2570#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2572pub struct PaneSnapDecision {
2573 pub input_ratio_bps: u16,
2574 pub snapped_ratio_bps: Option<u16>,
2575 pub nearest_ratio_bps: u16,
2576 pub nearest_distance_bps: u16,
2577 pub reason: PaneSnapReason,
2578}
2579
2580#[derive(Debug, Clone, PartialEq, Eq)]
2582pub enum PaneInteractionPolicyError {
2583 InvalidThreshold { field: &'static str, value: u16 },
2584 InvalidSnapTuning { step_bps: u16, hysteresis_bps: u16 },
2585 DeltaOverflow,
2586}
2587
2588impl fmt::Display for PaneInteractionPolicyError {
2589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2590 match self {
2591 Self::InvalidThreshold { field, value } => {
2592 write!(f, "invalid {field} value {value} (must be > 0)")
2593 }
2594 Self::InvalidSnapTuning {
2595 step_bps,
2596 hysteresis_bps,
2597 } => {
2598 write!(
2599 f,
2600 "invalid snap tuning step_bps={step_bps} hysteresis_bps={hysteresis_bps}"
2601 )
2602 }
2603 Self::DeltaOverflow => write!(f, "delta scaling overflow"),
2604 }
2605 }
2606}
2607
2608impl std::error::Error for PaneInteractionPolicyError {}
2609
2610fn scale_delta_by_factor(
2611 delta: i32,
2612 factor: PaneScaleFactor,
2613) -> Result<i32, PaneInteractionPolicyError> {
2614 let scaled = i64::from(delta)
2615 .checked_mul(i64::from(factor.numerator()))
2616 .ok_or(PaneInteractionPolicyError::DeltaOverflow)?;
2617 let normalized = scaled / i64::from(factor.denominator());
2618 i32::try_from(normalized).map_err(|_| PaneInteractionPolicyError::DeltaOverflow)
2619}
2620
2621#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2628#[serde(tag = "state", rename_all = "snake_case")]
2629pub enum PaneDragResizeState {
2630 Idle,
2631 Armed {
2632 target: PaneResizeTarget,
2633 pointer_id: u32,
2634 origin: PanePointerPosition,
2635 current: PanePointerPosition,
2636 started_sequence: u64,
2637 },
2638 Dragging {
2639 target: PaneResizeTarget,
2640 pointer_id: u32,
2641 origin: PanePointerPosition,
2642 current: PanePointerPosition,
2643 started_sequence: u64,
2644 drag_started_sequence: u64,
2645 },
2646}
2647
2648#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2650#[serde(rename_all = "snake_case")]
2651pub enum PaneDragResizeNoopReason {
2652 IdleWithoutActiveDrag,
2653 ActiveDragAlreadyInProgress,
2654 PointerMismatch,
2655 TargetMismatch,
2656 ActiveStateDisallowsDiscreteInput,
2657 ThresholdNotReached,
2658 BelowHysteresis,
2659}
2660
2661#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2663#[serde(tag = "effect", rename_all = "snake_case")]
2664pub enum PaneDragResizeEffect {
2665 Armed {
2666 target: PaneResizeTarget,
2667 pointer_id: u32,
2668 origin: PanePointerPosition,
2669 },
2670 DragStarted {
2671 target: PaneResizeTarget,
2672 pointer_id: u32,
2673 origin: PanePointerPosition,
2674 current: PanePointerPosition,
2675 total_delta_x: i32,
2676 total_delta_y: i32,
2677 },
2678 DragUpdated {
2679 target: PaneResizeTarget,
2680 pointer_id: u32,
2681 previous: PanePointerPosition,
2682 current: PanePointerPosition,
2683 delta_x: i32,
2684 delta_y: i32,
2685 total_delta_x: i32,
2686 total_delta_y: i32,
2687 },
2688 Committed {
2689 target: PaneResizeTarget,
2690 pointer_id: u32,
2691 origin: PanePointerPosition,
2692 end: PanePointerPosition,
2693 total_delta_x: i32,
2694 total_delta_y: i32,
2695 },
2696 Canceled {
2697 target: Option<PaneResizeTarget>,
2698 pointer_id: Option<u32>,
2699 reason: PaneCancelReason,
2700 },
2701 KeyboardApplied {
2702 target: PaneResizeTarget,
2703 direction: PaneResizeDirection,
2704 units: u16,
2705 },
2706 WheelApplied {
2707 target: PaneResizeTarget,
2708 lines: i16,
2709 },
2710 Noop {
2711 reason: PaneDragResizeNoopReason,
2712 },
2713}
2714
2715#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2717pub struct PaneDragResizeTransition {
2718 pub transition_id: u64,
2719 pub sequence: u64,
2720 pub from: PaneDragResizeState,
2721 pub to: PaneDragResizeState,
2722 pub effect: PaneDragResizeEffect,
2723}
2724
2725#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2727pub struct PaneDragResizeMachine {
2728 state: PaneDragResizeState,
2729 drag_threshold: u16,
2730 update_hysteresis: u16,
2731 transition_counter: u64,
2732}
2733
2734impl Default for PaneDragResizeMachine {
2735 fn default() -> Self {
2736 Self {
2737 state: PaneDragResizeState::Idle,
2738 drag_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
2739 update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
2740 transition_counter: 0,
2741 }
2742 }
2743}
2744
2745impl PaneDragResizeMachine {
2746 pub fn new(drag_threshold: u16) -> Result<Self, PaneDragResizeMachineError> {
2748 Self::new_with_hysteresis(drag_threshold, PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS)
2749 }
2750
2751 pub fn new_with_hysteresis(
2754 drag_threshold: u16,
2755 update_hysteresis: u16,
2756 ) -> Result<Self, PaneDragResizeMachineError> {
2757 if drag_threshold == 0 {
2758 return Err(PaneDragResizeMachineError::InvalidDragThreshold {
2759 threshold: drag_threshold,
2760 });
2761 }
2762 if update_hysteresis == 0 {
2763 return Err(PaneDragResizeMachineError::InvalidUpdateHysteresis {
2764 hysteresis: update_hysteresis,
2765 });
2766 }
2767 Ok(Self {
2768 state: PaneDragResizeState::Idle,
2769 drag_threshold,
2770 update_hysteresis,
2771 transition_counter: 0,
2772 })
2773 }
2774
2775 #[must_use]
2777 pub const fn state(&self) -> PaneDragResizeState {
2778 self.state
2779 }
2780
2781 #[must_use]
2783 pub const fn drag_threshold(&self) -> u16 {
2784 self.drag_threshold
2785 }
2786
2787 #[must_use]
2789 pub const fn update_hysteresis(&self) -> u16 {
2790 self.update_hysteresis
2791 }
2792
2793 #[must_use]
2795 pub const fn is_active(&self) -> bool {
2796 !matches!(self.state, PaneDragResizeState::Idle)
2797 }
2798
2799 pub fn force_cancel(&mut self) -> Option<PaneDragResizeTransition> {
2809 let from = self.state;
2810 match from {
2811 PaneDragResizeState::Idle => None,
2812 PaneDragResizeState::Armed {
2813 target, pointer_id, ..
2814 }
2815 | PaneDragResizeState::Dragging {
2816 target, pointer_id, ..
2817 } => {
2818 self.state = PaneDragResizeState::Idle;
2819 self.transition_counter = self.transition_counter.saturating_add(1);
2820 Some(PaneDragResizeTransition {
2821 transition_id: self.transition_counter,
2822 sequence: 0,
2823 from,
2824 to: PaneDragResizeState::Idle,
2825 effect: PaneDragResizeEffect::Canceled {
2826 target: Some(target),
2827 pointer_id: Some(pointer_id),
2828 reason: PaneCancelReason::Programmatic,
2829 },
2830 })
2831 }
2832 }
2833 }
2834
2835 pub fn apply_event(
2838 &mut self,
2839 event: &PaneSemanticInputEvent,
2840 ) -> Result<PaneDragResizeTransition, PaneDragResizeMachineError> {
2841 event
2842 .validate()
2843 .map_err(PaneDragResizeMachineError::InvalidEvent)?;
2844
2845 let from = self.state;
2846 let effect = match (self.state, &event.kind) {
2847 (
2848 PaneDragResizeState::Idle,
2849 PaneSemanticInputEventKind::PointerDown {
2850 target,
2851 pointer_id,
2852 position,
2853 ..
2854 },
2855 ) => {
2856 self.state = PaneDragResizeState::Armed {
2857 target: *target,
2858 pointer_id: *pointer_id,
2859 origin: *position,
2860 current: *position,
2861 started_sequence: event.sequence,
2862 };
2863 PaneDragResizeEffect::Armed {
2864 target: *target,
2865 pointer_id: *pointer_id,
2866 origin: *position,
2867 }
2868 }
2869 (
2870 PaneDragResizeState::Idle,
2871 PaneSemanticInputEventKind::KeyboardResize {
2872 target,
2873 direction,
2874 units,
2875 },
2876 ) => PaneDragResizeEffect::KeyboardApplied {
2877 target: *target,
2878 direction: *direction,
2879 units: *units,
2880 },
2881 (
2882 PaneDragResizeState::Idle,
2883 PaneSemanticInputEventKind::WheelNudge { target, lines },
2884 ) => PaneDragResizeEffect::WheelApplied {
2885 target: *target,
2886 lines: *lines,
2887 },
2888 (PaneDragResizeState::Idle, _) => PaneDragResizeEffect::Noop {
2889 reason: PaneDragResizeNoopReason::IdleWithoutActiveDrag,
2890 },
2891 (
2892 PaneDragResizeState::Armed {
2893 target,
2894 pointer_id,
2895 origin,
2896 current: _,
2897 started_sequence,
2898 },
2899 PaneSemanticInputEventKind::PointerMove {
2900 target: incoming_target,
2901 pointer_id: incoming_pointer_id,
2902 position,
2903 ..
2904 },
2905 ) => {
2906 if *incoming_pointer_id != pointer_id {
2907 PaneDragResizeEffect::Noop {
2908 reason: PaneDragResizeNoopReason::PointerMismatch,
2909 }
2910 } else if *incoming_target != target {
2911 PaneDragResizeEffect::Noop {
2912 reason: PaneDragResizeNoopReason::TargetMismatch,
2913 }
2914 } else {
2915 self.state = PaneDragResizeState::Armed {
2916 target,
2917 pointer_id,
2918 origin,
2919 current: *position,
2920 started_sequence,
2921 };
2922 if crossed_drag_threshold(origin, *position, self.drag_threshold) {
2923 self.state = PaneDragResizeState::Dragging {
2924 target,
2925 pointer_id,
2926 origin,
2927 current: *position,
2928 started_sequence,
2929 drag_started_sequence: event.sequence,
2930 };
2931 let (total_delta_x, total_delta_y) = delta(origin, *position);
2932 PaneDragResizeEffect::DragStarted {
2933 target,
2934 pointer_id,
2935 origin,
2936 current: *position,
2937 total_delta_x,
2938 total_delta_y,
2939 }
2940 } else {
2941 PaneDragResizeEffect::Noop {
2942 reason: PaneDragResizeNoopReason::ThresholdNotReached,
2943 }
2944 }
2945 }
2946 }
2947 (
2948 PaneDragResizeState::Armed {
2949 target,
2950 pointer_id,
2951 origin,
2952 ..
2953 },
2954 PaneSemanticInputEventKind::PointerUp {
2955 target: incoming_target,
2956 pointer_id: incoming_pointer_id,
2957 position,
2958 ..
2959 },
2960 ) => {
2961 if *incoming_pointer_id != pointer_id {
2962 PaneDragResizeEffect::Noop {
2963 reason: PaneDragResizeNoopReason::PointerMismatch,
2964 }
2965 } else if *incoming_target != target {
2966 PaneDragResizeEffect::Noop {
2967 reason: PaneDragResizeNoopReason::TargetMismatch,
2968 }
2969 } else {
2970 self.state = PaneDragResizeState::Idle;
2971 let (total_delta_x, total_delta_y) = delta(origin, *position);
2972 PaneDragResizeEffect::Committed {
2973 target,
2974 pointer_id,
2975 origin,
2976 end: *position,
2977 total_delta_x,
2978 total_delta_y,
2979 }
2980 }
2981 }
2982 (
2983 PaneDragResizeState::Armed {
2984 target, pointer_id, ..
2985 },
2986 PaneSemanticInputEventKind::Cancel {
2987 target: incoming_target,
2988 reason,
2989 },
2990 ) => {
2991 if !cancel_target_matches(target, *incoming_target) {
2992 PaneDragResizeEffect::Noop {
2993 reason: PaneDragResizeNoopReason::TargetMismatch,
2994 }
2995 } else {
2996 self.state = PaneDragResizeState::Idle;
2997 PaneDragResizeEffect::Canceled {
2998 target: Some(target),
2999 pointer_id: Some(pointer_id),
3000 reason: *reason,
3001 }
3002 }
3003 }
3004 (
3005 PaneDragResizeState::Armed {
3006 target, pointer_id, ..
3007 },
3008 PaneSemanticInputEventKind::Blur {
3009 target: incoming_target,
3010 },
3011 ) => {
3012 if !cancel_target_matches(target, *incoming_target) {
3013 PaneDragResizeEffect::Noop {
3014 reason: PaneDragResizeNoopReason::TargetMismatch,
3015 }
3016 } else {
3017 self.state = PaneDragResizeState::Idle;
3018 PaneDragResizeEffect::Canceled {
3019 target: Some(target),
3020 pointer_id: Some(pointer_id),
3021 reason: PaneCancelReason::Blur,
3022 }
3023 }
3024 }
3025 (PaneDragResizeState::Armed { .. }, PaneSemanticInputEventKind::PointerDown { .. }) => {
3026 PaneDragResizeEffect::Noop {
3027 reason: PaneDragResizeNoopReason::ActiveDragAlreadyInProgress,
3028 }
3029 }
3030 (
3031 PaneDragResizeState::Armed { .. },
3032 PaneSemanticInputEventKind::KeyboardResize { .. }
3033 | PaneSemanticInputEventKind::WheelNudge { .. },
3034 ) => PaneDragResizeEffect::Noop {
3035 reason: PaneDragResizeNoopReason::ActiveStateDisallowsDiscreteInput,
3036 },
3037 (
3038 PaneDragResizeState::Dragging {
3039 target,
3040 pointer_id,
3041 origin,
3042 current,
3043 started_sequence,
3044 drag_started_sequence,
3045 },
3046 PaneSemanticInputEventKind::PointerMove {
3047 target: incoming_target,
3048 pointer_id: incoming_pointer_id,
3049 position,
3050 ..
3051 },
3052 ) => {
3053 if *incoming_pointer_id != pointer_id {
3054 PaneDragResizeEffect::Noop {
3055 reason: PaneDragResizeNoopReason::PointerMismatch,
3056 }
3057 } else if *incoming_target != target {
3058 PaneDragResizeEffect::Noop {
3059 reason: PaneDragResizeNoopReason::TargetMismatch,
3060 }
3061 } else {
3062 let previous = current;
3063 if !crossed_drag_threshold(previous, *position, self.update_hysteresis) {
3064 PaneDragResizeEffect::Noop {
3065 reason: PaneDragResizeNoopReason::BelowHysteresis,
3066 }
3067 } else {
3068 let (delta_x, delta_y) = delta(previous, *position);
3069 let (total_delta_x, total_delta_y) = delta(origin, *position);
3070 self.state = PaneDragResizeState::Dragging {
3071 target,
3072 pointer_id,
3073 origin,
3074 current: *position,
3075 started_sequence,
3076 drag_started_sequence,
3077 };
3078 PaneDragResizeEffect::DragUpdated {
3079 target,
3080 pointer_id,
3081 previous,
3082 current: *position,
3083 delta_x,
3084 delta_y,
3085 total_delta_x,
3086 total_delta_y,
3087 }
3088 }
3089 }
3090 }
3091 (
3092 PaneDragResizeState::Dragging {
3093 target,
3094 pointer_id,
3095 origin,
3096 ..
3097 },
3098 PaneSemanticInputEventKind::PointerUp {
3099 target: incoming_target,
3100 pointer_id: incoming_pointer_id,
3101 position,
3102 ..
3103 },
3104 ) => {
3105 if *incoming_pointer_id != pointer_id {
3106 PaneDragResizeEffect::Noop {
3107 reason: PaneDragResizeNoopReason::PointerMismatch,
3108 }
3109 } else if *incoming_target != target {
3110 PaneDragResizeEffect::Noop {
3111 reason: PaneDragResizeNoopReason::TargetMismatch,
3112 }
3113 } else {
3114 self.state = PaneDragResizeState::Idle;
3115 let (total_delta_x, total_delta_y) = delta(origin, *position);
3116 PaneDragResizeEffect::Committed {
3117 target,
3118 pointer_id,
3119 origin,
3120 end: *position,
3121 total_delta_x,
3122 total_delta_y,
3123 }
3124 }
3125 }
3126 (
3127 PaneDragResizeState::Dragging {
3128 target, pointer_id, ..
3129 },
3130 PaneSemanticInputEventKind::Cancel {
3131 target: incoming_target,
3132 reason,
3133 },
3134 ) => {
3135 if !cancel_target_matches(target, *incoming_target) {
3136 PaneDragResizeEffect::Noop {
3137 reason: PaneDragResizeNoopReason::TargetMismatch,
3138 }
3139 } else {
3140 self.state = PaneDragResizeState::Idle;
3141 PaneDragResizeEffect::Canceled {
3142 target: Some(target),
3143 pointer_id: Some(pointer_id),
3144 reason: *reason,
3145 }
3146 }
3147 }
3148 (
3149 PaneDragResizeState::Dragging {
3150 target, pointer_id, ..
3151 },
3152 PaneSemanticInputEventKind::Blur {
3153 target: incoming_target,
3154 },
3155 ) => {
3156 if !cancel_target_matches(target, *incoming_target) {
3157 PaneDragResizeEffect::Noop {
3158 reason: PaneDragResizeNoopReason::TargetMismatch,
3159 }
3160 } else {
3161 self.state = PaneDragResizeState::Idle;
3162 PaneDragResizeEffect::Canceled {
3163 target: Some(target),
3164 pointer_id: Some(pointer_id),
3165 reason: PaneCancelReason::Blur,
3166 }
3167 }
3168 }
3169 (
3170 PaneDragResizeState::Dragging { .. },
3171 PaneSemanticInputEventKind::PointerDown { .. },
3172 ) => PaneDragResizeEffect::Noop {
3173 reason: PaneDragResizeNoopReason::ActiveDragAlreadyInProgress,
3174 },
3175 (
3176 PaneDragResizeState::Dragging { .. },
3177 PaneSemanticInputEventKind::KeyboardResize { .. }
3178 | PaneSemanticInputEventKind::WheelNudge { .. },
3179 ) => PaneDragResizeEffect::Noop {
3180 reason: PaneDragResizeNoopReason::ActiveStateDisallowsDiscreteInput,
3181 },
3182 };
3183
3184 self.transition_counter = self.transition_counter.saturating_add(1);
3185 Ok(PaneDragResizeTransition {
3186 transition_id: self.transition_counter,
3187 sequence: event.sequence,
3188 from,
3189 to: self.state,
3190 effect,
3191 })
3192 }
3193}
3194
3195#[derive(Debug, Clone, PartialEq, Eq)]
3197pub enum PaneDragResizeMachineError {
3198 InvalidDragThreshold { threshold: u16 },
3199 InvalidUpdateHysteresis { hysteresis: u16 },
3200 InvalidEvent(PaneSemanticInputEventError),
3201}
3202
3203impl fmt::Display for PaneDragResizeMachineError {
3204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3205 match self {
3206 Self::InvalidDragThreshold { threshold } => {
3207 write!(f, "drag threshold must be > 0 (got {threshold})")
3208 }
3209 Self::InvalidUpdateHysteresis { hysteresis } => {
3210 write!(f, "update hysteresis must be > 0 (got {hysteresis})")
3211 }
3212 Self::InvalidEvent(error) => write!(f, "invalid semantic pane input event: {error}"),
3213 }
3214 }
3215}
3216
3217impl std::error::Error for PaneDragResizeMachineError {
3218 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3219 if let Self::InvalidEvent(error) = self {
3220 return Some(error);
3221 }
3222 None
3223 }
3224}
3225
3226fn delta(origin: PanePointerPosition, current: PanePointerPosition) -> (i32, i32) {
3227 (current.x - origin.x, current.y - origin.y)
3228}
3229
3230fn crossed_drag_threshold(
3231 origin: PanePointerPosition,
3232 current: PanePointerPosition,
3233 threshold: u16,
3234) -> bool {
3235 let (dx, dy) = delta(origin, current);
3236 let threshold = i64::from(threshold);
3237 let squared_distance = i64::from(dx) * i64::from(dx) + i64::from(dy) * i64::from(dy);
3238 squared_distance >= threshold * threshold
3239}
3240
3241fn cancel_target_matches(active: PaneResizeTarget, incoming: Option<PaneResizeTarget>) -> bool {
3242 incoming.is_none() || incoming == Some(active)
3243}
3244
3245fn round_f64_to_i32(value: f64) -> i32 {
3246 if !value.is_finite() {
3247 return 0;
3248 }
3249 if value >= f64::from(i32::MAX) {
3250 return i32::MAX;
3251 }
3252 if value <= f64::from(i32::MIN) {
3253 return i32::MIN;
3254 }
3255 value.round() as i32
3256}
3257
3258fn axis_share_from_pointer(
3259 rect: Rect,
3260 pointer: PanePointerPosition,
3261 axis: SplitAxis,
3262 inset_cells: f64,
3263) -> f64 {
3264 let inset = inset_cells.max(0.0);
3265 let (origin, extent, coordinate) = match axis {
3266 SplitAxis::Horizontal => (
3267 f64::from(rect.x),
3268 f64::from(rect.width),
3269 f64::from(pointer.x),
3270 ),
3271 SplitAxis::Vertical => (
3272 f64::from(rect.y),
3273 f64::from(rect.height),
3274 f64::from(pointer.y),
3275 ),
3276 };
3277 if extent <= 0.0 {
3278 return 0.5;
3279 }
3280 let low = origin + inset.min(extent / 2.0);
3281 let high = (origin + extent) - inset.min(extent / 2.0);
3282 if high <= low {
3283 return 0.5;
3284 }
3285 ((coordinate - low) / (high - low)).clamp(0.0, 1.0)
3286}
3287
3288fn elastic_ratio_bps(raw_bps: u16, pressure: PanePressureSnapProfile) -> u16 {
3289 let raw = f64::from(raw_bps.clamp(1, 9_999)) / 10_000.0;
3290 let confidence = (f64::from(pressure.strength_bps) / 10_000.0).clamp(0.0, 1.0);
3291 let edge_band = (0.16 - confidence * 0.09).clamp(0.05, 0.18);
3292 let resistance = (0.62 - confidence * 0.34).clamp(0.18, 0.68);
3293 let eased = if raw < edge_band {
3294 let ratio = (raw / edge_band).clamp(0.0, 1.0);
3295 edge_band * ratio.powf(1.0 / (1.0 + resistance))
3296 } else if raw > 1.0 - edge_band {
3297 let ratio = ((1.0 - raw) / edge_band).clamp(0.0, 1.0);
3298 1.0 - edge_band * ratio.powf(1.0 / (1.0 + resistance))
3299 } else {
3300 raw
3301 };
3302 (eased * 10_000.0).round().clamp(1.0, 9_999.0) as u16
3303}
3304
3305fn classify_resize_grip(
3306 rect: Rect,
3307 pointer: PanePointerPosition,
3308 inset_cells: f64,
3309) -> Option<PaneResizeGrip> {
3310 let inset = inset_cells.max(0.5);
3311 let left = f64::from(rect.x);
3312 let right = f64::from(rect.x.saturating_add(rect.width.saturating_sub(1)));
3313 let top = f64::from(rect.y);
3314 let bottom = f64::from(rect.y.saturating_add(rect.height.saturating_sub(1)));
3315 let px = f64::from(pointer.x);
3316 let py = f64::from(pointer.y);
3317
3318 if px < left - inset || px > right + inset || py < top - inset || py > bottom + inset {
3319 return None;
3320 }
3321
3322 let mut near_left = (px - left).abs() <= inset;
3323 let mut near_right = (px - right).abs() <= inset;
3324 let mut near_top = (py - top).abs() <= inset;
3325 let mut near_bottom = (py - bottom).abs() <= inset;
3326
3327 if near_left && near_right {
3329 if (px - left).abs() < (px - right).abs() {
3330 near_right = false;
3331 } else {
3332 near_left = false;
3333 }
3334 }
3335 if near_top && near_bottom {
3336 if (py - top).abs() < (py - bottom).abs() {
3337 near_bottom = false;
3338 } else {
3339 near_top = false;
3340 }
3341 }
3342
3343 match (near_left, near_right, near_top, near_bottom) {
3344 (true, false, true, false) => Some(PaneResizeGrip::TopLeft),
3345 (false, true, true, false) => Some(PaneResizeGrip::TopRight),
3346 (true, false, false, true) => Some(PaneResizeGrip::BottomLeft),
3347 (false, true, false, true) => Some(PaneResizeGrip::BottomRight),
3348 (true, false, false, false) => Some(PaneResizeGrip::Left),
3349 (false, true, false, false) => Some(PaneResizeGrip::Right),
3350 (false, false, true, false) => Some(PaneResizeGrip::Top),
3351 (false, false, false, true) => Some(PaneResizeGrip::Bottom),
3352 _ => None,
3353 }
3354}
3355
3356fn euclidean_distance(a: PanePointerPosition, b: PanePointerPosition) -> f64 {
3357 let dx = f64::from(a.x - b.x);
3358 let dy = f64::from(a.y - b.y);
3359 (dx * dx + dy * dy).sqrt()
3360}
3361
3362fn rect_zone_anchor(rect: Rect, zone: PaneDockZone) -> PanePointerPosition {
3363 let left = i32::from(rect.x);
3364 let right = i32::from(rect.x.saturating_add(rect.width.saturating_sub(1)));
3365 let top = i32::from(rect.y);
3366 let bottom = i32::from(rect.y.saturating_add(rect.height.saturating_sub(1)));
3367 let mid_x = (left + right) / 2;
3368 let mid_y = (top + bottom) / 2;
3369 match zone {
3370 PaneDockZone::Left => PanePointerPosition::new(left, mid_y),
3371 PaneDockZone::Right => PanePointerPosition::new(right, mid_y),
3372 PaneDockZone::Top => PanePointerPosition::new(mid_x, top),
3373 PaneDockZone::Bottom => PanePointerPosition::new(mid_x, bottom),
3374 PaneDockZone::Center => PanePointerPosition::new(mid_x, mid_y),
3375 }
3376}
3377
3378fn dock_zone_ghost_rect(rect: Rect, zone: PaneDockZone) -> Rect {
3379 match zone {
3380 PaneDockZone::Left => {
3381 Rect::new(rect.x, rect.y, (rect.width / 2).max(1), rect.height.max(1))
3382 }
3383 PaneDockZone::Right => {
3384 let width = (rect.width / 2).max(1);
3385 Rect::new(
3386 rect.x.saturating_add(rect.width.saturating_sub(width)),
3387 rect.y,
3388 width,
3389 rect.height.max(1),
3390 )
3391 }
3392 PaneDockZone::Top => Rect::new(rect.x, rect.y, rect.width.max(1), (rect.height / 2).max(1)),
3393 PaneDockZone::Bottom => {
3394 let height = (rect.height / 2).max(1);
3395 Rect::new(
3396 rect.x,
3397 rect.y.saturating_add(rect.height.saturating_sub(height)),
3398 rect.width.max(1),
3399 height,
3400 )
3401 }
3402 PaneDockZone::Center => rect,
3403 }
3404}
3405
3406fn dock_zone_score(distance: f64, radius: f64, zone: PaneDockZone) -> f64 {
3407 if radius <= 0.0 || distance > radius {
3408 return 0.0;
3409 }
3410 let base = 1.0 - (distance / radius);
3411 let zone_weight = match zone {
3412 PaneDockZone::Center => 0.85,
3413 PaneDockZone::Left | PaneDockZone::Right | PaneDockZone::Top | PaneDockZone::Bottom => 1.0,
3414 };
3415 base * zone_weight
3416}
3417
3418const fn dock_zone_rank(zone: PaneDockZone) -> u8 {
3419 match zone {
3420 PaneDockZone::Left => 0,
3421 PaneDockZone::Right => 1,
3422 PaneDockZone::Top => 2,
3423 PaneDockZone::Bottom => 3,
3424 PaneDockZone::Center => 4,
3425 }
3426}
3427
3428fn dock_preview_for_rect(
3429 target: PaneId,
3430 rect: Rect,
3431 pointer: PanePointerPosition,
3432 magnetic_field_cells: f64,
3433) -> Option<PaneDockPreview> {
3434 let radius = magnetic_field_cells.max(0.5);
3435 let zones = [
3436 PaneDockZone::Left,
3437 PaneDockZone::Right,
3438 PaneDockZone::Top,
3439 PaneDockZone::Bottom,
3440 PaneDockZone::Center,
3441 ];
3442 let mut best: Option<PaneDockPreview> = None;
3443 for zone in zones {
3444 let anchor = rect_zone_anchor(rect, zone);
3445 let distance = euclidean_distance(anchor, pointer);
3446 let score = dock_zone_score(distance, radius, zone);
3447 if score <= 0.0 {
3448 continue;
3449 }
3450 let candidate = PaneDockPreview {
3451 target,
3452 zone,
3453 score,
3454 ghost_rect: dock_zone_ghost_rect(rect, zone),
3455 };
3456 match best {
3457 Some(current) if candidate.score <= current.score => {}
3458 _ => best = Some(candidate),
3459 }
3460 }
3461 best
3462}
3463
3464fn dock_zone_motion_intent(zone: PaneDockZone, motion: PaneMotionVector) -> f64 {
3465 let dx = f64::from(motion.delta_x);
3466 let dy = f64::from(motion.delta_y);
3467 let abs_dx = dx.abs();
3468 let abs_dy = dy.abs();
3469 let total = (abs_dx + abs_dy).max(1.0);
3470 let horizontal = abs_dx / total;
3471 let vertical = abs_dy / total;
3472 let speed_factor = (motion.speed / 140.0).clamp(0.0, 1.0);
3473 let noise_penalty = (f64::from(motion.direction_changes) / 10.0).clamp(0.0, 1.0);
3474
3475 let directional = match zone {
3476 PaneDockZone::Left => {
3477 if dx < 0.0 {
3478 0.95 + horizontal * 0.55
3479 } else {
3480 1.0 - horizontal * 0.35
3481 }
3482 }
3483 PaneDockZone::Right => {
3484 if dx > 0.0 {
3485 0.95 + horizontal * 0.55
3486 } else {
3487 1.0 - horizontal * 0.35
3488 }
3489 }
3490 PaneDockZone::Top => {
3491 if dy < 0.0 {
3492 0.95 + vertical * 0.55
3493 } else {
3494 1.0 - vertical * 0.35
3495 }
3496 }
3497 PaneDockZone::Bottom => {
3498 if dy > 0.0 {
3499 0.95 + vertical * 0.55
3500 } else {
3501 1.0 - vertical * 0.35
3502 }
3503 }
3504 PaneDockZone::Center => {
3505 let axis_ambiguity = 1.0 - horizontal.max(vertical);
3506 0.9 + axis_ambiguity * 0.25 - speed_factor * 0.12
3507 }
3508 };
3509 (directional - noise_penalty * 0.22).clamp(0.55, 1.45)
3510}
3511
3512fn dock_preview_for_rect_with_motion(
3513 target: PaneId,
3514 rect: Rect,
3515 pointer: PanePointerPosition,
3516 magnetic_field_cells: f64,
3517 motion: PaneMotionVector,
3518) -> Option<PaneDockPreview> {
3519 let radius = magnetic_field_cells.max(0.5);
3520 let zones = [
3521 PaneDockZone::Left,
3522 PaneDockZone::Right,
3523 PaneDockZone::Top,
3524 PaneDockZone::Bottom,
3525 PaneDockZone::Center,
3526 ];
3527 let mut best: Option<PaneDockPreview> = None;
3528 for zone in zones {
3529 let anchor = rect_zone_anchor(rect, zone);
3530 let distance = euclidean_distance(anchor, pointer);
3531 let base = dock_zone_score(distance, radius, zone);
3532 if base <= 0.0 {
3533 continue;
3534 }
3535 let intent = dock_zone_motion_intent(zone, motion);
3536 let score = (base * intent).clamp(0.0, 1.0);
3537 if score <= 0.0 {
3538 continue;
3539 }
3540 let candidate = PaneDockPreview {
3541 target,
3542 zone,
3543 score,
3544 ghost_rect: dock_zone_ghost_rect(rect, zone),
3545 };
3546 match best {
3547 Some(current) if candidate.score <= current.score => {}
3548 _ => best = Some(candidate),
3549 }
3550 }
3551 best
3552}
3553
3554fn zone_to_axis_placement_and_target_share(
3555 zone: PaneDockZone,
3556 incoming_share_bps: u16,
3557) -> (SplitAxis, PanePlacement, u16) {
3558 let incoming = incoming_share_bps.clamp(500, 9_500);
3559 let target_share = 10_000_u16.saturating_sub(incoming);
3560 match zone {
3561 PaneDockZone::Left => (
3562 SplitAxis::Horizontal,
3563 PanePlacement::IncomingFirst,
3564 incoming,
3565 ),
3566 PaneDockZone::Right => (
3567 SplitAxis::Horizontal,
3568 PanePlacement::ExistingFirst,
3569 target_share,
3570 ),
3571 PaneDockZone::Top => (SplitAxis::Vertical, PanePlacement::IncomingFirst, incoming),
3572 PaneDockZone::Bottom => (
3573 SplitAxis::Vertical,
3574 PanePlacement::ExistingFirst,
3575 target_share,
3576 ),
3577 PaneDockZone::Center => (SplitAxis::Horizontal, PanePlacement::ExistingFirst, 5_000),
3578 }
3579}
3580
3581#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3583#[serde(tag = "op", rename_all = "snake_case")]
3584pub enum PaneOperation {
3585 SplitLeaf {
3588 target: PaneId,
3589 axis: SplitAxis,
3590 ratio: PaneSplitRatio,
3591 placement: PanePlacement,
3592 new_leaf: PaneLeaf,
3593 },
3594 CloseNode { target: PaneId },
3596 MoveSubtree {
3599 source: PaneId,
3600 target: PaneId,
3601 axis: SplitAxis,
3602 ratio: PaneSplitRatio,
3603 placement: PanePlacement,
3604 },
3605 SwapNodes { first: PaneId, second: PaneId },
3607 SetSplitRatio {
3609 split: PaneId,
3610 ratio: PaneSplitRatio,
3611 },
3612 NormalizeRatios,
3614}
3615
3616impl PaneOperation {
3617 #[must_use]
3619 pub const fn kind(&self) -> PaneOperationKind {
3620 match self {
3621 Self::SplitLeaf { .. } => PaneOperationKind::SplitLeaf,
3622 Self::CloseNode { .. } => PaneOperationKind::CloseNode,
3623 Self::MoveSubtree { .. } => PaneOperationKind::MoveSubtree,
3624 Self::SwapNodes { .. } => PaneOperationKind::SwapNodes,
3625 Self::SetSplitRatio { .. } => PaneOperationKind::SetSplitRatio,
3626 Self::NormalizeRatios => PaneOperationKind::NormalizeRatios,
3627 }
3628 }
3629
3630 #[must_use]
3631 fn referenced_nodes(&self) -> Vec<PaneId> {
3632 match self {
3633 Self::SplitLeaf { target, .. } | Self::CloseNode { target } => vec![*target],
3634 Self::MoveSubtree { source, target, .. }
3635 | Self::SwapNodes {
3636 first: source,
3637 second: target,
3638 } => {
3639 vec![*source, *target]
3640 }
3641 Self::SetSplitRatio { split, .. } => vec![*split],
3642 Self::NormalizeRatios => Vec::new(),
3643 }
3644 }
3645}
3646
3647#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3649#[serde(rename_all = "snake_case")]
3650pub enum PaneOperationKind {
3651 SplitLeaf,
3652 CloseNode,
3653 MoveSubtree,
3654 SwapNodes,
3655 SetSplitRatio,
3656 NormalizeRatios,
3657}
3658
3659#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3669#[serde(rename_all = "snake_case")]
3670pub enum PaneOperationFamily {
3671 Local,
3676 Structural,
3680}
3681
3682impl PaneOperationKind {
3683 #[must_use]
3685 pub const fn family(self) -> PaneOperationFamily {
3686 match self {
3687 Self::SetSplitRatio => PaneOperationFamily::Local,
3688 Self::SplitLeaf
3689 | Self::CloseNode
3690 | Self::MoveSubtree
3691 | Self::SwapNodes
3692 | Self::NormalizeRatios => PaneOperationFamily::Structural,
3693 }
3694 }
3695}
3696
3697impl PaneOperation {
3698 #[must_use]
3700 pub const fn family(&self) -> PaneOperationFamily {
3701 self.kind().family()
3702 }
3703}
3704
3705#[derive(Debug, Clone, PartialEq, Eq)]
3707pub struct PaneOperationOutcome {
3708 pub operation_id: u64,
3709 pub kind: PaneOperationKind,
3710 pub touched_nodes: SmallVec<[PaneId; 4]>,
3714 pub before_hash: u64,
3715 pub after_hash: u64,
3716}
3717
3718#[derive(Debug, Clone, PartialEq, Eq)]
3720pub struct PaneOperationError {
3721 pub operation_id: u64,
3722 pub kind: PaneOperationKind,
3723 pub touched_nodes: SmallVec<[PaneId; 4]>,
3726 pub before_hash: u64,
3727 pub after_hash: u64,
3728 pub reason: PaneOperationFailure,
3729}
3730
3731#[derive(Debug, Clone, PartialEq, Eq)]
3733pub enum PaneOperationFailure {
3734 MissingNode {
3735 node_id: PaneId,
3736 },
3737 NodeNotLeaf {
3738 node_id: PaneId,
3739 },
3740 ParentNotSplit {
3741 node_id: PaneId,
3742 },
3743 ParentChildMismatch {
3744 parent: PaneId,
3745 child: PaneId,
3746 },
3747 CannotCloseRoot {
3748 node_id: PaneId,
3749 },
3750 CannotMoveRoot {
3751 node_id: PaneId,
3752 },
3753 SameNode {
3754 first: PaneId,
3755 second: PaneId,
3756 },
3757 AncestorConflict {
3758 ancestor: PaneId,
3759 descendant: PaneId,
3760 },
3761 TargetRemovedByDetach {
3762 target: PaneId,
3763 detached_parent: PaneId,
3764 },
3765 PaneIdOverflow {
3766 current: PaneId,
3767 },
3768 InvalidRatio {
3769 node_id: PaneId,
3770 numerator: u32,
3771 denominator: u32,
3772 },
3773 Validation(PaneModelError),
3774}
3775
3776impl fmt::Display for PaneOperationFailure {
3777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3778 match self {
3779 Self::MissingNode { node_id } => write!(f, "node {} not found", node_id.0),
3780 Self::NodeNotLeaf { node_id } => write!(f, "node {} is not a leaf", node_id.0),
3781 Self::ParentNotSplit { node_id } => {
3782 write!(f, "node {} is not a split parent", node_id.0)
3783 }
3784 Self::ParentChildMismatch { parent, child } => write!(
3785 f,
3786 "split parent {} does not reference child {}",
3787 parent.0, child.0
3788 ),
3789 Self::CannotCloseRoot { node_id } => {
3790 write!(f, "cannot close root node {}", node_id.0)
3791 }
3792 Self::CannotMoveRoot { node_id } => {
3793 write!(f, "cannot move root node {}", node_id.0)
3794 }
3795 Self::SameNode { first, second } => write!(
3796 f,
3797 "operation requires distinct nodes, got {} and {}",
3798 first.0, second.0
3799 ),
3800 Self::AncestorConflict {
3801 ancestor,
3802 descendant,
3803 } => write!(
3804 f,
3805 "operation would create cycle: node {} is an ancestor of {}",
3806 ancestor.0, descendant.0
3807 ),
3808 Self::TargetRemovedByDetach {
3809 target,
3810 detached_parent,
3811 } => write!(
3812 f,
3813 "target {} would be removed while detaching parent {}",
3814 target.0, detached_parent.0
3815 ),
3816 Self::PaneIdOverflow { current } => {
3817 write!(f, "pane id overflow after {}", current.0)
3818 }
3819 Self::InvalidRatio {
3820 node_id,
3821 numerator,
3822 denominator,
3823 } => write!(
3824 f,
3825 "split node {} has invalid ratio {numerator}/{denominator}",
3826 node_id.0
3827 ),
3828 Self::Validation(err) => write!(f, "{err}"),
3829 }
3830 }
3831}
3832
3833impl std::error::Error for PaneOperationFailure {
3834 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3835 if let Self::Validation(err) = self {
3836 return Some(err);
3837 }
3838 None
3839 }
3840}
3841
3842impl fmt::Display for PaneOperationError {
3843 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3844 write!(
3845 f,
3846 "pane op {} ({:?}) failed: {} [nodes={:?}, before_hash={:#x}, after_hash={:#x}]",
3847 self.operation_id,
3848 self.kind,
3849 self.reason,
3850 self.touched_nodes
3851 .iter()
3852 .map(|node_id| node_id.0)
3853 .collect::<Vec<_>>(),
3854 self.before_hash,
3855 self.after_hash
3856 )
3857 }
3858}
3859
3860impl std::error::Error for PaneOperationError {
3861 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3862 Some(&self.reason)
3863 }
3864}
3865
3866#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3868pub struct PaneOperationJournalEntry {
3869 pub transaction_id: u64,
3870 pub sequence: u64,
3871 pub operation_id: u64,
3872 pub operation: PaneOperation,
3873 pub kind: PaneOperationKind,
3874 pub touched_nodes: Vec<PaneId>,
3875 pub before_hash: u64,
3876 pub after_hash: u64,
3877 pub result: PaneOperationJournalResult,
3878}
3879
3880#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3882#[serde(tag = "status", rename_all = "snake_case")]
3883pub enum PaneOperationJournalResult {
3884 Applied,
3885 Rejected { reason: String },
3886}
3887
3888#[derive(Debug, Clone, PartialEq, Eq)]
3890pub struct PaneTransactionOutcome {
3891 pub transaction_id: u64,
3892 pub committed: bool,
3893 pub tree: PaneTree,
3894 pub journal: Vec<PaneOperationJournalEntry>,
3895}
3896
3897#[derive(Debug, Clone, PartialEq, Eq)]
3899pub struct PaneTransaction {
3900 transaction_id: u64,
3901 sequence: u64,
3902 base_tree: PaneTree,
3903 working_tree: PaneTree,
3904 journal: Vec<PaneOperationJournalEntry>,
3905}
3906
3907impl PaneTransaction {
3908 fn new(transaction_id: u64, base_tree: PaneTree) -> Self {
3909 Self {
3910 transaction_id,
3911 sequence: 1,
3912 base_tree: base_tree.clone(),
3913 working_tree: base_tree,
3914 journal: Vec::new(),
3915 }
3916 }
3917
3918 #[must_use]
3920 pub const fn transaction_id(&self) -> u64 {
3921 self.transaction_id
3922 }
3923
3924 #[must_use]
3926 pub fn tree(&self) -> &PaneTree {
3927 &self.working_tree
3928 }
3929
3930 #[must_use]
3932 pub fn journal(&self) -> &[PaneOperationJournalEntry] {
3933 &self.journal
3934 }
3935
3936 pub fn apply_operation(
3940 &mut self,
3941 operation_id: u64,
3942 operation: PaneOperation,
3943 ) -> Result<PaneOperationOutcome, PaneOperationError> {
3944 let operation_for_journal = operation.clone();
3945 let kind = operation_for_journal.kind();
3946 let sequence = self.next_sequence();
3947
3948 match self.working_tree.apply_operation(operation_id, operation) {
3949 Ok(outcome) => {
3950 self.journal.push(PaneOperationJournalEntry {
3951 transaction_id: self.transaction_id,
3952 sequence,
3953 operation_id,
3954 operation: operation_for_journal,
3955 kind,
3956 touched_nodes: outcome.touched_nodes.to_vec(),
3957 before_hash: outcome.before_hash,
3958 after_hash: outcome.after_hash,
3959 result: PaneOperationJournalResult::Applied,
3960 });
3961 Ok(outcome)
3962 }
3963 Err(err) => {
3964 self.journal.push(PaneOperationJournalEntry {
3965 transaction_id: self.transaction_id,
3966 sequence,
3967 operation_id,
3968 operation: operation_for_journal,
3969 kind,
3970 touched_nodes: err.touched_nodes.to_vec(),
3971 before_hash: err.before_hash,
3972 after_hash: err.after_hash,
3973 result: PaneOperationJournalResult::Rejected {
3974 reason: err.reason.to_string(),
3975 },
3976 });
3977 Err(err)
3978 }
3979 }
3980 }
3981
3982 #[must_use]
3984 pub fn commit(self) -> PaneTransactionOutcome {
3985 PaneTransactionOutcome {
3986 transaction_id: self.transaction_id,
3987 committed: true,
3988 tree: self.working_tree,
3989 journal: self.journal,
3990 }
3991 }
3992
3993 #[must_use]
3995 pub fn rollback(self) -> PaneTransactionOutcome {
3996 PaneTransactionOutcome {
3997 transaction_id: self.transaction_id,
3998 committed: false,
3999 tree: self.base_tree,
4000 journal: self.journal,
4001 }
4002 }
4003
4004 fn next_sequence(&mut self) -> u64 {
4005 let sequence = self.sequence;
4006 self.sequence = self.sequence.saturating_add(1);
4007 sequence
4008 }
4009}
4010
4011#[derive(Debug, Clone, PartialEq, Eq)]
4013pub struct PaneTree {
4014 schema_version: u16,
4015 root: PaneId,
4016 next_id: PaneId,
4017 nodes: BTreeMap<PaneId, PaneNodeRecord>,
4018 extensions: BTreeMap<String, String>,
4019}
4020
4021impl PaneTree {
4022 #[must_use]
4024 pub fn singleton(surface_key: impl Into<String>) -> Self {
4025 let root = PaneId::MIN;
4026 let mut nodes = BTreeMap::new();
4027 let _ = nodes.insert(
4028 root,
4029 PaneNodeRecord::leaf(root, None, PaneLeaf::new(surface_key)),
4030 );
4031 Self {
4032 schema_version: PANE_TREE_SCHEMA_VERSION,
4033 root,
4034 next_id: root.checked_next().unwrap_or(root),
4035 nodes,
4036 extensions: BTreeMap::new(),
4037 }
4038 }
4039
4040 pub fn from_snapshot(mut snapshot: PaneTreeSnapshot) -> Result<Self, PaneModelError> {
4042 if snapshot.schema_version != PANE_TREE_SCHEMA_VERSION {
4043 return Err(PaneModelError::UnsupportedSchemaVersion {
4044 version: snapshot.schema_version,
4045 });
4046 }
4047 snapshot.canonicalize();
4048 let mut nodes = BTreeMap::new();
4049 for node in snapshot.nodes {
4050 let node_id = node.id;
4051 if nodes.insert(node_id, node).is_some() {
4052 return Err(PaneModelError::DuplicateNodeId { node_id });
4053 }
4054 }
4055 validate_tree(snapshot.root, snapshot.next_id, &nodes)?;
4056 Ok(Self {
4057 schema_version: snapshot.schema_version,
4058 root: snapshot.root,
4059 next_id: snapshot.next_id,
4060 nodes,
4061 extensions: snapshot.extensions,
4062 })
4063 }
4064
4065 #[must_use]
4067 pub fn to_snapshot(&self) -> PaneTreeSnapshot {
4068 let mut snapshot = PaneTreeSnapshot {
4069 schema_version: self.schema_version,
4070 root: self.root,
4071 next_id: self.next_id,
4072 nodes: self.nodes.values().cloned().collect(),
4073 extensions: self.extensions.clone(),
4074 };
4075 snapshot.canonicalize();
4076 snapshot
4077 }
4078
4079 #[must_use]
4081 pub const fn root(&self) -> PaneId {
4082 self.root
4083 }
4084
4085 #[must_use]
4087 pub const fn next_id(&self) -> PaneId {
4088 self.next_id
4089 }
4090
4091 #[must_use]
4093 pub const fn schema_version(&self) -> u16 {
4094 self.schema_version
4095 }
4096
4097 #[must_use]
4099 pub fn node(&self, id: PaneId) -> Option<&PaneNodeRecord> {
4100 self.nodes.get(&id)
4101 }
4102
4103 pub fn nodes(&self) -> impl Iterator<Item = &PaneNodeRecord> {
4105 self.nodes.values()
4106 }
4107
4108 pub(crate) const fn extensions(&self) -> &BTreeMap<String, String> {
4109 &self.extensions
4110 }
4111
4112 pub fn validate(&self) -> Result<(), PaneModelError> {
4114 validate_tree(self.root, self.next_id, &self.nodes)
4115 }
4116
4117 #[must_use]
4119 pub fn invariant_report(&self) -> PaneInvariantReport {
4120 self.to_snapshot().invariant_report()
4121 }
4122
4123 #[must_use]
4127 pub fn state_hash(&self) -> u64 {
4128 self.hash_state(false)
4129 }
4130
4131 pub(crate) fn history_state_hash(&self) -> u64 {
4135 self.hash_state(true)
4136 }
4137
4138 fn hash_state(&self, raw_ratios: bool) -> u64 {
4139 const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
4140 const PRIME: u64 = 0x0000_0001_0000_01b3;
4141
4142 fn mix(hash: &mut u64, byte: u8) {
4143 *hash ^= u64::from(byte);
4144 *hash = hash.wrapping_mul(PRIME);
4145 }
4146
4147 fn mix_bytes(hash: &mut u64, bytes: &[u8]) {
4148 for byte in bytes {
4149 mix(hash, *byte);
4150 }
4151 }
4152
4153 fn mix_u16(hash: &mut u64, value: u16) {
4154 mix_bytes(hash, &value.to_le_bytes());
4155 }
4156
4157 fn mix_u32(hash: &mut u64, value: u32) {
4158 mix_bytes(hash, &value.to_le_bytes());
4159 }
4160
4161 fn mix_u64(hash: &mut u64, value: u64) {
4162 mix_bytes(hash, &value.to_le_bytes());
4163 }
4164
4165 fn mix_bool(hash: &mut u64, value: bool) {
4166 mix(hash, u8::from(value));
4167 }
4168
4169 fn mix_opt_u16(hash: &mut u64, value: Option<u16>) {
4170 match value {
4171 Some(value) => {
4172 mix(hash, 1);
4173 mix_u16(hash, value);
4174 }
4175 None => mix(hash, 0),
4176 }
4177 }
4178
4179 fn mix_opt_pane_id(hash: &mut u64, value: Option<PaneId>) {
4180 match value {
4181 Some(value) => {
4182 mix(hash, 1);
4183 mix_u64(hash, value.get());
4184 }
4185 None => mix(hash, 0),
4186 }
4187 }
4188
4189 fn mix_str(hash: &mut u64, value: &str) {
4190 mix_u64(hash, value.len() as u64);
4191 mix_bytes(hash, value.as_bytes());
4192 }
4193
4194 fn mix_extensions(hash: &mut u64, extensions: &BTreeMap<String, String>) {
4195 mix_u64(hash, extensions.len() as u64);
4196 for (key, value) in extensions {
4197 mix_str(hash, key);
4198 mix_str(hash, value);
4199 }
4200 }
4201
4202 fn mix_constraints(hash: &mut u64, constraints: PaneConstraints) {
4203 mix_u16(hash, constraints.min_width);
4204 mix_u16(hash, constraints.min_height);
4205 mix_opt_u16(hash, constraints.max_width);
4206 mix_opt_u16(hash, constraints.max_height);
4207 mix_bool(hash, constraints.collapsible);
4208 }
4209
4210 let mut hash = OFFSET_BASIS;
4211 mix_u16(&mut hash, self.schema_version);
4212 mix_u64(&mut hash, self.root.get());
4213 mix_u64(&mut hash, self.next_id.get());
4214 mix_extensions(&mut hash, &self.extensions);
4215 mix_u64(&mut hash, self.nodes.len() as u64);
4216
4217 for node in self.nodes.values() {
4218 mix_u64(&mut hash, node.id.get());
4219 mix_opt_pane_id(&mut hash, node.parent);
4220 mix_constraints(&mut hash, node.constraints);
4221 mix_extensions(&mut hash, &node.extensions);
4222
4223 match &node.kind {
4224 PaneNodeKind::Leaf(leaf) => {
4225 mix(&mut hash, 1);
4226 mix_str(&mut hash, &leaf.surface_key);
4227 mix_extensions(&mut hash, &leaf.extensions);
4228 }
4229 PaneNodeKind::Split(split) => {
4230 mix(&mut hash, 2);
4231 let axis_byte = match split.axis {
4232 SplitAxis::Horizontal => 1,
4233 SplitAxis::Vertical => 2,
4234 };
4235 mix(&mut hash, axis_byte);
4236 mix_u32(
4237 &mut hash,
4238 if raw_ratios {
4239 split.ratio.numerator
4240 } else {
4241 split.ratio.numerator()
4242 },
4243 );
4244 mix_u32(
4245 &mut hash,
4246 if raw_ratios {
4247 split.ratio.denominator
4248 } else {
4249 split.ratio.denominator()
4250 },
4251 );
4252 mix_u64(&mut hash, split.first.get());
4253 mix_u64(&mut hash, split.second.get());
4254 }
4255 }
4256 }
4257
4258 hash
4259 }
4260
4261 #[must_use]
4266 pub fn begin_transaction(&self, transaction_id: u64) -> PaneTransaction {
4267 PaneTransaction::new(transaction_id, self.clone())
4268 }
4269
4270 pub fn apply_operation(
4282 &mut self,
4283 operation_id: u64,
4284 operation: PaneOperation,
4285 ) -> Result<PaneOperationOutcome, PaneOperationError> {
4286 if let PaneOperation::SetSplitRatio { split, ratio } = operation {
4287 return self.apply_set_split_ratio_atomic(operation_id, split, ratio);
4289 }
4290
4291 self.apply_operation_generic(operation_id, operation, PaneValidationMode::Adaptive)
4292 }
4293
4294 pub fn apply_operation_conservative(
4304 &mut self,
4305 operation_id: u64,
4306 operation: PaneOperation,
4307 ) -> Result<PaneOperationOutcome, PaneOperationError> {
4308 self.apply_operation_generic(operation_id, operation, PaneValidationMode::AlwaysFull)
4309 }
4310
4311 fn apply_operation_generic(
4316 &mut self,
4317 operation_id: u64,
4318 operation: PaneOperation,
4319 mode: PaneValidationMode,
4320 ) -> Result<PaneOperationOutcome, PaneOperationError> {
4321 let kind = operation.kind();
4322 let before_hash = self.state_hash();
4323 let mut working = self.clone();
4324 let mut touched = operation
4325 .referenced_nodes()
4326 .into_iter()
4327 .collect::<BTreeSet<_>>();
4328
4329 if let Err(reason) = working.apply_operation_inner(operation, &mut touched) {
4330 return Err(PaneOperationError {
4331 operation_id,
4332 kind,
4333 touched_nodes: touched.into_iter().collect(),
4334 before_hash,
4335 after_hash: working.state_hash(),
4336 reason,
4337 });
4338 }
4339
4340 let touched_nodes: SmallVec<[PaneId; 4]> = touched.into_iter().collect();
4343 if let Err(err) = working.validate_after_operation_with_mode(kind, &touched_nodes, mode) {
4344 return Err(PaneOperationError {
4345 operation_id,
4346 kind,
4347 touched_nodes,
4348 before_hash,
4349 after_hash: working.state_hash(),
4350 reason: PaneOperationFailure::Validation(err),
4351 });
4352 }
4353
4354 let after_hash = working.state_hash();
4355 *self = working;
4356
4357 Ok(PaneOperationOutcome {
4358 operation_id,
4359 kind,
4360 touched_nodes,
4361 before_hash,
4362 after_hash,
4363 })
4364 }
4365
4366 fn apply_set_split_ratio_atomic(
4367 &mut self,
4368 operation_id: u64,
4369 split_id: PaneId,
4370 ratio: PaneSplitRatio,
4371 ) -> Result<PaneOperationOutcome, PaneOperationError> {
4372 let kind = PaneOperationKind::SetSplitRatio;
4373 let before_hash = self.state_hash();
4374 let normalized =
4375 PaneSplitRatio::new(ratio.numerator(), ratio.denominator()).map_err(|_| {
4376 PaneOperationError {
4377 operation_id,
4378 kind,
4379 touched_nodes: smallvec![split_id],
4380 before_hash,
4381 after_hash: before_hash,
4382 reason: PaneOperationFailure::InvalidRatio {
4383 node_id: split_id,
4384 numerator: ratio.numerator(),
4385 denominator: ratio.denominator(),
4386 },
4387 }
4388 })?;
4389
4390 let previous_ratio = {
4391 let node = self.nodes.get_mut(&split_id).ok_or(PaneOperationError {
4392 operation_id,
4393 kind,
4394 touched_nodes: smallvec![split_id],
4395 before_hash,
4396 after_hash: before_hash,
4397 reason: PaneOperationFailure::MissingNode { node_id: split_id },
4398 })?;
4399 let PaneNodeKind::Split(split) = &mut node.kind else {
4400 return Err(PaneOperationError {
4401 operation_id,
4402 kind,
4403 touched_nodes: smallvec![split_id],
4404 before_hash,
4405 after_hash: before_hash,
4406 reason: PaneOperationFailure::ParentNotSplit { node_id: split_id },
4407 });
4408 };
4409 let previous_ratio = split.ratio;
4410 split.ratio = normalized;
4411 previous_ratio
4412 };
4413
4414 if let Err(err) = self.validate_after_operation(kind, &[split_id]) {
4415 let node = self.nodes.get_mut(&split_id).ok_or(PaneOperationError {
4416 operation_id,
4417 kind,
4418 touched_nodes: smallvec![split_id],
4419 before_hash,
4420 after_hash: before_hash,
4421 reason: PaneOperationFailure::Validation(err.clone()),
4422 })?;
4423 let PaneNodeKind::Split(split) = &mut node.kind else {
4424 return Err(PaneOperationError {
4425 operation_id,
4426 kind,
4427 touched_nodes: smallvec![split_id],
4428 before_hash,
4429 after_hash: before_hash,
4430 reason: PaneOperationFailure::Validation(err),
4431 });
4432 };
4433 split.ratio = previous_ratio;
4434 return Err(PaneOperationError {
4435 operation_id,
4436 kind,
4437 touched_nodes: smallvec![split_id],
4438 before_hash,
4439 after_hash: before_hash,
4440 reason: PaneOperationFailure::Validation(err),
4441 });
4442 }
4443
4444 let after_hash = self.state_hash();
4445 Ok(PaneOperationOutcome {
4446 operation_id,
4447 kind,
4448 touched_nodes: smallvec![split_id],
4449 before_hash,
4450 after_hash,
4451 })
4452 }
4453
4454 fn apply_operation_in_place_for_replay(
4455 &mut self,
4456 operation_id: u64,
4457 operation: &PaneOperation,
4458 ) -> Result<(), PaneOperationError> {
4459 let kind = operation.kind();
4460 let before_hash = self.state_hash();
4461 let referenced: SmallVec<[PaneId; 4]> = operation.referenced_nodes().into_iter().collect();
4462 let mut touched = referenced.iter().copied().collect::<BTreeSet<_>>();
4463
4464 if let Err(reason) = self.apply_operation_inner_ref(operation, &mut touched) {
4465 return Err(PaneOperationError {
4466 operation_id,
4467 kind,
4468 touched_nodes: referenced,
4469 before_hash,
4470 after_hash: self.state_hash(),
4471 reason,
4472 });
4473 }
4474
4475 let grown: SmallVec<[PaneId; 4]> = touched.into_iter().collect();
4478 if let Err(err) = self.validate_after_operation(kind, &grown) {
4479 return Err(PaneOperationError {
4480 operation_id,
4481 kind,
4482 touched_nodes: referenced,
4483 before_hash,
4484 after_hash: self.state_hash(),
4485 reason: PaneOperationFailure::Validation(err),
4486 });
4487 }
4488
4489 Ok(())
4490 }
4491
4492 fn validate_after_operation(
4493 &self,
4494 kind: PaneOperationKind,
4495 touched: &[PaneId],
4496 ) -> Result<(), PaneModelError> {
4497 self.validate_after_operation_with_mode(kind, touched, PaneValidationMode::Adaptive)
4498 }
4499
4500 fn validate_after_operation_with_mode(
4501 &self,
4502 kind: PaneOperationKind,
4503 touched: &[PaneId],
4504 mode: PaneValidationMode,
4505 ) -> Result<(), PaneModelError> {
4506 let strategy = match mode {
4507 PaneValidationMode::AlwaysFull => PaneValidationStrategy::FullTree,
4508 PaneValidationMode::Adaptive => self.validation_strategy_for_operation(kind),
4509 };
4510 match strategy {
4511 PaneValidationStrategy::FullTree => self.validate(),
4512 PaneValidationStrategy::LocalClosure => self.validate_local_closure(touched),
4513 }
4514 }
4515
4516 const fn validation_strategy_for_operation(
4520 &self,
4521 kind: PaneOperationKind,
4522 ) -> PaneValidationStrategy {
4523 match kind.family() {
4524 PaneOperationFamily::Local => PaneValidationStrategy::LocalClosure,
4525 PaneOperationFamily::Structural => PaneValidationStrategy::FullTree,
4526 }
4527 }
4528
4529 fn validate_local_closure(&self, touched: &[PaneId]) -> Result<(), PaneModelError> {
4530 for node_id in touched {
4531 let node = self
4532 .nodes
4533 .get(node_id)
4534 .ok_or(PaneModelError::MissingRoot { root: *node_id })?;
4535 node.constraints.validate(*node_id)?;
4536
4537 if *node_id == self.root {
4538 if let Some(parent) = node.parent {
4539 return Err(PaneModelError::RootHasParent {
4540 root: self.root,
4541 parent,
4542 });
4543 }
4544 } else if let Some(parent_id) = node.parent {
4545 let parent = self
4546 .nodes
4547 .get(&parent_id)
4548 .ok_or(PaneModelError::MissingParent {
4549 node_id: *node_id,
4550 parent: parent_id,
4551 })?;
4552 let PaneNodeKind::Split(split) = &parent.kind else {
4553 return Err(PaneModelError::ParentMismatch {
4554 node_id: *node_id,
4555 expected: Some(parent_id),
4556 actual: node.parent,
4557 });
4558 };
4559 if split.first != *node_id && split.second != *node_id {
4560 return Err(PaneModelError::ParentMismatch {
4561 node_id: *node_id,
4562 expected: Some(parent_id),
4563 actual: node.parent,
4564 });
4565 }
4566 }
4567
4568 if let PaneNodeKind::Split(split) = &node.kind {
4569 if split.ratio.numerator() == 0 || split.ratio.denominator() == 0 {
4570 return Err(PaneModelError::InvalidSplitRatio {
4571 numerator: split.ratio.numerator(),
4572 denominator: split.ratio.denominator(),
4573 });
4574 }
4575 if split.first == *node_id || split.second == *node_id {
4576 return Err(PaneModelError::SelfReferentialSplit { node_id: *node_id });
4577 }
4578 if split.first == split.second {
4579 return Err(PaneModelError::DuplicateSplitChildren {
4580 node_id: *node_id,
4581 child: split.first,
4582 });
4583 }
4584 for child_id in [split.first, split.second] {
4585 let child = self
4586 .nodes
4587 .get(&child_id)
4588 .ok_or(PaneModelError::MissingChild {
4589 parent: *node_id,
4590 child: child_id,
4591 })?;
4592 if child.parent != Some(*node_id) {
4593 return Err(PaneModelError::ParentMismatch {
4594 node_id: child_id,
4595 expected: Some(*node_id),
4596 actual: child.parent,
4597 });
4598 }
4599 }
4600 }
4601 }
4602
4603 Ok(())
4604 }
4605
4606 fn apply_operation_inner(
4607 &mut self,
4608 operation: PaneOperation,
4609 touched: &mut BTreeSet<PaneId>,
4610 ) -> Result<(), PaneOperationFailure> {
4611 match operation {
4612 PaneOperation::SplitLeaf {
4613 target,
4614 axis,
4615 ratio,
4616 placement,
4617 new_leaf,
4618 } => self.apply_split_leaf(target, axis, ratio, placement, new_leaf, touched),
4619 PaneOperation::CloseNode { target } => self.apply_close_node(target, touched),
4620 PaneOperation::MoveSubtree {
4621 source,
4622 target,
4623 axis,
4624 ratio,
4625 placement,
4626 } => self.apply_move_subtree(source, target, axis, ratio, placement, touched),
4627 PaneOperation::SwapNodes { first, second } => {
4628 self.apply_swap_nodes(first, second, touched)
4629 }
4630 PaneOperation::SetSplitRatio { split, ratio } => {
4631 self.apply_set_split_ratio(split, ratio, touched)
4632 }
4633 PaneOperation::NormalizeRatios => self.apply_normalize_ratios(touched),
4634 }
4635 }
4636
4637 fn apply_operation_inner_ref(
4638 &mut self,
4639 operation: &PaneOperation,
4640 touched: &mut BTreeSet<PaneId>,
4641 ) -> Result<(), PaneOperationFailure> {
4642 match operation {
4643 PaneOperation::SplitLeaf {
4644 target,
4645 axis,
4646 ratio,
4647 placement,
4648 new_leaf,
4649 } => self.apply_split_leaf(
4650 *target,
4651 *axis,
4652 *ratio,
4653 *placement,
4654 new_leaf.clone(),
4655 touched,
4656 ),
4657 PaneOperation::CloseNode { target } => self.apply_close_node(*target, touched),
4658 PaneOperation::MoveSubtree {
4659 source,
4660 target,
4661 axis,
4662 ratio,
4663 placement,
4664 } => self.apply_move_subtree(*source, *target, *axis, *ratio, *placement, touched),
4665 PaneOperation::SwapNodes { first, second } => {
4666 self.apply_swap_nodes(*first, *second, touched)
4667 }
4668 PaneOperation::SetSplitRatio { split, ratio } => {
4669 self.apply_set_split_ratio(*split, *ratio, touched)
4670 }
4671 PaneOperation::NormalizeRatios => self.apply_normalize_ratios(touched),
4672 }
4673 }
4674
4675 fn apply_split_leaf(
4676 &mut self,
4677 target: PaneId,
4678 axis: SplitAxis,
4679 ratio: PaneSplitRatio,
4680 placement: PanePlacement,
4681 new_leaf: PaneLeaf,
4682 touched: &mut BTreeSet<PaneId>,
4683 ) -> Result<(), PaneOperationFailure> {
4684 let target_parent = match self.nodes.get(&target) {
4685 Some(PaneNodeRecord {
4686 parent,
4687 kind: PaneNodeKind::Leaf(_),
4688 ..
4689 }) => *parent,
4690 Some(_) => {
4691 return Err(PaneOperationFailure::NodeNotLeaf { node_id: target });
4692 }
4693 None => {
4694 return Err(PaneOperationFailure::MissingNode { node_id: target });
4695 }
4696 };
4697
4698 let split_id = self.allocate_node_id()?;
4699 let new_leaf_id = self.allocate_node_id()?;
4700 touched.extend([target, split_id, new_leaf_id]);
4701 if let Some(parent_id) = target_parent {
4702 let _ = touched.insert(parent_id);
4703 }
4704
4705 let (first, second) = placement.ordered(target, new_leaf_id);
4706 let split_record = PaneNodeRecord::split(
4707 split_id,
4708 target_parent,
4709 PaneSplit {
4710 axis,
4711 ratio,
4712 first,
4713 second,
4714 },
4715 );
4716
4717 if let Some(target_node) = self.nodes.get_mut(&target) {
4718 target_node.parent = Some(split_id);
4719 }
4720 let _ = self.nodes.insert(
4721 new_leaf_id,
4722 PaneNodeRecord::leaf(new_leaf_id, Some(split_id), new_leaf),
4723 );
4724 let _ = self.nodes.insert(split_id, split_record);
4725
4726 if let Some(parent_id) = target_parent {
4727 self.replace_child(parent_id, target, split_id)?;
4728 } else {
4729 self.root = split_id;
4730 }
4731
4732 Ok(())
4733 }
4734
4735 fn apply_close_node(
4736 &mut self,
4737 target: PaneId,
4738 touched: &mut BTreeSet<PaneId>,
4739 ) -> Result<(), PaneOperationFailure> {
4740 if !self.nodes.contains_key(&target) {
4741 return Err(PaneOperationFailure::MissingNode { node_id: target });
4742 }
4743 if target == self.root {
4744 return Err(PaneOperationFailure::CannotCloseRoot { node_id: target });
4745 }
4746
4747 let subtree_ids = self.collect_subtree_ids(target)?;
4748 for node_id in &subtree_ids {
4749 let _ = touched.insert(*node_id);
4750 }
4751
4752 let (parent_id, sibling_id, grandparent_id) =
4753 self.promote_sibling_after_detach(target, touched)?;
4754 let _ = touched.insert(parent_id);
4755 let _ = touched.insert(sibling_id);
4756 if let Some(grandparent_id) = grandparent_id {
4757 let _ = touched.insert(grandparent_id);
4758 }
4759
4760 for node_id in subtree_ids {
4761 let _ = self.nodes.remove(&node_id);
4762 }
4763
4764 Ok(())
4765 }
4766
4767 fn apply_move_subtree(
4768 &mut self,
4769 source: PaneId,
4770 target: PaneId,
4771 axis: SplitAxis,
4772 ratio: PaneSplitRatio,
4773 placement: PanePlacement,
4774 touched: &mut BTreeSet<PaneId>,
4775 ) -> Result<(), PaneOperationFailure> {
4776 if source == target {
4777 return Err(PaneOperationFailure::SameNode {
4778 first: source,
4779 second: target,
4780 });
4781 }
4782
4783 if !self.nodes.contains_key(&source) {
4784 return Err(PaneOperationFailure::MissingNode { node_id: source });
4785 }
4786 if !self.nodes.contains_key(&target) {
4787 return Err(PaneOperationFailure::MissingNode { node_id: target });
4788 }
4789
4790 if source == self.root {
4791 return Err(PaneOperationFailure::CannotMoveRoot { node_id: source });
4792 }
4793 if self.is_ancestor(source, target)? {
4794 return Err(PaneOperationFailure::AncestorConflict {
4795 ancestor: source,
4796 descendant: target,
4797 });
4798 }
4799
4800 let source_parent = self
4801 .nodes
4802 .get(&source)
4803 .and_then(|node| node.parent)
4804 .ok_or(PaneOperationFailure::CannotMoveRoot { node_id: source })?;
4805 if source_parent == target {
4806 return Err(PaneOperationFailure::TargetRemovedByDetach {
4807 target,
4808 detached_parent: source_parent,
4809 });
4810 }
4811
4812 let _ = touched.insert(source);
4813 let _ = touched.insert(target);
4814 let _ = touched.insert(source_parent);
4815
4816 let (removed_parent, sibling_id, grandparent_id) =
4817 self.promote_sibling_after_detach(source, touched)?;
4818 let _ = touched.insert(removed_parent);
4819 let _ = touched.insert(sibling_id);
4820 if let Some(grandparent_id) = grandparent_id {
4821 let _ = touched.insert(grandparent_id);
4822 }
4823
4824 if let Some(source_node) = self.nodes.get_mut(&source) {
4825 source_node.parent = None;
4826 }
4827
4828 if !self.nodes.contains_key(&target) {
4829 return Err(PaneOperationFailure::MissingNode { node_id: target });
4830 }
4831 let target_parent = self.nodes.get(&target).and_then(|node| node.parent);
4832 if let Some(parent_id) = target_parent {
4833 let _ = touched.insert(parent_id);
4834 }
4835
4836 let split_id = self.allocate_node_id()?;
4837 let _ = touched.insert(split_id);
4838 let (first, second) = placement.ordered(target, source);
4839
4840 if let Some(target_node) = self.nodes.get_mut(&target) {
4841 target_node.parent = Some(split_id);
4842 }
4843 if let Some(source_node) = self.nodes.get_mut(&source) {
4844 source_node.parent = Some(split_id);
4845 }
4846
4847 let _ = self.nodes.insert(
4848 split_id,
4849 PaneNodeRecord::split(
4850 split_id,
4851 target_parent,
4852 PaneSplit {
4853 axis,
4854 ratio,
4855 first,
4856 second,
4857 },
4858 ),
4859 );
4860
4861 if let Some(parent_id) = target_parent {
4862 self.replace_child(parent_id, target, split_id)?;
4863 } else {
4864 self.root = split_id;
4865 }
4866
4867 Ok(())
4868 }
4869
4870 fn apply_swap_nodes(
4871 &mut self,
4872 first: PaneId,
4873 second: PaneId,
4874 touched: &mut BTreeSet<PaneId>,
4875 ) -> Result<(), PaneOperationFailure> {
4876 if first == second {
4877 return Ok(());
4878 }
4879
4880 if !self.nodes.contains_key(&first) {
4881 return Err(PaneOperationFailure::MissingNode { node_id: first });
4882 }
4883 if !self.nodes.contains_key(&second) {
4884 return Err(PaneOperationFailure::MissingNode { node_id: second });
4885 }
4886 if self.is_ancestor(first, second)? {
4887 return Err(PaneOperationFailure::AncestorConflict {
4888 ancestor: first,
4889 descendant: second,
4890 });
4891 }
4892 if self.is_ancestor(second, first)? {
4893 return Err(PaneOperationFailure::AncestorConflict {
4894 ancestor: second,
4895 descendant: first,
4896 });
4897 }
4898
4899 let _ = touched.insert(first);
4900 let _ = touched.insert(second);
4901
4902 let first_parent = self.nodes.get(&first).and_then(|node| node.parent);
4903 let second_parent = self.nodes.get(&second).and_then(|node| node.parent);
4904
4905 if first_parent == second_parent {
4906 if let Some(parent_id) = first_parent {
4907 let _ = touched.insert(parent_id);
4908 self.swap_children(parent_id, first, second)?;
4909 }
4910 return Ok(());
4911 }
4912
4913 match (first_parent, second_parent) {
4914 (Some(left_parent), Some(right_parent)) => {
4915 let _ = touched.insert(left_parent);
4916 let _ = touched.insert(right_parent);
4917 self.replace_child(left_parent, first, second)?;
4918 self.replace_child(right_parent, second, first)?;
4919 if let Some(left) = self.nodes.get_mut(&first) {
4920 left.parent = Some(right_parent);
4921 }
4922 if let Some(right) = self.nodes.get_mut(&second) {
4923 right.parent = Some(left_parent);
4924 }
4925 }
4926 (None, Some(parent_id)) => {
4927 let _ = touched.insert(parent_id);
4928 self.replace_child(parent_id, second, first)?;
4929 if let Some(first_node) = self.nodes.get_mut(&first) {
4930 first_node.parent = Some(parent_id);
4931 }
4932 if let Some(second_node) = self.nodes.get_mut(&second) {
4933 second_node.parent = None;
4934 }
4935 self.root = second;
4936 }
4937 (Some(parent_id), None) => {
4938 let _ = touched.insert(parent_id);
4939 self.replace_child(parent_id, first, second)?;
4940 if let Some(first_node) = self.nodes.get_mut(&first) {
4941 first_node.parent = None;
4942 }
4943 if let Some(second_node) = self.nodes.get_mut(&second) {
4944 second_node.parent = Some(parent_id);
4945 }
4946 self.root = first;
4947 }
4948 (None, None) => {}
4949 }
4950
4951 Ok(())
4952 }
4953
4954 fn apply_normalize_ratios(
4955 &mut self,
4956 touched: &mut BTreeSet<PaneId>,
4957 ) -> Result<(), PaneOperationFailure> {
4958 for node in self.nodes.values_mut() {
4959 if let PaneNodeKind::Split(split) = &mut node.kind {
4960 let normalized =
4961 PaneSplitRatio::new(split.ratio.numerator(), split.ratio.denominator())
4962 .map_err(|_| PaneOperationFailure::InvalidRatio {
4963 node_id: node.id,
4964 numerator: split.ratio.numerator(),
4965 denominator: split.ratio.denominator(),
4966 })?;
4967 split.ratio = normalized;
4968 let _ = touched.insert(node.id);
4969 }
4970 }
4971 Ok(())
4972 }
4973
4974 fn apply_set_split_ratio(
4975 &mut self,
4976 split_id: PaneId,
4977 ratio: PaneSplitRatio,
4978 touched: &mut BTreeSet<PaneId>,
4979 ) -> Result<(), PaneOperationFailure> {
4980 let node = self
4981 .nodes
4982 .get_mut(&split_id)
4983 .ok_or(PaneOperationFailure::MissingNode { node_id: split_id })?;
4984 let PaneNodeKind::Split(split) = &mut node.kind else {
4985 return Err(PaneOperationFailure::ParentNotSplit { node_id: split_id });
4986 };
4987 split.ratio =
4988 PaneSplitRatio::new(ratio.numerator(), ratio.denominator()).map_err(|_| {
4989 PaneOperationFailure::InvalidRatio {
4990 node_id: split_id,
4991 numerator: ratio.numerator(),
4992 denominator: ratio.denominator(),
4993 }
4994 })?;
4995 let _ = touched.insert(split_id);
4996 Ok(())
4997 }
4998
4999 fn replace_child(
5000 &mut self,
5001 parent_id: PaneId,
5002 old_child: PaneId,
5003 new_child: PaneId,
5004 ) -> Result<(), PaneOperationFailure> {
5005 let parent = self
5006 .nodes
5007 .get_mut(&parent_id)
5008 .ok_or(PaneOperationFailure::MissingNode { node_id: parent_id })?;
5009 let PaneNodeKind::Split(split) = &mut parent.kind else {
5010 return Err(PaneOperationFailure::ParentNotSplit { node_id: parent_id });
5011 };
5012
5013 if split.first == old_child {
5014 split.first = new_child;
5015 return Ok(());
5016 }
5017 if split.second == old_child {
5018 split.second = new_child;
5019 return Ok(());
5020 }
5021
5022 Err(PaneOperationFailure::ParentChildMismatch {
5023 parent: parent_id,
5024 child: old_child,
5025 })
5026 }
5027
5028 fn swap_children(
5029 &mut self,
5030 parent_id: PaneId,
5031 left: PaneId,
5032 right: PaneId,
5033 ) -> Result<(), PaneOperationFailure> {
5034 let parent = self
5035 .nodes
5036 .get_mut(&parent_id)
5037 .ok_or(PaneOperationFailure::MissingNode { node_id: parent_id })?;
5038 let PaneNodeKind::Split(split) = &mut parent.kind else {
5039 return Err(PaneOperationFailure::ParentNotSplit { node_id: parent_id });
5040 };
5041
5042 let has_pair = (split.first == left && split.second == right)
5043 || (split.first == right && split.second == left);
5044 if !has_pair {
5045 return Err(PaneOperationFailure::ParentChildMismatch {
5046 parent: parent_id,
5047 child: left,
5048 });
5049 }
5050
5051 std::mem::swap(&mut split.first, &mut split.second);
5052 Ok(())
5053 }
5054
5055 fn promote_sibling_after_detach(
5056 &mut self,
5057 detached: PaneId,
5058 touched: &mut BTreeSet<PaneId>,
5059 ) -> Result<(PaneId, PaneId, Option<PaneId>), PaneOperationFailure> {
5060 let parent_id = self
5061 .nodes
5062 .get(&detached)
5063 .ok_or(PaneOperationFailure::MissingNode { node_id: detached })?
5064 .parent
5065 .ok_or(PaneOperationFailure::CannotMoveRoot { node_id: detached })?;
5066 let parent_node = self
5067 .nodes
5068 .get(&parent_id)
5069 .ok_or(PaneOperationFailure::MissingNode { node_id: parent_id })?;
5070 let PaneNodeKind::Split(parent_split) = &parent_node.kind else {
5071 return Err(PaneOperationFailure::ParentNotSplit { node_id: parent_id });
5072 };
5073
5074 let sibling_id = if parent_split.first == detached {
5075 parent_split.second
5076 } else if parent_split.second == detached {
5077 parent_split.first
5078 } else {
5079 return Err(PaneOperationFailure::ParentChildMismatch {
5080 parent: parent_id,
5081 child: detached,
5082 });
5083 };
5084
5085 let grandparent_id = parent_node.parent;
5086 let _ = touched.insert(parent_id);
5087 let _ = touched.insert(sibling_id);
5088 if let Some(grandparent_id) = grandparent_id {
5089 let _ = touched.insert(grandparent_id);
5090 self.replace_child(grandparent_id, parent_id, sibling_id)?;
5091 } else {
5092 self.root = sibling_id;
5093 }
5094
5095 let sibling_node =
5096 self.nodes
5097 .get_mut(&sibling_id)
5098 .ok_or(PaneOperationFailure::MissingNode {
5099 node_id: sibling_id,
5100 })?;
5101 sibling_node.parent = grandparent_id;
5102 let _ = self.nodes.remove(&parent_id);
5103
5104 Ok((parent_id, sibling_id, grandparent_id))
5105 }
5106
5107 fn is_ancestor(
5108 &self,
5109 ancestor: PaneId,
5110 mut node_id: PaneId,
5111 ) -> Result<bool, PaneOperationFailure> {
5112 loop {
5113 let node = self
5114 .nodes
5115 .get(&node_id)
5116 .ok_or(PaneOperationFailure::MissingNode { node_id })?;
5117 let Some(parent_id) = node.parent else {
5118 return Ok(false);
5119 };
5120 if parent_id == ancestor {
5121 return Ok(true);
5122 }
5123 node_id = parent_id;
5124 }
5125 }
5126
5127 fn collect_subtree_ids(&self, root_id: PaneId) -> Result<Vec<PaneId>, PaneOperationFailure> {
5128 if !self.nodes.contains_key(&root_id) {
5129 return Err(PaneOperationFailure::MissingNode { node_id: root_id });
5130 }
5131
5132 let mut out = Vec::new();
5133 let mut stack = vec![root_id];
5134 while let Some(node_id) = stack.pop() {
5135 let node = self
5136 .nodes
5137 .get(&node_id)
5138 .ok_or(PaneOperationFailure::MissingNode { node_id })?;
5139 out.push(node_id);
5140 if let PaneNodeKind::Split(split) = &node.kind {
5141 stack.push(split.first);
5142 stack.push(split.second);
5143 }
5144 }
5145 Ok(out)
5146 }
5147
5148 fn allocate_node_id(&mut self) -> Result<PaneId, PaneOperationFailure> {
5149 let current = self.next_id;
5150 self.next_id = self
5151 .next_id
5152 .checked_next()
5153 .map_err(|_| PaneOperationFailure::PaneIdOverflow { current })?;
5154 Ok(current)
5155 }
5156
5157 pub fn solve_layout(&self, area: Rect) -> Result<PaneLayout, PaneModelError> {
5169 let mut bounds = BTreeMap::new();
5170 self.subtree_constraints(self.root, &mut bounds)?;
5171 let mut rects = BTreeMap::new();
5172 self.solve_node(self.root, area, &bounds, &mut rects)?;
5173 Ok(PaneLayout { area, rects })
5174 }
5175
5176 fn subtree_constraints(
5177 &self,
5178 node_id: PaneId,
5179 bounds: &mut BTreeMap<PaneId, PaneConstraints>,
5180 ) -> Result<PaneConstraints, PaneModelError> {
5181 let node = self
5182 .nodes
5183 .get(&node_id)
5184 .ok_or(PaneModelError::MissingRoot { root: node_id })?;
5185 let mut constraints = node.constraints;
5186 if let PaneNodeKind::Split(split) = &node.kind {
5187 for child in [split.first, split.second] {
5188 if !self.nodes.contains_key(&child) {
5189 return Err(PaneModelError::MissingChild {
5190 parent: node_id,
5191 child,
5192 });
5193 }
5194 }
5195 let first = self.subtree_constraints(split.first, bounds)?;
5196 let second = self.subtree_constraints(split.second, bounds)?;
5197 let width = subtree_axis_bounds(
5198 node_id,
5199 SplitAxis::Horizontal,
5200 split.axis,
5201 constraints,
5202 first,
5203 second,
5204 )?;
5205 let height = subtree_axis_bounds(
5206 node_id,
5207 SplitAxis::Vertical,
5208 split.axis,
5209 constraints,
5210 first,
5211 second,
5212 )?;
5213 constraints.min_width = width.min;
5214 constraints.max_width = width.max;
5215 constraints.min_height = height.min;
5216 constraints.max_height = height.max;
5217 }
5218 bounds.insert(node_id, constraints);
5219 Ok(constraints)
5220 }
5221
5222 fn solve_node(
5223 &self,
5224 node_id: PaneId,
5225 area: Rect,
5226 bounds: &BTreeMap<PaneId, PaneConstraints>,
5227 rects: &mut BTreeMap<PaneId, Rect>,
5228 ) -> Result<(), PaneModelError> {
5229 let Some(node) = self.nodes.get(&node_id) else {
5230 return Err(PaneModelError::MissingRoot { root: node_id });
5231 };
5232
5233 validate_area_against_constraints(node_id, area, node.constraints)?;
5234 let _ = rects.insert(node_id, area);
5235
5236 let PaneNodeKind::Split(split) = &node.kind else {
5237 return Ok(());
5238 };
5239
5240 let first_constraints = bounds
5241 .get(&split.first)
5242 .ok_or(PaneModelError::MissingChild {
5243 parent: node_id,
5244 child: split.first,
5245 })?;
5246 let second_constraints = bounds
5247 .get(&split.second)
5248 .ok_or(PaneModelError::MissingChild {
5249 parent: node_id,
5250 child: split.second,
5251 })?;
5252
5253 let available = match split.axis {
5254 SplitAxis::Horizontal => area.width,
5255 SplitAxis::Vertical => area.height,
5256 };
5257
5258 let (first_size, second_size) = solve_split_sizes(
5259 node_id,
5260 split.axis,
5261 available,
5262 split.ratio,
5263 axis_bounds(*first_constraints, split.axis),
5264 axis_bounds(*second_constraints, split.axis),
5265 )?;
5266
5267 let (first_rect, second_rect) = match split.axis {
5268 SplitAxis::Horizontal => (
5269 Rect::new(area.x, area.y, first_size, area.height),
5270 Rect::new(
5271 area.x.saturating_add(first_size),
5272 area.y,
5273 second_size,
5274 area.height,
5275 ),
5276 ),
5277 SplitAxis::Vertical => (
5278 Rect::new(area.x, area.y, area.width, first_size),
5279 Rect::new(
5280 area.x,
5281 area.y.saturating_add(first_size),
5282 area.width,
5283 second_size,
5284 ),
5285 ),
5286 };
5287
5288 self.solve_node(split.first, first_rect, bounds, rects)?;
5289 self.solve_node(split.second, second_rect, bounds, rects)?;
5290 Ok(())
5291 }
5292
5293 #[must_use]
5295 pub fn choose_dock_preview(
5296 &self,
5297 layout: &PaneLayout,
5298 pointer: PanePointerPosition,
5299 magnetic_field_cells: f64,
5300 ) -> Option<PaneDockPreview> {
5301 self.choose_dock_preview_excluding(layout, pointer, magnetic_field_cells, None)
5302 }
5303
5304 #[must_use]
5307 pub fn ranked_dock_previews_with_motion(
5308 &self,
5309 layout: &PaneLayout,
5310 pointer: PanePointerPosition,
5311 motion: PaneMotionVector,
5312 magnetic_field_cells: f64,
5313 excluded: Option<PaneId>,
5314 limit: usize,
5315 ) -> Vec<PaneDockPreview> {
5316 self.collect_dock_previews_excluding_with_motion(
5317 layout,
5318 pointer,
5319 magnetic_field_cells,
5320 excluded,
5321 motion,
5322 limit,
5323 )
5324 }
5325
5326 pub fn plan_reflow_move_with_preview(
5329 &self,
5330 source: PaneId,
5331 layout: &PaneLayout,
5332 pointer: PanePointerPosition,
5333 motion: PaneMotionVector,
5334 inertial: Option<PaneInertialThrow>,
5335 magnetic_field_cells: f64,
5336 ) -> Result<PaneReflowMovePlan, PaneReflowPlanError> {
5337 if !self.nodes.contains_key(&source) {
5338 return Err(PaneReflowPlanError::MissingSource { source });
5339 }
5340 if source == self.root {
5341 return Err(PaneReflowPlanError::SourceCannotMoveRoot { source });
5342 }
5343
5344 let projected = inertial
5345 .map(|profile| profile.projected_pointer(pointer))
5346 .unwrap_or(pointer);
5347 let preview = self
5348 .choose_dock_preview_excluding_with_motion(
5349 layout,
5350 projected,
5351 magnetic_field_cells,
5352 Some(source),
5353 motion,
5354 )
5355 .ok_or(PaneReflowPlanError::NoDockTarget)?;
5356
5357 let snap_profile = PanePressureSnapProfile::from_motion(motion);
5358 let magnetic_boost = (preview.score * 1_800.0).round().clamp(0.0, 1_800.0) as u16;
5359 let incoming_share_bps = snap_profile
5360 .strength_bps
5361 .saturating_sub(2_200)
5362 .saturating_add(magnetic_boost / 2)
5363 .clamp(2_400, 7_800);
5364
5365 let operations = if preview.zone == PaneDockZone::Center {
5366 vec![PaneOperation::SwapNodes {
5367 first: source,
5368 second: preview.target,
5369 }]
5370 } else {
5371 let (axis, placement, target_first_share) =
5372 zone_to_axis_placement_and_target_share(preview.zone, incoming_share_bps);
5373 let ratio = PaneSplitRatio::new(
5374 u32::from(target_first_share.max(1)),
5375 u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5376 )
5377 .map_err(|_| PaneReflowPlanError::InvalidRatio {
5378 numerator: u32::from(target_first_share.max(1)),
5379 denominator: u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5380 })?;
5381 vec![PaneOperation::MoveSubtree {
5382 source,
5383 target: preview.target,
5384 axis,
5385 ratio,
5386 placement,
5387 }]
5388 };
5389
5390 Ok(PaneReflowMovePlan {
5391 source,
5392 pointer,
5393 projected_pointer: projected,
5394 preview,
5395 snap_profile,
5396 operations,
5397 })
5398 }
5399
5400 pub fn apply_reflow_move_plan(
5402 &mut self,
5403 operation_seed: u64,
5404 plan: &PaneReflowMovePlan,
5405 ) -> Result<Vec<PaneOperationOutcome>, PaneOperationError> {
5406 let mut outcomes = Vec::with_capacity(plan.operations.len());
5407 for (index, operation) in plan.operations.iter().cloned().enumerate() {
5408 let outcome =
5409 self.apply_operation(operation_seed.saturating_add(index as u64), operation)?;
5410 outcomes.push(outcome);
5411 }
5412 Ok(outcomes)
5413 }
5414
5415 pub fn plan_edge_resize(
5417 &self,
5418 leaf: PaneId,
5419 layout: &PaneLayout,
5420 grip: PaneResizeGrip,
5421 pointer: PanePointerPosition,
5422 pressure: PanePressureSnapProfile,
5423 ) -> Result<PaneEdgeResizePlan, PaneEdgeResizePlanError> {
5424 let node = self
5425 .nodes
5426 .get(&leaf)
5427 .ok_or(PaneEdgeResizePlanError::MissingLeaf { leaf })?;
5428 if !matches!(node.kind, PaneNodeKind::Leaf(_)) {
5429 return Err(PaneEdgeResizePlanError::NodeNotLeaf { node: leaf });
5430 }
5431
5432 let tuned_snap = pressure.apply_to_tuning(PaneSnapTuning::default());
5433 let mut operations = Vec::with_capacity(2);
5434
5435 if let Some(_toward_max) = grip.horizontal_edge() {
5436 let split_id = self
5437 .nearest_axis_split_for_node(leaf, SplitAxis::Horizontal)
5438 .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5439 leaf,
5440 axis: SplitAxis::Horizontal,
5441 })?;
5442 let split_rect = layout
5443 .rect(split_id)
5444 .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5445 let share = axis_share_from_pointer(
5446 split_rect,
5447 pointer,
5448 SplitAxis::Horizontal,
5449 PANE_EDGE_GRIP_INSET_CELLS,
5450 );
5451 let raw_bps = elastic_ratio_bps(
5452 (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5453 pressure,
5454 );
5455 let snapped = tuned_snap
5456 .decide(raw_bps, None)
5457 .snapped_ratio_bps
5458 .unwrap_or(raw_bps);
5459 let ratio = PaneSplitRatio::new(
5460 u32::from(snapped.max(1)),
5461 u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5462 )
5463 .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5464 numerator: u32::from(snapped.max(1)),
5465 denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5466 })?;
5467 operations.push(PaneOperation::SetSplitRatio {
5468 split: split_id,
5469 ratio,
5470 });
5471 }
5472
5473 if let Some(_toward_max) = grip.vertical_edge() {
5474 let split_id = self
5475 .nearest_axis_split_for_node(leaf, SplitAxis::Vertical)
5476 .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5477 leaf,
5478 axis: SplitAxis::Vertical,
5479 })?;
5480 let split_rect = layout
5481 .rect(split_id)
5482 .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5483 let share = axis_share_from_pointer(
5484 split_rect,
5485 pointer,
5486 SplitAxis::Vertical,
5487 PANE_EDGE_GRIP_INSET_CELLS,
5488 );
5489 let raw_bps = elastic_ratio_bps(
5490 (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5491 pressure,
5492 );
5493 let snapped = tuned_snap
5494 .decide(raw_bps, None)
5495 .snapped_ratio_bps
5496 .unwrap_or(raw_bps);
5497 let ratio = PaneSplitRatio::new(
5498 u32::from(snapped.max(1)),
5499 u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5500 )
5501 .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5502 numerator: u32::from(snapped.max(1)),
5503 denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5504 })?;
5505 operations.push(PaneOperation::SetSplitRatio {
5506 split: split_id,
5507 ratio,
5508 });
5509 }
5510
5511 Ok(PaneEdgeResizePlan {
5512 leaf,
5513 grip,
5514 operations,
5515 })
5516 }
5517
5518 pub fn apply_edge_resize_plan(
5520 &mut self,
5521 operation_seed: u64,
5522 plan: &PaneEdgeResizePlan,
5523 ) -> Result<Vec<PaneOperationOutcome>, PaneOperationError> {
5524 let mut outcomes = Vec::with_capacity(plan.operations.len());
5525 for (index, operation) in plan.operations.iter().cloned().enumerate() {
5526 outcomes.push(
5527 self.apply_operation(operation_seed.saturating_add(index as u64), operation)?,
5528 );
5529 }
5530 Ok(outcomes)
5531 }
5532
5533 fn ratio_from_first_share_bps(
5538 first_share_bps: u16,
5539 ) -> Result<PaneSplitRatio, PaneSplitterResizePlanError> {
5540 let first = first_share_bps.clamp(1, 9_999);
5541 let numerator = u32::from(first);
5542 let denominator = u32::from(10_000_u16 - first);
5543 PaneSplitRatio::new(numerator, denominator).map_err(|_| {
5544 PaneSplitterResizePlanError::InvalidRatio {
5545 numerator,
5546 denominator,
5547 }
5548 })
5549 }
5550
5551 fn resolve_splitter_target(
5553 &self,
5554 target: PaneResizeTarget,
5555 ) -> Result<&PaneSplit, PaneSplitterResizePlanError> {
5556 let node =
5557 self.nodes
5558 .get(&target.split_id)
5559 .ok_or(PaneSplitterResizePlanError::MissingSplit {
5560 split: target.split_id,
5561 })?;
5562 let PaneNodeKind::Split(split) = &node.kind else {
5563 return Err(PaneSplitterResizePlanError::NotASplit {
5564 node: target.split_id,
5565 });
5566 };
5567 if split.axis != target.axis {
5568 return Err(PaneSplitterResizePlanError::AxisMismatch {
5569 split: target.split_id,
5570 expected: target.axis,
5571 actual: split.axis,
5572 });
5573 }
5574 Ok(split)
5575 }
5576
5577 pub fn plan_splitter_resize(
5588 &self,
5589 target: PaneResizeTarget,
5590 layout: &PaneLayout,
5591 pointer: PanePointerPosition,
5592 pressure: PanePressureSnapProfile,
5593 ) -> Result<PaneOperation, PaneSplitterResizePlanError> {
5594 self.resolve_splitter_target(target)?;
5595 let split_rect =
5596 layout
5597 .rect(target.split_id)
5598 .ok_or(PaneSplitterResizePlanError::MissingLayoutRect {
5599 node: target.split_id,
5600 })?;
5601 let share =
5602 axis_share_from_pointer(split_rect, pointer, target.axis, PANE_EDGE_GRIP_INSET_CELLS);
5603 let raw_bps = elastic_ratio_bps(
5604 (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5605 pressure,
5606 );
5607 let snapped = pressure
5608 .apply_to_tuning(PaneSnapTuning::default())
5609 .decide(raw_bps, None)
5610 .snapped_ratio_bps
5611 .unwrap_or(raw_bps);
5612 let ratio = Self::ratio_from_first_share_bps(snapped)?;
5613 Ok(PaneOperation::SetSplitRatio {
5614 split: target.split_id,
5615 ratio,
5616 })
5617 }
5618
5619 pub fn plan_splitter_nudge(
5627 &self,
5628 target: PaneResizeTarget,
5629 delta_bps: i32,
5630 ) -> Result<PaneOperation, PaneSplitterResizePlanError> {
5631 let split = self.resolve_splitter_target(target)?;
5632 let total = u64::from(split.ratio.numerator()) + u64::from(split.ratio.denominator());
5633 let current_bps = ((u64::from(split.ratio.numerator()) * 10_000) / total) as i32;
5634 let next_bps = current_bps.saturating_add(delta_bps).clamp(1, 9_999) as u16;
5635 let ratio = Self::ratio_from_first_share_bps(next_bps)?;
5636 Ok(PaneOperation::SetSplitRatio {
5637 split: target.split_id,
5638 ratio,
5639 })
5640 }
5641
5642 #[must_use]
5662 pub fn operations_for_transition(
5663 &self,
5664 transition: &PaneDragResizeTransition,
5665 layout: &PaneLayout,
5666 pressure: PanePressureSnapProfile,
5667 ) -> Vec<PaneOperation> {
5668 let planned = match transition.effect {
5669 PaneDragResizeEffect::DragStarted {
5670 target, current, ..
5671 }
5672 | PaneDragResizeEffect::DragUpdated {
5673 target, current, ..
5674 } => self.plan_splitter_resize(target, layout, current, pressure),
5675 PaneDragResizeEffect::Committed { target, end, .. } => {
5676 self.plan_splitter_resize(target, layout, end, pressure)
5677 }
5678 PaneDragResizeEffect::KeyboardApplied {
5679 target,
5680 direction,
5681 units,
5682 } => {
5683 let magnitude = i32::from(units) * i32::from(PANE_SNAP_DEFAULT_STEP_BPS);
5684 let delta_bps = match direction {
5685 PaneResizeDirection::Increase => magnitude,
5686 PaneResizeDirection::Decrease => -magnitude,
5687 };
5688 self.plan_splitter_nudge(target, delta_bps)
5689 }
5690 PaneDragResizeEffect::WheelApplied { target, lines } => {
5691 let delta_bps = i32::from(lines) * i32::from(PANE_SNAP_DEFAULT_STEP_BPS);
5692 self.plan_splitter_nudge(target, delta_bps)
5693 }
5694 PaneDragResizeEffect::Armed { .. }
5695 | PaneDragResizeEffect::Canceled { .. }
5696 | PaneDragResizeEffect::Noop { .. } => return Vec::new(),
5697 };
5698 planned.into_iter().collect()
5699 }
5700
5701 pub fn plan_group_move(
5703 &self,
5704 selection: &PaneSelectionState,
5705 layout: &PaneLayout,
5706 pointer: PanePointerPosition,
5707 motion: PaneMotionVector,
5708 inertial: Option<PaneInertialThrow>,
5709 magnetic_field_cells: f64,
5710 ) -> Result<PaneGroupTransformPlan, PaneReflowPlanError> {
5711 if selection.is_empty() {
5712 return Ok(PaneGroupTransformPlan {
5713 members: Vec::new(),
5714 operations: Vec::new(),
5715 });
5716 }
5717 let members = selection.as_sorted_vec();
5718 let anchor = selection.anchor.unwrap_or(members[0]);
5719 let reflow = self.plan_reflow_move_with_preview(
5720 anchor,
5721 layout,
5722 pointer,
5723 motion,
5724 inertial,
5725 magnetic_field_cells,
5726 )?;
5727 let mut operations = reflow.operations.clone();
5728 if members.len() > 1 {
5729 let (axis, placement, target_first_share) =
5730 zone_to_axis_placement_and_target_share(reflow.preview.zone, 5_000);
5731 let ratio = PaneSplitRatio::new(
5732 u32::from(target_first_share.max(1)),
5733 u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5734 )
5735 .map_err(|_| PaneReflowPlanError::InvalidRatio {
5736 numerator: u32::from(target_first_share.max(1)),
5737 denominator: u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5738 })?;
5739 for member in members.iter().copied().filter(|member| *member != anchor) {
5740 operations.push(PaneOperation::MoveSubtree {
5741 source: member,
5742 target: anchor,
5743 axis,
5744 ratio,
5745 placement,
5746 });
5747 }
5748 }
5749 Ok(PaneGroupTransformPlan {
5750 members,
5751 operations,
5752 })
5753 }
5754
5755 pub fn plan_group_resize(
5758 &self,
5759 selection: &PaneSelectionState,
5760 layout: &PaneLayout,
5761 grip: PaneResizeGrip,
5762 pointer: PanePointerPosition,
5763 pressure: PanePressureSnapProfile,
5764 ) -> Result<PaneGroupTransformPlan, PaneEdgeResizePlanError> {
5765 if selection.is_empty() {
5766 return Ok(PaneGroupTransformPlan {
5767 members: Vec::new(),
5768 operations: Vec::new(),
5769 });
5770 }
5771 let members = selection.as_sorted_vec();
5772 let cluster_root = self
5773 .lowest_common_ancestor(&members)
5774 .unwrap_or_else(|| selection.anchor.unwrap_or(members[0]));
5775 let proxy_leaf = selection.anchor.unwrap_or(members[0]);
5776
5777 let tuned_snap = pressure.apply_to_tuning(PaneSnapTuning::default());
5778 let mut operations = Vec::with_capacity(2);
5779
5780 if grip.horizontal_edge().is_some() {
5781 let split_id = self
5782 .nearest_axis_split_for_node(cluster_root, SplitAxis::Horizontal)
5783 .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5784 leaf: proxy_leaf,
5785 axis: SplitAxis::Horizontal,
5786 })?;
5787 let split_rect = layout
5788 .rect(split_id)
5789 .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5790 let share = axis_share_from_pointer(
5791 split_rect,
5792 pointer,
5793 SplitAxis::Horizontal,
5794 PANE_EDGE_GRIP_INSET_CELLS,
5795 );
5796 let raw_bps = elastic_ratio_bps(
5797 (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5798 pressure,
5799 );
5800 let snapped = tuned_snap
5801 .decide(raw_bps, None)
5802 .snapped_ratio_bps
5803 .unwrap_or(raw_bps);
5804 let ratio = PaneSplitRatio::new(
5805 u32::from(snapped.max(1)),
5806 u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5807 )
5808 .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5809 numerator: u32::from(snapped.max(1)),
5810 denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5811 })?;
5812 operations.push(PaneOperation::SetSplitRatio {
5813 split: split_id,
5814 ratio,
5815 });
5816 }
5817
5818 if grip.vertical_edge().is_some() {
5819 let split_id = self
5820 .nearest_axis_split_for_node(cluster_root, SplitAxis::Vertical)
5821 .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5822 leaf: proxy_leaf,
5823 axis: SplitAxis::Vertical,
5824 })?;
5825 let split_rect = layout
5826 .rect(split_id)
5827 .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5828 let share = axis_share_from_pointer(
5829 split_rect,
5830 pointer,
5831 SplitAxis::Vertical,
5832 PANE_EDGE_GRIP_INSET_CELLS,
5833 );
5834 let raw_bps = elastic_ratio_bps(
5835 (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5836 pressure,
5837 );
5838 let snapped = tuned_snap
5839 .decide(raw_bps, None)
5840 .snapped_ratio_bps
5841 .unwrap_or(raw_bps);
5842 let ratio = PaneSplitRatio::new(
5843 u32::from(snapped.max(1)),
5844 u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5845 )
5846 .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5847 numerator: u32::from(snapped.max(1)),
5848 denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5849 })?;
5850 operations.push(PaneOperation::SetSplitRatio {
5851 split: split_id,
5852 ratio,
5853 });
5854 }
5855
5856 Ok(PaneGroupTransformPlan {
5857 members,
5858 operations,
5859 })
5860 }
5861
5862 pub fn apply_group_transform_plan(
5864 &mut self,
5865 operation_seed: u64,
5866 plan: &PaneGroupTransformPlan,
5867 ) -> Result<Vec<PaneOperationOutcome>, PaneOperationError> {
5868 let mut outcomes = Vec::with_capacity(plan.operations.len());
5869 for (index, operation) in plan.operations.iter().cloned().enumerate() {
5870 outcomes.push(
5871 self.apply_operation(operation_seed.saturating_add(index as u64), operation)?,
5872 );
5873 }
5874 Ok(outcomes)
5875 }
5876
5877 pub fn plan_intelligence_mode(
5879 &self,
5880 mode: PaneLayoutIntelligenceMode,
5881 primary: PaneId,
5882 ) -> Result<Vec<PaneOperation>, PaneReflowPlanError> {
5883 if !self.nodes.contains_key(&primary) {
5884 return Err(PaneReflowPlanError::MissingSource { source: primary });
5885 }
5886 let mut leaves = self
5887 .nodes
5888 .values()
5889 .filter_map(|node| matches!(node.kind, PaneNodeKind::Leaf(_)).then_some(node.id))
5890 .collect::<Vec<_>>();
5891 leaves.sort_unstable();
5892 let secondary = leaves.iter().copied().find(|leaf| *leaf != primary);
5893
5894 let focused_ratio =
5895 PaneSplitRatio::new(7, 3).map_err(|_| PaneReflowPlanError::InvalidRatio {
5896 numerator: 7,
5897 denominator: 3,
5898 })?;
5899 let balanced_ratio =
5900 PaneSplitRatio::new(1, 1).map_err(|_| PaneReflowPlanError::InvalidRatio {
5901 numerator: 1,
5902 denominator: 1,
5903 })?;
5904 let monitor_ratio =
5905 PaneSplitRatio::new(2, 1).map_err(|_| PaneReflowPlanError::InvalidRatio {
5906 numerator: 2,
5907 denominator: 1,
5908 })?;
5909
5910 let mut operations = Vec::new();
5911 match mode {
5912 PaneLayoutIntelligenceMode::Focus => {
5913 if primary != self.root {
5914 operations.push(PaneOperation::MoveSubtree {
5915 source: primary,
5916 target: self.root,
5917 axis: SplitAxis::Horizontal,
5918 ratio: focused_ratio,
5919 placement: PanePlacement::IncomingFirst,
5920 });
5921 }
5922 }
5923 PaneLayoutIntelligenceMode::Compare => {
5924 if let Some(other) = secondary
5925 && other != primary
5926 {
5927 operations.push(PaneOperation::MoveSubtree {
5928 source: primary,
5929 target: other,
5930 axis: SplitAxis::Horizontal,
5931 ratio: balanced_ratio,
5932 placement: PanePlacement::IncomingFirst,
5933 });
5934 }
5935 }
5936 PaneLayoutIntelligenceMode::Monitor => {
5937 if primary != self.root {
5938 operations.push(PaneOperation::MoveSubtree {
5939 source: primary,
5940 target: self.root,
5941 axis: SplitAxis::Vertical,
5942 ratio: monitor_ratio,
5943 placement: PanePlacement::IncomingFirst,
5944 });
5945 }
5946 }
5947 PaneLayoutIntelligenceMode::Compact => {
5948 for node in self.nodes.values() {
5949 if matches!(node.kind, PaneNodeKind::Split(_)) {
5950 operations.push(PaneOperation::SetSplitRatio {
5951 split: node.id,
5952 ratio: balanced_ratio,
5953 });
5954 }
5955 }
5956 operations.push(PaneOperation::NormalizeRatios);
5957 }
5958 }
5959 Ok(operations)
5960 }
5961
5962 fn choose_dock_preview_excluding(
5963 &self,
5964 layout: &PaneLayout,
5965 pointer: PanePointerPosition,
5966 magnetic_field_cells: f64,
5967 excluded: Option<PaneId>,
5968 ) -> Option<PaneDockPreview> {
5969 let mut best: Option<PaneDockPreview> = None;
5970 for node in self.nodes.values() {
5971 if !matches!(node.kind, PaneNodeKind::Leaf(_)) {
5972 continue;
5973 }
5974 if excluded == Some(node.id) {
5975 continue;
5976 }
5977 let Some(rect) = layout.rect(node.id) else {
5978 continue;
5979 };
5980 let Some(candidate) =
5981 dock_preview_for_rect(node.id, rect, pointer, magnetic_field_cells)
5982 else {
5983 continue;
5984 };
5985 match best {
5986 Some(current)
5987 if candidate.score < current.score
5988 || (candidate.score == current.score
5989 && candidate.target > current.target) => {}
5990 _ => best = Some(candidate),
5991 }
5992 }
5993 best
5994 }
5995
5996 fn choose_dock_preview_excluding_with_motion(
5997 &self,
5998 layout: &PaneLayout,
5999 pointer: PanePointerPosition,
6000 magnetic_field_cells: f64,
6001 excluded: Option<PaneId>,
6002 motion: PaneMotionVector,
6003 ) -> Option<PaneDockPreview> {
6004 self.collect_dock_previews_excluding_with_motion(
6005 layout,
6006 pointer,
6007 magnetic_field_cells,
6008 excluded,
6009 motion,
6010 1,
6011 )
6012 .into_iter()
6013 .next()
6014 }
6015
6016 fn collect_dock_previews_excluding_with_motion(
6017 &self,
6018 layout: &PaneLayout,
6019 pointer: PanePointerPosition,
6020 magnetic_field_cells: f64,
6021 excluded: Option<PaneId>,
6022 motion: PaneMotionVector,
6023 limit: usize,
6024 ) -> Vec<PaneDockPreview> {
6025 let limit = limit.max(1);
6026 let mut candidates = Vec::new();
6027 for node in self.nodes.values() {
6028 if !matches!(node.kind, PaneNodeKind::Leaf(_)) {
6029 continue;
6030 }
6031 if excluded == Some(node.id) {
6032 continue;
6033 }
6034 let Some(rect) = layout.rect(node.id) else {
6035 continue;
6036 };
6037 let Some(candidate) = dock_preview_for_rect_with_motion(
6038 node.id,
6039 rect,
6040 pointer,
6041 magnetic_field_cells,
6042 motion,
6043 ) else {
6044 continue;
6045 };
6046 candidates.push(candidate);
6047 }
6048 candidates.sort_by(|left, right| {
6049 right
6050 .score
6051 .total_cmp(&left.score)
6052 .then_with(|| left.target.cmp(&right.target))
6053 .then_with(|| dock_zone_rank(left.zone).cmp(&dock_zone_rank(right.zone)))
6054 });
6055 if candidates.len() > limit {
6056 candidates.truncate(limit);
6057 }
6058 candidates
6059 }
6060
6061 fn nearest_axis_split_for_node(&self, node: PaneId, axis: SplitAxis) -> Option<PaneId> {
6062 let mut cursor = Some(node);
6063 while let Some(node_id) = cursor {
6064 let parent = self.nodes.get(&node_id).and_then(|record| record.parent)?;
6065 let parent_record = self.nodes.get(&parent)?;
6066 if let PaneNodeKind::Split(split) = &parent_record.kind
6067 && split.axis == axis
6068 {
6069 return Some(parent);
6070 }
6071 cursor = Some(parent);
6072 }
6073 None
6074 }
6075
6076 fn lowest_common_ancestor(&self, nodes: &[PaneId]) -> Option<PaneId> {
6077 if nodes.is_empty() {
6078 return None;
6079 }
6080 let mut ancestor_paths = nodes
6081 .iter()
6082 .map(|node_id| self.ancestor_chain(*node_id))
6083 .collect::<Option<Vec<_>>>()?;
6084 let first = ancestor_paths.remove(0);
6085 first
6086 .into_iter()
6087 .find(|candidate| ancestor_paths.iter().all(|path| path.contains(candidate)))
6088 }
6089
6090 fn ancestor_chain(&self, node: PaneId) -> Option<Vec<PaneId>> {
6091 let mut out = Vec::new();
6092 let mut cursor = Some(node);
6093 while let Some(node_id) = cursor {
6094 if !self.nodes.contains_key(&node_id) {
6095 return None;
6096 }
6097 out.push(node_id);
6098 cursor = self.nodes.get(&node_id).and_then(|record| record.parent);
6099 }
6100 Some(out)
6101 }
6102}
6103
6104impl PaneInteractionTimeline {
6105 #[must_use]
6107 pub fn with_baseline(tree: &PaneTree) -> Self {
6108 Self {
6109 baseline: Some(tree.to_snapshot()),
6110 entries: Vec::new(),
6111 cursor: 0,
6112 checkpoints: Vec::new(),
6113 checkpoint_interval: DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL,
6114 max_entries: DEFAULT_PANE_TIMELINE_MAX_ENTRIES,
6115 }
6116 }
6117
6118 #[must_use]
6120 pub fn with_max_entries(mut self, max_entries: usize) -> Self {
6121 self.max_entries = max_entries;
6122 self
6123 }
6124
6125 pub fn set_max_entries(&mut self, max_entries: usize) -> usize {
6135 let before = self.entries.len();
6136 self.max_entries = max_entries;
6137 self.enforce_entry_limit();
6138 before.saturating_sub(self.entries.len())
6139 }
6140
6141 #[must_use]
6143 pub const fn applied_len(&self) -> usize {
6144 self.cursor
6145 }
6146
6147 #[must_use]
6149 pub fn next_operation_id(&self) -> u64 {
6150 self.entries
6151 .iter()
6152 .map(|entry| entry.operation_id)
6153 .max()
6154 .unwrap_or(0)
6155 .saturating_add(1)
6156 .max(1)
6157 }
6158
6159 #[must_use]
6161 pub fn replay_diagnostics(&self) -> PaneInteractionTimelineReplayDiagnostics {
6162 let replay_start_idx = self
6163 .checkpoints
6164 .iter()
6165 .rev()
6166 .find(|checkpoint| checkpoint.applied_len <= self.cursor)
6167 .map_or(0, |checkpoint| checkpoint.applied_len);
6168
6169 PaneInteractionTimelineReplayDiagnostics {
6170 entry_count: self.entries.len(),
6171 cursor: self.cursor,
6172 checkpoint_count: self.checkpoints.len(),
6173 checkpoint_interval: self.checkpoint_interval,
6174 checkpoint_hit: replay_start_idx != 0,
6175 replay_start_idx,
6176 replay_depth: self.cursor.saturating_sub(replay_start_idx),
6177 }
6178 }
6179
6180 #[must_use]
6182 pub fn retention_diagnostics(&self) -> PaneInteractionTimelineRetentionDiagnostics {
6183 let mut snapshot_stats = PaneTimelineSnapshotRetentionStats::default();
6184 let baseline_present = self.baseline.is_some();
6185 if let Some(baseline) = &self.baseline {
6186 snapshot_stats.add_snapshot(baseline);
6187 }
6188 for checkpoint in &self.checkpoints {
6189 snapshot_stats.add_snapshot(&checkpoint.snapshot);
6190 }
6191
6192 let retained_operation_payload_bytes = self
6193 .entries
6194 .iter()
6195 .map(|entry| pane_operation_retained_payload_bytes(&entry.operation))
6196 .sum::<usize>();
6197 let estimated_entry_struct_bytes = self
6198 .entries
6199 .len()
6200 .saturating_mul(std::mem::size_of::<PaneInteractionTimelineEntry>());
6201 let estimated_checkpoint_struct_bytes = self
6202 .checkpoints
6203 .len()
6204 .saturating_mul(std::mem::size_of::<PaneInteractionTimelineCheckpoint>());
6205 let estimated_snapshot_struct_bytes = snapshot_stats
6206 .snapshot_count
6207 .saturating_mul(std::mem::size_of::<PaneTreeSnapshot>())
6208 .saturating_add(
6209 snapshot_stats
6210 .node_count
6211 .saturating_mul(std::mem::size_of::<PaneNodeRecord>()),
6212 );
6213 let estimated_total_retained_bytes = std::mem::size_of::<Self>()
6214 .saturating_add(estimated_entry_struct_bytes)
6215 .saturating_add(estimated_checkpoint_struct_bytes)
6216 .saturating_add(estimated_snapshot_struct_bytes)
6217 .saturating_add(snapshot_stats.leaf_payload_bytes)
6218 .saturating_add(snapshot_stats.extension_payload_bytes)
6219 .saturating_add(retained_operation_payload_bytes);
6220
6221 PaneInteractionTimelineRetentionDiagnostics {
6222 entry_count: self.entries.len(),
6223 cursor: self.cursor,
6224 redo_entry_count: self.entries.len().saturating_sub(self.cursor),
6225 checkpoint_count: self.checkpoints.len(),
6226 checkpoint_interval: self.checkpoint_interval,
6227 max_entries: self.max_entries,
6228 baseline_present,
6229 retained_snapshot_count: snapshot_stats.snapshot_count,
6230 baseline_node_count: self
6231 .baseline
6232 .as_ref()
6233 .map_or(0, |snapshot| snapshot.nodes.len()),
6234 checkpoint_node_count: self
6235 .checkpoints
6236 .iter()
6237 .map(|checkpoint| checkpoint.snapshot.nodes.len())
6238 .sum(),
6239 retained_snapshot_node_count: snapshot_stats.node_count,
6240 retained_leaf_payload_bytes: snapshot_stats.leaf_payload_bytes,
6241 retained_extension_entry_count: snapshot_stats.extension_entry_count,
6242 retained_extension_payload_bytes: snapshot_stats.extension_payload_bytes,
6243 retained_operation_payload_bytes,
6244 estimated_entry_struct_bytes,
6245 estimated_checkpoint_struct_bytes,
6246 estimated_snapshot_struct_bytes,
6247 estimated_total_retained_bytes,
6248 }
6249 }
6250
6251 #[must_use]
6253 pub fn checkpoint_decision(
6254 snapshot_cost_ns: u128,
6255 replay_step_cost_ns: u128,
6256 ) -> PaneInteractionTimelineCheckpointDecision {
6257 let interval =
6258 analytically_tuned_checkpoint_interval(snapshot_cost_ns, replay_step_cost_ns);
6259 let replay_depth_ns = replay_step_cost_ns.saturating_mul(interval as u128) / 2;
6260 PaneInteractionTimelineCheckpointDecision {
6261 checkpoint_interval: interval,
6262 estimated_snapshot_cost_ns: snapshot_cost_ns,
6263 estimated_replay_step_cost_ns: replay_step_cost_ns,
6264 estimated_replay_depth_ns: replay_depth_ns,
6265 }
6266 }
6267
6268 pub fn apply_and_record(
6273 &mut self,
6274 tree: &mut PaneTree,
6275 sequence: u64,
6276 operation_id: u64,
6277 operation: PaneOperation,
6278 ) -> Result<PaneOperationOutcome, PaneOperationError> {
6279 let baseline = self.baseline.is_none().then(|| tree.to_snapshot());
6280 let outcome = tree.apply_operation(operation_id, operation.clone())?;
6283 self.record_applied(tree, baseline, sequence, operation, &outcome, None, true);
6284 Ok(outcome)
6285 }
6286
6287 pub fn apply_and_record_coalesced_resize_delta(
6295 &mut self,
6296 tree: &mut PaneTree,
6297 sequence: u64,
6298 operation_id: u64,
6299 operation: PaneOperation,
6300 coalesce_after_operation_id: u64,
6301 ) -> Result<PaneOperationOutcome, PaneOperationError> {
6302 let baseline = self.baseline.is_none().then(|| tree.to_snapshot());
6303 let outcome = tree.apply_operation(operation_id, operation.clone())?;
6304 self.record_applied(
6305 tree,
6306 baseline,
6307 sequence,
6308 operation,
6309 &outcome,
6310 Some(coalesce_after_operation_id),
6311 true,
6312 );
6313 Ok(outcome)
6314 }
6315
6316 #[allow(clippy::too_many_arguments)]
6319 pub(crate) fn record_applied(
6320 &mut self,
6321 tree: &PaneTree,
6322 baseline: Option<PaneTreeSnapshot>,
6323 sequence: u64,
6324 operation: PaneOperation,
6325 outcome: &PaneOperationOutcome,
6326 coalesce_after: Option<u64>,
6327 checkpoints_enabled: bool,
6328 ) -> bool {
6329 if let Some(baseline) = baseline {
6330 self.baseline = Some(baseline);
6331 }
6332 if self.cursor < self.entries.len() {
6333 self.entries.truncate(self.cursor);
6334 self.checkpoints
6335 .retain(|checkpoint| checkpoint.applied_len <= self.cursor);
6336 }
6337 let coalesced_before_hash = match &operation {
6338 PaneOperation::SetSplitRatio { split, .. } if self.cursor == self.entries.len() => self
6339 .entries
6340 .last()
6341 .and_then(|entry| match &entry.operation {
6342 PaneOperation::SetSplitRatio {
6343 split: previous_split,
6344 ..
6345 } if previous_split == split
6346 && coalesce_after.is_some_and(|boundary| entry.operation_id > boundary) =>
6347 {
6348 Some(entry.before_hash)
6349 }
6350 _ => None,
6351 }),
6352 _ => None,
6353 };
6354
6355 if let Some(before_hash) = coalesced_before_hash
6356 && let Some(entry) = self.entries.last_mut()
6357 {
6358 *entry = PaneInteractionTimelineEntry {
6359 sequence,
6360 operation_id: outcome.operation_id,
6361 operation,
6362 before_hash,
6363 after_hash: outcome.after_hash,
6364 };
6365 self.cursor = self.entries.len();
6366 self.checkpoints
6367 .retain(|checkpoint| checkpoint.applied_len < self.cursor);
6368 self.enforce_entry_limit();
6369 if checkpoints_enabled {
6370 self.maybe_record_checkpoint(tree);
6371 }
6372 return true;
6373 }
6374
6375 self.entries.push(PaneInteractionTimelineEntry {
6376 sequence,
6377 operation_id: outcome.operation_id,
6378 operation,
6379 before_hash: outcome.before_hash,
6380 after_hash: outcome.after_hash,
6381 });
6382 self.cursor = self.entries.len();
6383 self.enforce_entry_limit();
6384 if checkpoints_enabled {
6385 self.maybe_record_checkpoint(tree);
6386 }
6387 false
6388 }
6389
6390 pub fn undo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneInteractionTimelineError> {
6393 if self.cursor == 0 {
6394 return Ok(false);
6395 }
6396 *tree = self.replay_at(self.cursor - 1)?;
6397 self.cursor -= 1;
6398 Ok(true)
6399 }
6400
6401 pub fn redo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneInteractionTimelineError> {
6404 if self.cursor >= self.entries.len() {
6405 return Ok(false);
6406 }
6407 *tree = self.replay_at(self.cursor + 1)?;
6408 self.cursor += 1;
6409 Ok(true)
6410 }
6411
6412 pub fn replay(&self) -> Result<PaneTree, PaneInteractionTimelineError> {
6414 self.replay_at(self.cursor)
6415 }
6416
6417 fn replay_at(&self, cursor: usize) -> Result<PaneTree, PaneInteractionTimelineError> {
6418 let (mut tree, start_idx) = self.restore_replay_start(cursor)?;
6419 for entry in self.entries.iter().take(cursor).skip(start_idx) {
6420 tree.apply_operation_in_place_for_replay(entry.operation_id, &entry.operation)
6421 .map_err(|source| PaneInteractionTimelineError::ApplyFailed { source })?;
6422 }
6423 Ok(tree)
6424 }
6425
6426 fn restore_replay_start(
6427 &self,
6428 cursor: usize,
6429 ) -> Result<(PaneTree, usize), PaneInteractionTimelineError> {
6430 if let Some(checkpoint) = self
6431 .checkpoints
6432 .iter()
6433 .rev()
6434 .find(|checkpoint| checkpoint.applied_len <= cursor)
6435 {
6436 let tree = PaneTree::from_snapshot(checkpoint.snapshot.clone())
6437 .map_err(|source| PaneInteractionTimelineError::BaselineInvalid { source })?;
6438 return Ok((tree, checkpoint.applied_len));
6439 }
6440
6441 let baseline = self
6442 .baseline
6443 .clone()
6444 .ok_or(PaneInteractionTimelineError::MissingBaseline)?;
6445 let tree = PaneTree::from_snapshot(baseline)
6446 .map_err(|source| PaneInteractionTimelineError::BaselineInvalid { source })?;
6447 Ok((tree, 0))
6448 }
6449
6450 fn maybe_record_checkpoint(&mut self, tree: &PaneTree) {
6451 if self.checkpoint_interval == 0 || self.cursor == 0 {
6452 return;
6453 }
6454 if !self.cursor.is_multiple_of(self.checkpoint_interval) {
6455 return;
6456 }
6457 if let Some(checkpoint) = self
6458 .checkpoints
6459 .iter_mut()
6460 .find(|checkpoint| checkpoint.applied_len == self.cursor)
6461 {
6462 checkpoint.snapshot = tree.to_snapshot();
6463 return;
6464 }
6465 self.checkpoints.push(PaneInteractionTimelineCheckpoint {
6466 applied_len: self.cursor,
6467 snapshot: tree.to_snapshot(),
6468 });
6469 }
6470
6471 fn enforce_entry_limit(&mut self) {
6472 if self.max_entries == 0 || self.entries.len() <= self.max_entries {
6473 return;
6474 }
6475
6476 let prune_count = self
6481 .entries
6482 .len()
6483 .saturating_sub(self.max_entries)
6484 .min(self.cursor);
6485 if prune_count == 0 {
6486 return;
6487 }
6488 let Some(baseline) = self.baseline.clone() else {
6489 return;
6490 };
6491 let Ok(mut baseline_tree) = PaneTree::from_snapshot(baseline) else {
6492 return;
6493 };
6494
6495 for entry in self.entries.iter().take(prune_count) {
6496 if baseline_tree
6497 .apply_operation_in_place_for_replay(entry.operation_id, &entry.operation)
6498 .is_err()
6499 {
6500 return;
6501 }
6502 }
6503
6504 self.baseline = Some(baseline_tree.to_snapshot());
6505 drop(self.entries.drain(..prune_count));
6506 self.cursor = self
6507 .cursor
6508 .saturating_sub(prune_count)
6509 .min(self.entries.len());
6510 self.checkpoints = self
6511 .checkpoints
6512 .iter()
6513 .filter(|checkpoint| checkpoint.applied_len > prune_count)
6514 .map(|checkpoint| PaneInteractionTimelineCheckpoint {
6515 applied_len: checkpoint.applied_len - prune_count,
6516 snapshot: checkpoint.snapshot.clone(),
6517 })
6518 .collect();
6519 }
6520}
6521
6522#[derive(Debug, Clone, Copy, Default)]
6523struct PaneTimelineSnapshotRetentionStats {
6524 snapshot_count: usize,
6525 node_count: usize,
6526 leaf_payload_bytes: usize,
6527 extension_entry_count: usize,
6528 extension_payload_bytes: usize,
6529}
6530
6531impl PaneTimelineSnapshotRetentionStats {
6532 fn add_snapshot(&mut self, snapshot: &PaneTreeSnapshot) {
6533 self.snapshot_count = self.snapshot_count.saturating_add(1);
6534 self.node_count = self.node_count.saturating_add(snapshot.nodes.len());
6535 self.extension_entry_count = self
6536 .extension_entry_count
6537 .saturating_add(snapshot.extensions.len());
6538 self.extension_payload_bytes = self
6539 .extension_payload_bytes
6540 .saturating_add(string_map_payload_bytes(&snapshot.extensions));
6541
6542 for node in &snapshot.nodes {
6543 self.extension_entry_count = self
6544 .extension_entry_count
6545 .saturating_add(node.extensions.len());
6546 self.extension_payload_bytes = self
6547 .extension_payload_bytes
6548 .saturating_add(string_map_payload_bytes(&node.extensions));
6549 if let PaneNodeKind::Leaf(leaf) = &node.kind {
6550 self.leaf_payload_bytes = self
6551 .leaf_payload_bytes
6552 .saturating_add(pane_leaf_surface_payload_bytes(leaf));
6553 self.extension_entry_count = self
6554 .extension_entry_count
6555 .saturating_add(leaf.extensions.len());
6556 self.extension_payload_bytes = self
6557 .extension_payload_bytes
6558 .saturating_add(string_map_payload_bytes(&leaf.extensions));
6559 }
6560 }
6561 }
6562}
6563
6564fn pane_operation_retained_payload_bytes(operation: &PaneOperation) -> usize {
6565 match operation {
6566 PaneOperation::SplitLeaf { new_leaf, .. } => pane_leaf_retained_payload_bytes(new_leaf),
6567 PaneOperation::CloseNode { .. }
6568 | PaneOperation::MoveSubtree { .. }
6569 | PaneOperation::SwapNodes { .. }
6570 | PaneOperation::SetSplitRatio { .. }
6571 | PaneOperation::NormalizeRatios => 0,
6572 }
6573}
6574
6575fn pane_leaf_retained_payload_bytes(leaf: &PaneLeaf) -> usize {
6576 pane_leaf_surface_payload_bytes(leaf).saturating_add(string_map_payload_bytes(&leaf.extensions))
6577}
6578
6579fn pane_leaf_surface_payload_bytes(leaf: &PaneLeaf) -> usize {
6580 leaf.surface_key.len()
6581}
6582
6583fn string_map_payload_bytes(map: &BTreeMap<String, String>) -> usize {
6584 map.iter()
6585 .map(|(key, value)| key.len().saturating_add(value.len()))
6586 .sum()
6587}
6588
6589fn analytically_tuned_checkpoint_interval(
6590 snapshot_cost_ns: u128,
6591 replay_step_cost_ns: u128,
6592) -> usize {
6593 if snapshot_cost_ns == 0 || replay_step_cost_ns == 0 {
6594 return DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL;
6595 }
6596
6597 let ratio = snapshot_cost_ns.saturating_mul(2) / replay_step_cost_ns;
6598 let root = integer_sqrt(ratio).max(1);
6599 usize::try_from(root).unwrap_or(DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL)
6600}
6601
6602fn integer_sqrt(value: u128) -> u128 {
6603 if value < 2 {
6604 return value;
6605 }
6606
6607 let mut left = 1u128;
6608 let mut right = value;
6609 let mut answer = 1u128;
6610 while left <= right {
6611 let mid = left + (right - left) / 2;
6612 if mid <= value / mid {
6613 answer = mid;
6614 left = mid + 1;
6615 } else {
6616 right = mid - 1;
6617 }
6618 }
6619 answer
6620}
6621
6622#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6624pub struct PaneIdAllocator {
6625 next: PaneId,
6626}
6627
6628impl PaneIdAllocator {
6629 #[must_use]
6631 pub const fn with_next(next: PaneId) -> Self {
6632 Self { next }
6633 }
6634
6635 #[must_use]
6637 pub fn from_tree(tree: &PaneTree) -> Self {
6638 Self { next: tree.next_id }
6639 }
6640
6641 #[must_use]
6643 pub const fn peek(&self) -> PaneId {
6644 self.next
6645 }
6646
6647 pub fn allocate(&mut self) -> Result<PaneId, PaneModelError> {
6649 let current = self.next;
6650 self.next = self.next.checked_next()?;
6651 Ok(current)
6652 }
6653}
6654
6655impl Default for PaneIdAllocator {
6656 fn default() -> Self {
6657 Self { next: PaneId::MIN }
6658 }
6659}
6660
6661#[derive(Debug, Clone, PartialEq, Eq)]
6663pub enum PaneModelError {
6664 ZeroPaneId,
6665 UnsupportedSchemaVersion {
6666 version: u16,
6667 },
6668 DuplicateNodeId {
6669 node_id: PaneId,
6670 },
6671 MissingRoot {
6672 root: PaneId,
6673 },
6674 RootHasParent {
6675 root: PaneId,
6676 parent: PaneId,
6677 },
6678 MissingParent {
6679 node_id: PaneId,
6680 parent: PaneId,
6681 },
6682 MissingChild {
6683 parent: PaneId,
6684 child: PaneId,
6685 },
6686 MultipleParents {
6687 child: PaneId,
6688 first_parent: PaneId,
6689 second_parent: PaneId,
6690 },
6691 ParentMismatch {
6692 node_id: PaneId,
6693 expected: Option<PaneId>,
6694 actual: Option<PaneId>,
6695 },
6696 SelfReferentialSplit {
6697 node_id: PaneId,
6698 },
6699 DuplicateSplitChildren {
6700 node_id: PaneId,
6701 child: PaneId,
6702 },
6703 InvalidSplitRatio {
6704 numerator: u32,
6705 denominator: u32,
6706 },
6707 InvalidConstraint {
6708 node_id: PaneId,
6709 axis: &'static str,
6710 min: u16,
6711 max: u16,
6712 },
6713 NodeConstraintUnsatisfied {
6714 node_id: PaneId,
6715 axis: &'static str,
6716 actual: u16,
6717 min: u16,
6718 max: Option<u16>,
6719 },
6720 OverconstrainedSplit {
6721 node_id: PaneId,
6722 axis: SplitAxis,
6723 available: u16,
6724 first_min: u16,
6725 first_max: u16,
6726 second_min: u16,
6727 second_max: u16,
6728 },
6729 InfeasibleSubtree {
6731 node_id: PaneId,
6732 axis: SplitAxis,
6733 min: u32,
6734 max: u16,
6735 },
6736 CycleDetected {
6737 node_id: PaneId,
6738 },
6739 UnreachableNode {
6740 node_id: PaneId,
6741 },
6742 TreeTooDeep {
6743 node_id: PaneId,
6744 depth: usize,
6745 max_depth: usize,
6746 },
6747 NextIdNotGreaterThanExisting {
6748 next_id: PaneId,
6749 max_existing: PaneId,
6750 },
6751 PaneIdOverflow {
6752 current: PaneId,
6753 },
6754}
6755
6756impl fmt::Display for PaneModelError {
6757 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6758 match self {
6759 Self::ZeroPaneId => write!(f, "pane id 0 is invalid"),
6760 Self::UnsupportedSchemaVersion { version } => {
6761 write!(
6762 f,
6763 "unsupported pane schema version {version} (expected {PANE_TREE_SCHEMA_VERSION})"
6764 )
6765 }
6766 Self::DuplicateNodeId { node_id } => write!(f, "duplicate pane node id {}", node_id.0),
6767 Self::MissingRoot { root } => write!(f, "root pane node {} not found", root.0),
6768 Self::RootHasParent { root, parent } => write!(
6769 f,
6770 "root pane node {} must not have parent {}",
6771 root.0, parent.0
6772 ),
6773 Self::MissingParent { node_id, parent } => write!(
6774 f,
6775 "node {} references missing parent {}",
6776 node_id.0, parent.0
6777 ),
6778 Self::MissingChild { parent, child } => write!(
6779 f,
6780 "split node {} references missing child {}",
6781 parent.0, child.0
6782 ),
6783 Self::MultipleParents {
6784 child,
6785 first_parent,
6786 second_parent,
6787 } => write!(
6788 f,
6789 "node {} has multiple parents: {} and {}",
6790 child.0, first_parent.0, second_parent.0
6791 ),
6792 Self::ParentMismatch {
6793 node_id,
6794 expected,
6795 actual,
6796 } => write!(
6797 f,
6798 "node {} parent mismatch: expected {:?}, got {:?}",
6799 node_id.0,
6800 expected.map(PaneId::get),
6801 actual.map(PaneId::get)
6802 ),
6803 Self::SelfReferentialSplit { node_id } => {
6804 write!(f, "split node {} cannot reference itself", node_id.0)
6805 }
6806 Self::DuplicateSplitChildren { node_id, child } => write!(
6807 f,
6808 "split node {} references child {} twice",
6809 node_id.0, child.0
6810 ),
6811 Self::InvalidSplitRatio {
6812 numerator,
6813 denominator,
6814 } => write!(
6815 f,
6816 "invalid split ratio {numerator}/{denominator}: both values must be > 0"
6817 ),
6818 Self::InvalidConstraint {
6819 node_id,
6820 axis,
6821 min,
6822 max,
6823 } => write!(
6824 f,
6825 "invalid {axis} constraints for node {}: max {max} < min {min}",
6826 node_id.0
6827 ),
6828 Self::NodeConstraintUnsatisfied {
6829 node_id,
6830 axis,
6831 actual,
6832 min,
6833 max,
6834 } => write!(
6835 f,
6836 "node {} {axis}={} violates constraints [min={}, max={:?}]",
6837 node_id.0, actual, min, max
6838 ),
6839 Self::OverconstrainedSplit {
6840 node_id,
6841 axis,
6842 available,
6843 first_min,
6844 first_max,
6845 second_min,
6846 second_max,
6847 } => write!(
6848 f,
6849 "overconstrained {:?} split at node {} (available={}): first[min={}, max={}], second[min={}, max={}]",
6850 axis, node_id.0, available, first_min, first_max, second_min, second_max
6851 ),
6852 Self::InfeasibleSubtree {
6853 node_id,
6854 axis,
6855 min,
6856 max,
6857 } => write!(
6858 f,
6859 "infeasible {axis:?} subtree at node {}: required minimum {min} exceeds maximum {max}",
6860 node_id.0
6861 ),
6862 Self::CycleDetected { node_id } => {
6863 write!(f, "cycle detected at node {}", node_id.0)
6864 }
6865 Self::UnreachableNode { node_id } => {
6866 write!(f, "node {} is unreachable from root", node_id.0)
6867 }
6868 Self::TreeTooDeep {
6869 node_id,
6870 depth,
6871 max_depth,
6872 } => write!(
6873 f,
6874 "node {} nests {depth} splits deep, past the maximum of {max_depth}",
6875 node_id.0
6876 ),
6877 Self::NextIdNotGreaterThanExisting {
6878 next_id,
6879 max_existing,
6880 } => write!(
6881 f,
6882 "next_id {} must be greater than max existing id {}",
6883 next_id.0, max_existing.0
6884 ),
6885 Self::PaneIdOverflow { current } => {
6886 write!(f, "pane id overflow after {}", current.0)
6887 }
6888 }
6889 }
6890}
6891
6892impl std::error::Error for PaneModelError {}
6893
6894fn snapshot_state_hash(snapshot: &PaneTreeSnapshot) -> u64 {
6895 const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
6896 const PRIME: u64 = 0x0000_0001_0000_01b3;
6897
6898 fn mix(hash: &mut u64, byte: u8) {
6899 *hash ^= u64::from(byte);
6900 *hash = hash.wrapping_mul(PRIME);
6901 }
6902
6903 fn mix_bytes(hash: &mut u64, bytes: &[u8]) {
6904 for byte in bytes {
6905 mix(hash, *byte);
6906 }
6907 }
6908
6909 fn mix_u16(hash: &mut u64, value: u16) {
6910 mix_bytes(hash, &value.to_le_bytes());
6911 }
6912
6913 fn mix_u32(hash: &mut u64, value: u32) {
6914 mix_bytes(hash, &value.to_le_bytes());
6915 }
6916
6917 fn mix_u64(hash: &mut u64, value: u64) {
6918 mix_bytes(hash, &value.to_le_bytes());
6919 }
6920
6921 fn mix_bool(hash: &mut u64, value: bool) {
6922 mix(hash, u8::from(value));
6923 }
6924
6925 fn mix_opt_u16(hash: &mut u64, value: Option<u16>) {
6926 match value {
6927 Some(value) => {
6928 mix(hash, 1);
6929 mix_u16(hash, value);
6930 }
6931 None => mix(hash, 0),
6932 }
6933 }
6934
6935 fn mix_opt_pane_id(hash: &mut u64, value: Option<PaneId>) {
6936 match value {
6937 Some(value) => {
6938 mix(hash, 1);
6939 mix_u64(hash, value.get());
6940 }
6941 None => mix(hash, 0),
6942 }
6943 }
6944
6945 fn mix_str(hash: &mut u64, value: &str) {
6946 mix_u64(hash, value.len() as u64);
6947 mix_bytes(hash, value.as_bytes());
6948 }
6949
6950 fn mix_extensions(hash: &mut u64, extensions: &BTreeMap<String, String>) {
6951 mix_u64(hash, extensions.len() as u64);
6952 for (key, value) in extensions {
6953 mix_str(hash, key);
6954 mix_str(hash, value);
6955 }
6956 }
6957
6958 let mut canonical = snapshot.clone();
6959 canonical.canonicalize();
6960
6961 let mut hash = OFFSET_BASIS;
6962 mix_u16(&mut hash, canonical.schema_version);
6963 mix_u64(&mut hash, canonical.root.get());
6964 mix_u64(&mut hash, canonical.next_id.get());
6965 mix_extensions(&mut hash, &canonical.extensions);
6966 mix_u64(&mut hash, canonical.nodes.len() as u64);
6967
6968 for node in &canonical.nodes {
6969 mix_u64(&mut hash, node.id.get());
6970 mix_opt_pane_id(&mut hash, node.parent);
6971 mix_u16(&mut hash, node.constraints.min_width);
6972 mix_u16(&mut hash, node.constraints.min_height);
6973 mix_opt_u16(&mut hash, node.constraints.max_width);
6974 mix_opt_u16(&mut hash, node.constraints.max_height);
6975 mix_bool(&mut hash, node.constraints.collapsible);
6976 mix_extensions(&mut hash, &node.extensions);
6977
6978 match &node.kind {
6979 PaneNodeKind::Leaf(leaf) => {
6980 mix(&mut hash, 1);
6981 mix_str(&mut hash, &leaf.surface_key);
6982 mix_extensions(&mut hash, &leaf.extensions);
6983 }
6984 PaneNodeKind::Split(split) => {
6985 mix(&mut hash, 2);
6986 let axis_byte = match split.axis {
6987 SplitAxis::Horizontal => 1,
6988 SplitAxis::Vertical => 2,
6989 };
6990 mix(&mut hash, axis_byte);
6991 mix_u32(&mut hash, split.ratio.numerator());
6992 mix_u32(&mut hash, split.ratio.denominator());
6993 mix_u64(&mut hash, split.first.get());
6994 mix_u64(&mut hash, split.second.get());
6995 }
6996 }
6997 }
6998
6999 hash
7000}
7001
7002fn push_invariant_issue(
7003 issues: &mut Vec<PaneInvariantIssue>,
7004 code: PaneInvariantCode,
7005 repairable: bool,
7006 node_id: Option<PaneId>,
7007 related_node: Option<PaneId>,
7008 message: impl Into<String>,
7009) {
7010 issues.push(PaneInvariantIssue {
7011 code,
7012 severity: PaneInvariantSeverity::Error,
7013 repairable,
7014 node_id,
7015 related_node,
7016 message: message.into(),
7017 });
7018}
7019
7020fn dfs_collect_cycles_and_reachable(
7028 root: PaneId,
7029 nodes: &BTreeMap<PaneId, PaneNodeRecord>,
7030 visiting: &mut BTreeSet<PaneId>,
7031 visited: &mut BTreeSet<PaneId>,
7032 cycle_nodes: &mut BTreeSet<PaneId>,
7033) {
7034 enum Step {
7037 Enter(PaneId),
7038 Exit(PaneId),
7039 }
7040
7041 let mut stack = vec![Step::Enter(root)];
7042 while let Some(step) = stack.pop() {
7043 match step {
7044 Step::Enter(node_id) => {
7045 if visiting.contains(&node_id) {
7046 let _ = cycle_nodes.insert(node_id);
7047 continue;
7048 }
7049 if !visited.insert(node_id) {
7050 continue;
7051 }
7052 let _ = visiting.insert(node_id);
7053 stack.push(Step::Exit(node_id));
7054 if let Some(node) = nodes.get(&node_id)
7055 && let PaneNodeKind::Split(split) = &node.kind
7056 {
7057 for child in [split.second, split.first] {
7060 if nodes.contains_key(&child) {
7061 stack.push(Step::Enter(child));
7062 }
7063 }
7064 }
7065 }
7066 Step::Exit(node_id) => {
7067 let _ = visiting.remove(&node_id);
7068 }
7069 }
7070 }
7071}
7072
7073fn build_invariant_report(snapshot: &PaneTreeSnapshot) -> PaneInvariantReport {
7074 let mut issues = Vec::new();
7075
7076 if snapshot.schema_version != PANE_TREE_SCHEMA_VERSION {
7077 push_invariant_issue(
7078 &mut issues,
7079 PaneInvariantCode::UnsupportedSchemaVersion,
7080 false,
7081 None,
7082 None,
7083 format!(
7084 "unsupported schema version {} (expected {})",
7085 snapshot.schema_version, PANE_TREE_SCHEMA_VERSION
7086 ),
7087 );
7088 }
7089
7090 let mut nodes = BTreeMap::new();
7091 for node in &snapshot.nodes {
7092 if nodes.insert(node.id, node.clone()).is_some() {
7093 push_invariant_issue(
7094 &mut issues,
7095 PaneInvariantCode::DuplicateNodeId,
7096 false,
7097 Some(node.id),
7098 None,
7099 format!("duplicate node id {}", node.id.get()),
7100 );
7101 }
7102 }
7103
7104 if let Some(max_existing) = nodes.keys().next_back().copied()
7105 && snapshot.next_id <= max_existing
7106 {
7107 push_invariant_issue(
7108 &mut issues,
7109 PaneInvariantCode::NextIdNotGreaterThanExisting,
7110 true,
7111 Some(snapshot.next_id),
7112 Some(max_existing),
7113 format!(
7114 "next_id {} must be greater than max node id {}",
7115 snapshot.next_id.get(),
7116 max_existing.get()
7117 ),
7118 );
7119 }
7120
7121 if !nodes.contains_key(&snapshot.root) {
7122 push_invariant_issue(
7123 &mut issues,
7124 PaneInvariantCode::MissingRoot,
7125 false,
7126 Some(snapshot.root),
7127 None,
7128 format!("root node {} is missing", snapshot.root.get()),
7129 );
7130 }
7131
7132 let mut expected_parents = BTreeMap::new();
7133 for node in nodes.values() {
7134 if let Err(err) = node.constraints.validate(node.id) {
7135 push_invariant_issue(
7136 &mut issues,
7137 PaneInvariantCode::InvalidConstraint,
7138 false,
7139 Some(node.id),
7140 None,
7141 err.to_string(),
7142 );
7143 }
7144
7145 if let Some(parent) = node.parent
7146 && !nodes.contains_key(&parent)
7147 {
7148 push_invariant_issue(
7149 &mut issues,
7150 PaneInvariantCode::MissingParent,
7151 true,
7152 Some(node.id),
7153 Some(parent),
7154 format!(
7155 "node {} references missing parent {}",
7156 node.id.get(),
7157 parent.get()
7158 ),
7159 );
7160 }
7161
7162 if let PaneNodeKind::Split(split) = &node.kind {
7163 if split.ratio.numerator() == 0 || split.ratio.denominator() == 0 {
7164 push_invariant_issue(
7165 &mut issues,
7166 PaneInvariantCode::InvalidSplitRatio,
7167 false,
7168 Some(node.id),
7169 None,
7170 format!(
7171 "split node {} has invalid ratio {}/{}",
7172 node.id.get(),
7173 split.ratio.numerator(),
7174 split.ratio.denominator()
7175 ),
7176 );
7177 }
7178
7179 if split.first == node.id || split.second == node.id {
7180 push_invariant_issue(
7181 &mut issues,
7182 PaneInvariantCode::SelfReferentialSplit,
7183 false,
7184 Some(node.id),
7185 None,
7186 format!("split node {} references itself", node.id.get()),
7187 );
7188 }
7189
7190 if split.first == split.second {
7191 push_invariant_issue(
7192 &mut issues,
7193 PaneInvariantCode::DuplicateSplitChildren,
7194 false,
7195 Some(node.id),
7196 Some(split.first),
7197 format!(
7198 "split node {} references child {} twice",
7199 node.id.get(),
7200 split.first.get()
7201 ),
7202 );
7203 }
7204
7205 for child in [split.first, split.second] {
7206 if !nodes.contains_key(&child) {
7207 push_invariant_issue(
7208 &mut issues,
7209 PaneInvariantCode::MissingChild,
7210 false,
7211 Some(node.id),
7212 Some(child),
7213 format!(
7214 "split node {} references missing child {}",
7215 node.id.get(),
7216 child.get()
7217 ),
7218 );
7219 continue;
7220 }
7221
7222 if let Some(first_parent) = expected_parents.insert(child, node.id)
7223 && first_parent != node.id
7224 {
7225 push_invariant_issue(
7226 &mut issues,
7227 PaneInvariantCode::MultipleParents,
7228 false,
7229 Some(child),
7230 Some(node.id),
7231 format!(
7232 "node {} has multiple split parents {} and {}",
7233 child.get(),
7234 first_parent.get(),
7235 node.id.get()
7236 ),
7237 );
7238 }
7239 }
7240 }
7241 }
7242
7243 if let Some(root_node) = nodes.get(&snapshot.root)
7244 && let Some(parent) = root_node.parent
7245 {
7246 push_invariant_issue(
7247 &mut issues,
7248 PaneInvariantCode::RootHasParent,
7249 true,
7250 Some(snapshot.root),
7251 Some(parent),
7252 format!(
7253 "root node {} must not have parent {}",
7254 snapshot.root.get(),
7255 parent.get()
7256 ),
7257 );
7258 }
7259
7260 for node in nodes.values() {
7261 let expected_parent = if node.id == snapshot.root {
7262 None
7263 } else {
7264 expected_parents.get(&node.id).copied()
7265 };
7266
7267 if node.parent != expected_parent {
7268 push_invariant_issue(
7269 &mut issues,
7270 PaneInvariantCode::ParentMismatch,
7271 true,
7272 Some(node.id),
7273 expected_parent,
7274 format!(
7275 "node {} parent mismatch: expected {:?}, got {:?}",
7276 node.id.get(),
7277 expected_parent.map(PaneId::get),
7278 node.parent.map(PaneId::get)
7279 ),
7280 );
7281 }
7282 }
7283
7284 if nodes.contains_key(&snapshot.root) {
7285 let mut visiting = BTreeSet::new();
7286 let mut visited = BTreeSet::new();
7287 let mut cycle_nodes = BTreeSet::new();
7288 dfs_collect_cycles_and_reachable(
7289 snapshot.root,
7290 &nodes,
7291 &mut visiting,
7292 &mut visited,
7293 &mut cycle_nodes,
7294 );
7295
7296 for node_id in cycle_nodes {
7297 push_invariant_issue(
7298 &mut issues,
7299 PaneInvariantCode::CycleDetected,
7300 false,
7301 Some(node_id),
7302 None,
7303 format!("cycle detected at node {}", node_id.get()),
7304 );
7305 }
7306
7307 for node_id in nodes.keys() {
7308 if !visited.contains(node_id) {
7309 push_invariant_issue(
7310 &mut issues,
7311 PaneInvariantCode::UnreachableNode,
7312 true,
7313 Some(*node_id),
7314 None,
7315 format!("node {} is unreachable from root", node_id.get()),
7316 );
7317 }
7318 }
7319 }
7320
7321 issues.sort_by(|left, right| {
7322 (
7323 left.code,
7324 left.node_id.is_none(),
7325 left.node_id,
7326 left.related_node.is_none(),
7327 left.related_node,
7328 &left.message,
7329 )
7330 .cmp(&(
7331 right.code,
7332 right.node_id.is_none(),
7333 right.node_id,
7334 right.related_node.is_none(),
7335 right.related_node,
7336 &right.message,
7337 ))
7338 });
7339
7340 PaneInvariantReport {
7341 snapshot_hash: snapshot_state_hash(snapshot),
7342 issues,
7343 }
7344}
7345
7346fn repair_snapshot_safe(
7347 mut snapshot: PaneTreeSnapshot,
7348) -> Result<PaneRepairOutcome, PaneRepairError> {
7349 snapshot.canonicalize();
7350
7351 let before_hash = snapshot_state_hash(&snapshot);
7352 let report_before = build_invariant_report(&snapshot);
7353 let mut unsafe_codes = report_before
7354 .issues
7355 .iter()
7356 .filter(|issue| issue.severity == PaneInvariantSeverity::Error && !issue.repairable)
7357 .map(|issue| issue.code)
7358 .collect::<Vec<_>>();
7359 unsafe_codes.sort();
7360 unsafe_codes.dedup();
7361
7362 if !unsafe_codes.is_empty() {
7363 return Err(PaneRepairError {
7364 before_hash,
7365 report: report_before,
7366 reason: PaneRepairFailure::UnsafeIssuesPresent {
7367 codes: unsafe_codes,
7368 },
7369 });
7370 }
7371
7372 let mut nodes = BTreeMap::new();
7373 for node in snapshot.nodes {
7374 let _ = nodes.entry(node.id).or_insert(node);
7375 }
7376
7377 let mut actions = Vec::new();
7378 let mut expected_parents = BTreeMap::new();
7379 for node in nodes.values() {
7380 if let PaneNodeKind::Split(split) = &node.kind {
7381 for child in [split.first, split.second] {
7382 let _ = expected_parents.entry(child).or_insert(node.id);
7383 }
7384 }
7385 }
7386
7387 for node in nodes.values_mut() {
7388 let expected_parent = if node.id == snapshot.root {
7389 None
7390 } else {
7391 expected_parents.get(&node.id).copied()
7392 };
7393 if node.parent != expected_parent {
7394 actions.push(PaneRepairAction::ReparentNode {
7395 node_id: node.id,
7396 before_parent: node.parent,
7397 after_parent: expected_parent,
7398 });
7399 node.parent = expected_parent;
7400 }
7401
7402 if let PaneNodeKind::Split(split) = &mut node.kind {
7403 let normalized =
7404 PaneSplitRatio::new(split.ratio.numerator(), split.ratio.denominator()).map_err(
7405 |error| PaneRepairError {
7406 before_hash,
7407 report: report_before.clone(),
7408 reason: PaneRepairFailure::ValidationFailed { error },
7409 },
7410 )?;
7411 if split.ratio != normalized {
7412 actions.push(PaneRepairAction::NormalizeRatio {
7413 node_id: node.id,
7414 before_numerator: split.ratio.numerator(),
7415 before_denominator: split.ratio.denominator(),
7416 after_numerator: normalized.numerator(),
7417 after_denominator: normalized.denominator(),
7418 });
7419 split.ratio = normalized;
7420 }
7421 }
7422 }
7423
7424 let mut visiting = BTreeSet::new();
7425 let mut visited = BTreeSet::new();
7426 let mut cycle_nodes = BTreeSet::new();
7427 if nodes.contains_key(&snapshot.root) {
7428 dfs_collect_cycles_and_reachable(
7429 snapshot.root,
7430 &nodes,
7431 &mut visiting,
7432 &mut visited,
7433 &mut cycle_nodes,
7434 );
7435 }
7436 if !cycle_nodes.is_empty() {
7437 let mut codes = vec![PaneInvariantCode::CycleDetected];
7438 codes.sort();
7439 codes.dedup();
7440 return Err(PaneRepairError {
7441 before_hash,
7442 report: report_before,
7443 reason: PaneRepairFailure::UnsafeIssuesPresent { codes },
7444 });
7445 }
7446
7447 let all_node_ids = nodes.keys().copied().collect::<Vec<_>>();
7448 for node_id in all_node_ids {
7449 if !visited.contains(&node_id) {
7450 let _ = nodes.remove(&node_id);
7451 actions.push(PaneRepairAction::RemoveOrphanNode { node_id });
7452 }
7453 }
7454
7455 if let Some(max_existing) = nodes.keys().next_back().copied()
7456 && snapshot.next_id <= max_existing
7457 {
7458 let after = max_existing
7459 .checked_next()
7460 .map_err(|error| PaneRepairError {
7461 before_hash,
7462 report: report_before.clone(),
7463 reason: PaneRepairFailure::ValidationFailed { error },
7464 })?;
7465 actions.push(PaneRepairAction::BumpNextId {
7466 before: snapshot.next_id,
7467 after,
7468 });
7469 snapshot.next_id = after;
7470 }
7471
7472 snapshot.nodes = nodes.into_values().collect();
7473 snapshot.canonicalize();
7474
7475 let tree = PaneTree::from_snapshot(snapshot).map_err(|error| PaneRepairError {
7476 before_hash,
7477 report: report_before.clone(),
7478 reason: PaneRepairFailure::ValidationFailed { error },
7479 })?;
7480 let report_after = tree.invariant_report();
7481 let after_hash = tree.state_hash();
7482
7483 Ok(PaneRepairOutcome {
7484 before_hash,
7485 after_hash,
7486 report_before,
7487 report_after,
7488 actions,
7489 tree,
7490 })
7491}
7492
7493fn validate_tree(
7494 root: PaneId,
7495 next_id: PaneId,
7496 nodes: &BTreeMap<PaneId, PaneNodeRecord>,
7497) -> Result<(), PaneModelError> {
7498 if !nodes.contains_key(&root) {
7499 return Err(PaneModelError::MissingRoot { root });
7500 }
7501
7502 let max_existing = nodes.keys().next_back().copied().unwrap_or(root);
7503 if next_id <= max_existing {
7504 return Err(PaneModelError::NextIdNotGreaterThanExisting {
7505 next_id,
7506 max_existing,
7507 });
7508 }
7509
7510 let mut expected_parents = BTreeMap::new();
7511
7512 for node in nodes.values() {
7513 node.constraints.validate(node.id)?;
7514
7515 if let Some(parent) = node.parent
7516 && !nodes.contains_key(&parent)
7517 {
7518 return Err(PaneModelError::MissingParent {
7519 node_id: node.id,
7520 parent,
7521 });
7522 }
7523
7524 if let PaneNodeKind::Split(split) = &node.kind {
7525 if split.ratio.numerator() == 0 || split.ratio.denominator() == 0 {
7526 return Err(PaneModelError::InvalidSplitRatio {
7527 numerator: split.ratio.numerator(),
7528 denominator: split.ratio.denominator(),
7529 });
7530 }
7531
7532 if split.first == node.id || split.second == node.id {
7533 return Err(PaneModelError::SelfReferentialSplit { node_id: node.id });
7534 }
7535 if split.first == split.second {
7536 return Err(PaneModelError::DuplicateSplitChildren {
7537 node_id: node.id,
7538 child: split.first,
7539 });
7540 }
7541
7542 for child in [split.first, split.second] {
7543 if !nodes.contains_key(&child) {
7544 return Err(PaneModelError::MissingChild {
7545 parent: node.id,
7546 child,
7547 });
7548 }
7549 if let Some(first_parent) = expected_parents.insert(child, node.id)
7550 && first_parent != node.id
7551 {
7552 return Err(PaneModelError::MultipleParents {
7553 child,
7554 first_parent,
7555 second_parent: node.id,
7556 });
7557 }
7558 }
7559 }
7560 }
7561
7562 if let Some(parent) = nodes.get(&root).and_then(|node| node.parent) {
7563 return Err(PaneModelError::RootHasParent { root, parent });
7564 }
7565
7566 for node in nodes.values() {
7567 let expected = if node.id == root {
7568 None
7569 } else {
7570 expected_parents.get(&node.id).copied()
7571 };
7572 if node.parent != expected {
7573 return Err(PaneModelError::ParentMismatch {
7574 node_id: node.id,
7575 expected,
7576 actual: node.parent,
7577 });
7578 }
7579 }
7580
7581 let mut visiting = BTreeSet::new();
7582 let mut visited = BTreeSet::new();
7583 dfs_validate(root, 0, nodes, &mut visiting, &mut visited)?;
7584
7585 if visited.len() != nodes.len()
7586 && let Some(node_id) = nodes.keys().find(|node_id| !visited.contains(node_id))
7587 {
7588 return Err(PaneModelError::UnreachableNode { node_id: *node_id });
7589 }
7590
7591 Ok(())
7592}
7593
7594#[derive(Debug, Clone, Copy)]
7595struct AxisBounds {
7596 min: u16,
7597 max: Option<u16>,
7598}
7599
7600fn axis_bounds(constraints: PaneConstraints, axis: SplitAxis) -> AxisBounds {
7601 match axis {
7602 SplitAxis::Horizontal => AxisBounds {
7603 min: constraints.min_width,
7604 max: constraints.max_width,
7605 },
7606 SplitAxis::Vertical => AxisBounds {
7607 min: constraints.min_height,
7608 max: constraints.max_height,
7609 },
7610 }
7611}
7612
7613fn subtree_axis_bounds(
7614 node_id: PaneId,
7615 axis: SplitAxis,
7616 split_axis: SplitAxis,
7617 own: PaneConstraints,
7618 first: PaneConstraints,
7619 second: PaneConstraints,
7620) -> Result<AxisBounds, PaneModelError> {
7621 let own = axis_bounds(own, axis);
7622 let first = axis_bounds(first, axis);
7623 let second = axis_bounds(second, axis);
7624 let first_max = u32::from(first.max.unwrap_or(u16::MAX));
7625 let second_max = u32::from(second.max.unwrap_or(u16::MAX));
7626 let (min, max) = if axis == split_axis {
7629 (
7630 u32::from(first.min) + u32::from(second.min),
7631 first_max + second_max,
7632 )
7633 } else {
7634 (
7635 u32::from(first.min.max(second.min)),
7636 first_max.min(second_max),
7637 )
7638 };
7639 let min = min.max(u32::from(own.min));
7640 let max = max.min(u32::from(own.max.unwrap_or(u16::MAX))) as u16;
7641 if min > u32::from(max) {
7642 return Err(PaneModelError::InfeasibleSubtree {
7643 node_id,
7644 axis,
7645 min,
7646 max,
7647 });
7648 }
7649 Ok(AxisBounds {
7650 min: min as u16,
7651 max: Some(max),
7652 })
7653}
7654
7655fn validate_area_against_constraints(
7656 node_id: PaneId,
7657 area: Rect,
7658 constraints: PaneConstraints,
7659) -> Result<(), PaneModelError> {
7660 if area.width < constraints.min_width {
7661 return Err(PaneModelError::NodeConstraintUnsatisfied {
7662 node_id,
7663 axis: "width",
7664 actual: area.width,
7665 min: constraints.min_width,
7666 max: constraints.max_width,
7667 });
7668 }
7669 if area.height < constraints.min_height {
7670 return Err(PaneModelError::NodeConstraintUnsatisfied {
7671 node_id,
7672 axis: "height",
7673 actual: area.height,
7674 min: constraints.min_height,
7675 max: constraints.max_height,
7676 });
7677 }
7678 if let Some(max_width) = constraints.max_width
7679 && area.width > max_width
7680 {
7681 return Err(PaneModelError::NodeConstraintUnsatisfied {
7682 node_id,
7683 axis: "width",
7684 actual: area.width,
7685 min: constraints.min_width,
7686 max: constraints.max_width,
7687 });
7688 }
7689 if let Some(max_height) = constraints.max_height
7690 && area.height > max_height
7691 {
7692 return Err(PaneModelError::NodeConstraintUnsatisfied {
7693 node_id,
7694 axis: "height",
7695 actual: area.height,
7696 min: constraints.min_height,
7697 max: constraints.max_height,
7698 });
7699 }
7700 Ok(())
7701}
7702
7703fn solve_split_sizes(
7704 node_id: PaneId,
7705 axis: SplitAxis,
7706 available: u16,
7707 ratio: PaneSplitRatio,
7708 first: AxisBounds,
7709 second: AxisBounds,
7710) -> Result<(u16, u16), PaneModelError> {
7711 let first_max = first.max.unwrap_or(available).min(available);
7712 let second_max = second.max.unwrap_or(available).min(available);
7713
7714 let feasible_first_min = first.min.max(available.saturating_sub(second_max));
7715 let feasible_first_max = first_max.min(available.saturating_sub(second.min));
7716
7717 if feasible_first_min > feasible_first_max {
7718 return Err(PaneModelError::OverconstrainedSplit {
7719 node_id,
7720 axis,
7721 available,
7722 first_min: first.min,
7723 first_max,
7724 second_min: second.min,
7725 second_max,
7726 });
7727 }
7728
7729 let total_weight = u64::from(ratio.numerator()) + u64::from(ratio.denominator());
7730 let desired_first_u64 = (u64::from(available) * u64::from(ratio.numerator())) / total_weight;
7731 let desired_first = desired_first_u64 as u16;
7732
7733 let first_size = desired_first.clamp(feasible_first_min, feasible_first_max);
7734 let second_size = available.saturating_sub(first_size);
7735 Ok((first_size, second_size))
7736}
7737
7738fn dfs_validate(
7739 node_id: PaneId,
7740 depth: usize,
7741 nodes: &BTreeMap<PaneId, PaneNodeRecord>,
7742 visiting: &mut BTreeSet<PaneId>,
7743 visited: &mut BTreeSet<PaneId>,
7744) -> Result<(), PaneModelError> {
7745 if visiting.contains(&node_id) {
7746 return Err(PaneModelError::CycleDetected { node_id });
7747 }
7748 if depth > PANE_TREE_MAX_DEPTH {
7751 return Err(PaneModelError::TreeTooDeep {
7752 node_id,
7753 depth,
7754 max_depth: PANE_TREE_MAX_DEPTH,
7755 });
7756 }
7757 if !visited.insert(node_id) {
7758 return Ok(());
7759 }
7760
7761 let _ = visiting.insert(node_id);
7762 if let Some(node) = nodes.get(&node_id)
7763 && let PaneNodeKind::Split(split) = &node.kind
7764 {
7765 dfs_validate(split.first, depth + 1, nodes, visiting, visited)?;
7766 dfs_validate(split.second, depth + 1, nodes, visiting, visited)?;
7767 }
7768 let _ = visiting.remove(&node_id);
7769 Ok(())
7770}
7771
7772fn gcd_u32(mut left: u32, mut right: u32) -> u32 {
7773 while right != 0 {
7774 let rem = left % right;
7775 left = right;
7776 right = rem;
7777 }
7778 left.max(1)
7779}
7780
7781#[cfg(test)]
7782mod tests {
7783 use super::*;
7784 use proptest::prelude::*;
7785
7786 fn id(raw: u64) -> PaneId {
7787 PaneId::new(raw).expect("test ID must be non-zero")
7788 }
7789
7790 fn make_valid_snapshot() -> PaneTreeSnapshot {
7791 let root = id(1);
7792 let left = id(2);
7793 let right = id(3);
7794
7795 PaneTreeSnapshot {
7796 schema_version: PANE_TREE_SCHEMA_VERSION,
7797 root,
7798 next_id: id(4),
7799 nodes: vec![
7800 PaneNodeRecord::leaf(
7801 right,
7802 Some(root),
7803 PaneLeaf {
7804 surface_key: "right".to_string(),
7805 extensions: BTreeMap::new(),
7806 },
7807 ),
7808 PaneNodeRecord::split(
7809 root,
7810 None,
7811 PaneSplit {
7812 axis: SplitAxis::Horizontal,
7813 ratio: PaneSplitRatio::new(3, 2).expect("valid ratio"),
7814 first: left,
7815 second: right,
7816 },
7817 ),
7818 PaneNodeRecord::leaf(
7819 left,
7820 Some(root),
7821 PaneLeaf {
7822 surface_key: "left".to_string(),
7823 extensions: BTreeMap::new(),
7824 },
7825 ),
7826 ],
7827 extensions: BTreeMap::new(),
7828 }
7829 }
7830
7831 fn make_deep_snapshot(depth: u64) -> PaneTreeSnapshot {
7834 let ratio = PaneSplitRatio::new(1, 1).expect("valid ratio");
7835 let mut nodes = Vec::new();
7836 for level in 0..depth {
7837 let split_id = id(2 * level + 1);
7838 let leaf_id = id(2 * level + 2);
7839 let second = id(2 * level + 3);
7840 nodes.push(PaneNodeRecord::split(
7841 split_id,
7842 (level > 0).then(|| id(2 * level - 1)),
7843 PaneSplit {
7844 axis: SplitAxis::Horizontal,
7845 ratio,
7846 first: leaf_id,
7847 second,
7848 },
7849 ));
7850 nodes.push(PaneNodeRecord::leaf(
7851 leaf_id,
7852 Some(split_id),
7853 PaneLeaf::new(format!("leaf {level}")),
7854 ));
7855 }
7856 nodes.push(PaneNodeRecord::leaf(
7857 id(2 * depth + 1),
7858 Some(id(2 * depth - 1)),
7859 PaneLeaf::new("tail"),
7860 ));
7861
7862 PaneTreeSnapshot {
7863 schema_version: PANE_TREE_SCHEMA_VERSION,
7864 root: id(1),
7865 next_id: id(2 * depth + 2),
7866 nodes,
7867 extensions: BTreeMap::new(),
7868 }
7869 }
7870
7871 #[test]
7875 fn a_snapshot_deeper_than_the_cap_is_refused() {
7876 let ok = PaneTree::from_snapshot(make_deep_snapshot(PANE_TREE_MAX_DEPTH as u64))
7877 .expect("a tree at the cap is accepted");
7878 assert_eq!(ok.nodes().count(), 2 * PANE_TREE_MAX_DEPTH + 1);
7879
7880 let error = PaneTree::from_snapshot(make_deep_snapshot(PANE_TREE_MAX_DEPTH as u64 + 1))
7881 .expect_err("a tree past the cap is refused");
7882 assert!(
7883 matches!(
7884 error,
7885 PaneModelError::TreeTooDeep {
7886 max_depth: PANE_TREE_MAX_DEPTH,
7887 ..
7888 }
7889 ),
7890 "expected TreeTooDeep, got {error}"
7891 );
7892 }
7893
7894 #[test]
7897 fn the_invariant_report_survives_a_snapshot_too_deep_to_validate() {
7898 let snapshot = make_deep_snapshot(50_000);
7899 let report = snapshot.invariant_report();
7900 assert!(
7901 !report.has_errors(),
7902 "a deep but otherwise sound snapshot reports no structural error: {:?}",
7903 report.issues
7904 );
7905 }
7906
7907 fn split_ratio(tree: &PaneTree, split: PaneId) -> PaneSplitRatio {
7908 let node = tree.node(split).expect("split node should exist");
7909 let PaneNodeKind::Split(split_node) = &node.kind else {
7910 let expected_split_node = false;
7911 assert!(expected_split_node, "node should be a split");
7912 return PaneSplitRatio::default();
7913 };
7914 split_node.ratio
7915 }
7916
7917 fn make_nested_snapshot() -> PaneTreeSnapshot {
7918 let root = id(1);
7919 let left = id(2);
7920 let right_split = id(3);
7921 let right_top = id(4);
7922 let right_bottom = id(5);
7923
7924 PaneTreeSnapshot {
7925 schema_version: PANE_TREE_SCHEMA_VERSION,
7926 root,
7927 next_id: id(6),
7928 nodes: vec![
7929 PaneNodeRecord::split(
7930 root,
7931 None,
7932 PaneSplit {
7933 axis: SplitAxis::Horizontal,
7934 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
7935 first: left,
7936 second: right_split,
7937 },
7938 ),
7939 PaneNodeRecord::leaf(left, Some(root), PaneLeaf::new("left")),
7940 PaneNodeRecord::split(
7941 right_split,
7942 Some(root),
7943 PaneSplit {
7944 axis: SplitAxis::Vertical,
7945 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
7946 first: right_top,
7947 second: right_bottom,
7948 },
7949 ),
7950 PaneNodeRecord::leaf(right_top, Some(right_split), PaneLeaf::new("right_top")),
7951 PaneNodeRecord::leaf(
7952 right_bottom,
7953 Some(right_split),
7954 PaneLeaf::new("right_bottom"),
7955 ),
7956 ],
7957 extensions: BTreeMap::new(),
7958 }
7959 }
7960
7961 #[test]
7962 fn ratio_is_normalized() {
7963 let ratio = PaneSplitRatio::new(12, 8).expect("ratio should normalize");
7964 assert_eq!(ratio.numerator(), 3);
7965 assert_eq!(ratio.denominator(), 2);
7966 }
7967
7968 #[test]
7969 fn snapshot_round_trip_preserves_canonical_order() {
7970 let tree =
7971 PaneTree::from_snapshot(make_valid_snapshot()).expect("snapshot should validate");
7972 let snapshot = tree.to_snapshot();
7973 let ids = snapshot
7974 .nodes
7975 .iter()
7976 .map(|node| node.id.get())
7977 .collect::<Vec<_>>();
7978 assert_eq!(ids, vec![1, 2, 3]);
7979 }
7980
7981 #[test]
7982 fn duplicate_node_id_is_rejected() {
7983 let mut snapshot = make_valid_snapshot();
7984 snapshot.nodes.push(PaneNodeRecord::leaf(
7985 id(2),
7986 Some(id(1)),
7987 PaneLeaf::new("dup"),
7988 ));
7989 let err = PaneTree::from_snapshot(snapshot).expect_err("duplicate ID should fail");
7990 assert_eq!(err, PaneModelError::DuplicateNodeId { node_id: id(2) });
7991 }
7992
7993 #[test]
7994 fn missing_child_is_rejected() {
7995 let mut snapshot = make_valid_snapshot();
7996 snapshot.nodes.retain(|node| node.id != id(3));
7997 let err = PaneTree::from_snapshot(snapshot).expect_err("missing child should fail");
7998 assert_eq!(
7999 err,
8000 PaneModelError::MissingChild {
8001 parent: id(1),
8002 child: id(3),
8003 }
8004 );
8005 }
8006
8007 #[test]
8008 fn unreachable_node_is_rejected() {
8009 let mut snapshot = make_valid_snapshot();
8010 snapshot
8011 .nodes
8012 .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8013 snapshot.next_id = id(11);
8014 let err = PaneTree::from_snapshot(snapshot).expect_err("orphan should fail");
8015 assert_eq!(err, PaneModelError::UnreachableNode { node_id: id(10) });
8016 }
8017
8018 #[test]
8019 fn next_id_must_be_greater_than_existing_ids() {
8020 let mut snapshot = make_valid_snapshot();
8021 snapshot.next_id = id(3);
8022 let err = PaneTree::from_snapshot(snapshot).expect_err("next_id should be > max ID");
8023 assert_eq!(
8024 err,
8025 PaneModelError::NextIdNotGreaterThanExisting {
8026 next_id: id(3),
8027 max_existing: id(3),
8028 }
8029 );
8030 }
8031
8032 #[test]
8033 fn constraints_validate_bounds() {
8034 let constraints = PaneConstraints {
8035 min_width: 8,
8036 min_height: 1,
8037 max_width: Some(4),
8038 max_height: None,
8039 collapsible: false,
8040 margin: None,
8041 padding: None,
8042 };
8043 let err = constraints
8044 .validate(id(5))
8045 .expect_err("max width below min width must fail");
8046 assert_eq!(
8047 err,
8048 PaneModelError::InvalidConstraint {
8049 node_id: id(5),
8050 axis: "width",
8051 min: 8,
8052 max: 4,
8053 }
8054 );
8055 }
8056
8057 #[test]
8058 fn allocator_is_deterministic() {
8059 let mut allocator = PaneIdAllocator::default();
8060 assert_eq!(allocator.allocate().expect("id 1"), id(1));
8061 assert_eq!(allocator.allocate().expect("id 2"), id(2));
8062 assert_eq!(allocator.peek(), id(3));
8063 }
8064
8065 #[test]
8066 fn snapshot_json_shape_contains_forward_compat_fields() {
8067 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8068 let json = serde_json::to_value(tree.to_snapshot()).expect("snapshot should serialize");
8069 assert_eq!(json["schema_version"], serde_json::json!(1));
8070 assert!(json.get("extensions").is_some());
8071 let nodes = json["nodes"]
8072 .as_array()
8073 .expect("nodes should serialize as array");
8074 assert_eq!(nodes.len(), 3);
8075 assert!(nodes[0].get("kind").is_some());
8076 }
8077
8078 #[test]
8079 fn solver_horizontal_ratio_split() {
8080 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8081 let layout = tree
8082 .solve_layout(Rect::new(0, 0, 50, 10))
8083 .expect("layout solve should succeed");
8084
8085 assert_eq!(layout.rect(id(1)), Some(Rect::new(0, 0, 50, 10)));
8086 assert_eq!(layout.rect(id(2)), Some(Rect::new(0, 0, 30, 10)));
8087 assert_eq!(layout.rect(id(3)), Some(Rect::new(30, 0, 20, 10)));
8088 }
8089
8090 #[test]
8091 fn solver_clamps_to_child_minimum_constraints() {
8092 let mut snapshot = make_valid_snapshot();
8093 for node in &mut snapshot.nodes {
8094 if node.id == id(2) {
8095 node.constraints.min_width = 35;
8096 }
8097 }
8098
8099 let tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
8100 let layout = tree
8101 .solve_layout(Rect::new(0, 0, 50, 10))
8102 .expect("layout solve should succeed");
8103
8104 assert_eq!(layout.rect(id(2)), Some(Rect::new(0, 0, 35, 10)));
8105 assert_eq!(layout.rect(id(3)), Some(Rect::new(35, 0, 15, 10)));
8106 }
8107
8108 #[test]
8109 fn solver_rejects_overconstrained_split() {
8110 let mut snapshot = make_valid_snapshot();
8111 for node in &mut snapshot.nodes {
8112 if node.id == id(2) {
8113 node.constraints.min_width = 30;
8114 }
8115 if node.id == id(3) {
8116 node.constraints.min_width = 30;
8117 }
8118 }
8119
8120 let tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
8121 let err = tree
8122 .solve_layout(Rect::new(0, 0, 50, 10))
8123 .expect_err("infeasible constraints should fail");
8124
8125 assert_eq!(
8126 err,
8127 PaneModelError::OverconstrainedSplit {
8128 node_id: id(1),
8129 axis: SplitAxis::Horizontal,
8130 available: 50,
8131 first_min: 30,
8132 first_max: 50,
8133 second_min: 30,
8134 second_max: 50,
8135 }
8136 );
8137 }
8138
8139 #[test]
8140 fn solver_is_deterministic() {
8141 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8142 let first = tree
8143 .solve_layout(Rect::new(0, 0, 79, 17))
8144 .expect("first solve should succeed");
8145 let second = tree
8146 .solve_layout(Rect::new(0, 0, 79, 17))
8147 .expect("second solve should succeed");
8148 assert_eq!(first, second);
8149 }
8150
8151 #[test]
8152 fn solver_reserves_space_for_nested_minima() {
8153 for axis in [SplitAxis::Horizontal, SplitAxis::Vertical] {
8154 let mut snapshot = make_nested_snapshot();
8155 for node in &mut snapshot.nodes {
8156 if let PaneNodeKind::Split(split) = &mut node.kind {
8157 split.axis = axis;
8158 split.ratio = PaneSplitRatio::new(3, 2).expect("ratio");
8159 }
8160 if node.id == id(4) || node.id == id(5) {
8161 node.constraints.min_width = 2;
8162 node.constraints.min_height = 2;
8163 }
8164 }
8165 let tree = PaneTree::from_snapshot(snapshot).expect("nested tree");
8166 let before = tree.to_snapshot();
8167 let layout = tree
8168 .solve_layout(Rect::new(10, 20, 7, 7))
8169 .expect("three leaves fit when descendant minima are respected");
8170 let (left, nested) = match axis {
8171 SplitAxis::Horizontal => (Rect::new(10, 20, 3, 7), Rect::new(13, 20, 4, 7)),
8172 SplitAxis::Vertical => (Rect::new(10, 20, 7, 3), Rect::new(10, 23, 7, 4)),
8173 };
8174 assert_eq!(layout.rect(id(2)), Some(left));
8175 assert_eq!(layout.rect(id(3)), Some(nested));
8176 assert_eq!(
8177 tree.to_snapshot(),
8178 before,
8179 "solving does not mutate history"
8180 );
8181 }
8182 }
8183
8184 #[test]
8185 fn solver_respects_nested_maxima_across_axes() {
8186 for axis in [SplitAxis::Horizontal, SplitAxis::Vertical] {
8187 let mut snapshot = make_nested_snapshot();
8188 for node in &mut snapshot.nodes {
8189 if let PaneNodeKind::Split(split) = &mut node.kind {
8190 split.axis = if node.id == id(1) {
8191 axis
8192 } else if axis == SplitAxis::Horizontal {
8193 SplitAxis::Vertical
8194 } else {
8195 SplitAxis::Horizontal
8196 };
8197 split.ratio = PaneSplitRatio::new(1, 1).expect("ratio");
8198 }
8199 if node.id == id(4) || node.id == id(5) {
8200 match axis {
8201 SplitAxis::Horizontal => node.constraints.max_width = Some(3),
8202 SplitAxis::Vertical => node.constraints.max_height = Some(3),
8203 }
8204 }
8205 }
8206 let tree = PaneTree::from_snapshot(snapshot).expect("nested tree");
8207 let layout = tree
8208 .solve_layout(Rect::new(0, 0, 10, 10))
8209 .expect("remaining space belongs to the uncapped sibling");
8210 let nested = layout.rect(id(3)).expect("nested rectangle");
8211 assert_eq!(
8212 match axis {
8213 SplitAxis::Horizontal => nested.width,
8214 SplitAxis::Vertical => nested.height,
8215 },
8216 3
8217 );
8218 }
8219 }
8220
8221 #[test]
8222 fn solver_descendant_bounds_cover_zero_and_u16_limits() {
8223 for axis in [SplitAxis::Horizontal, SplitAxis::Vertical] {
8224 for (first, second, extent, fits) in [
8225 (0, 0, 0, true),
8226 (32_767, 32_768, u16::MAX, true),
8227 (32_767, 32_768, u16::MAX - 1, false),
8228 (32_768, 32_768, u16::MAX, false),
8229 ] {
8230 let mut snapshot = make_nested_snapshot();
8231 for node in &mut snapshot.nodes {
8232 node.constraints.min_width = 0;
8233 node.constraints.min_height = 0;
8234 if let PaneNodeKind::Split(split) = &mut node.kind {
8235 split.axis = axis;
8236 }
8237 let minimum = if node.id == id(4) {
8238 first
8239 } else if node.id == id(5) {
8240 second
8241 } else {
8242 0
8243 };
8244 match axis {
8245 SplitAxis::Horizontal => node.constraints.min_width = minimum,
8246 SplitAxis::Vertical => node.constraints.min_height = minimum,
8247 }
8248 }
8249 let tree = PaneTree::from_snapshot(snapshot).expect("valid bounds");
8250 let area = match axis {
8251 SplitAxis::Horizontal => Rect::new(0, 0, extent, 1),
8252 SplitAxis::Vertical => Rect::new(0, 0, 1, extent),
8253 };
8254 assert_eq!(
8255 tree.solve_layout(area).is_ok(),
8256 fits,
8257 "{axis:?}: {first}+{second} in {extent}"
8258 );
8259 }
8260 }
8261 }
8262
8263 fn exhaustive_pane_feasibility(
8266 tree: &PaneTree,
8267 node_id: PaneId,
8268 width: u16,
8269 height: u16,
8270 ) -> bool {
8271 let node = tree.node(node_id).expect("oracle node");
8272 let c = node.constraints;
8273 if width < c.min_width
8274 || height < c.min_height
8275 || c.max_width.is_some_and(|max| width > max)
8276 || c.max_height.is_some_and(|max| height > max)
8277 {
8278 return false;
8279 }
8280 match &node.kind {
8281 PaneNodeKind::Leaf(_) => true,
8282 PaneNodeKind::Split(split) => match split.axis {
8283 SplitAxis::Horizontal => (0..=width).any(|first| {
8284 exhaustive_pane_feasibility(tree, split.first, first, height)
8285 && exhaustive_pane_feasibility(tree, split.second, width - first, height)
8286 }),
8287 SplitAxis::Vertical => (0..=height).any(|first| {
8288 exhaustive_pane_feasibility(tree, split.first, width, first)
8289 && exhaustive_pane_feasibility(tree, split.second, width, height - first)
8290 }),
8291 },
8292 }
8293 }
8294
8295 proptest! {
8296 #![proptest_config(ProptestConfig::with_cases(256))]
8297
8298 #[test]
8299 fn solver_matches_exhaustive_nested_feasibility(
8300 bounds in prop::collection::vec((0u16..5, 0u16..5, prop::option::of(0u16..5), prop::option::of(0u16..5)), 5),
8301 axes in any::<[bool; 2]>(),
8302 weights in prop::array::uniform4(1u32..9),
8303 ) {
8304 let mut snapshot = make_nested_snapshot();
8305 let mut split_index = 0;
8306 for (node, (min_width, min_height, width_slack, height_slack)) in snapshot.nodes.iter_mut().zip(bounds) {
8307 node.constraints.min_width = min_width;
8308 node.constraints.min_height = min_height;
8309 node.constraints.max_width = width_slack.map(|slack| min_width + slack);
8310 node.constraints.max_height = height_slack.map(|slack| min_height + slack);
8311 if let PaneNodeKind::Split(split) = &mut node.kind {
8312 split.axis = if axes[split_index] { SplitAxis::Horizontal } else { SplitAxis::Vertical };
8313 split.ratio = PaneSplitRatio::new(weights[split_index * 2], weights[split_index * 2 + 1]).expect("positive weights");
8314 split_index += 1;
8315 }
8316 }
8317 let tree = PaneTree::from_snapshot(snapshot).expect("valid individual constraints");
8318 let before = tree.to_snapshot();
8319 for width in 0..=12 {
8320 for height in 0..=12 {
8321 let expected = exhaustive_pane_feasibility(&tree, tree.root(), width, height);
8322 let actual = tree.solve_layout(Rect::new(2, 3, width, height));
8323 prop_assert_eq!(actual.is_ok(), expected, "viewport {}x{}, result {:?}, tree {:?}", width, height, actual, before);
8324 if let Ok(layout) = actual {
8325 for node in tree.nodes() {
8326 let rect = layout.rect(node.id).expect("every node has a rectangle");
8327 prop_assert!(rect.x >= 2 && rect.y >= 3);
8328 prop_assert!(rect.right() <= 2 + width && rect.bottom() <= 3 + height);
8329 prop_assert!(exhaustive_pane_feasibility(&tree, node.id, rect.width, rect.height));
8330 }
8331 }
8332 }
8333 }
8334 prop_assert_eq!(tree.to_snapshot(), before);
8335 }
8336 }
8337
8338 #[test]
8339 fn split_leaf_wraps_existing_leaf_with_new_split() {
8340 let mut tree = PaneTree::singleton("root");
8341 let outcome = tree
8342 .apply_operation(
8343 7,
8344 PaneOperation::SplitLeaf {
8345 target: id(1),
8346 axis: SplitAxis::Horizontal,
8347 ratio: PaneSplitRatio::new(3, 2).expect("valid ratio"),
8348 placement: PanePlacement::ExistingFirst,
8349 new_leaf: PaneLeaf::new("new"),
8350 },
8351 )
8352 .expect("split should succeed");
8353
8354 assert_eq!(outcome.operation_id, 7);
8355 assert_eq!(outcome.kind, PaneOperationKind::SplitLeaf);
8356 assert_ne!(outcome.before_hash, outcome.after_hash);
8357 assert_eq!(tree.root(), id(2));
8358
8359 let root = tree.node(id(2)).expect("split node exists");
8360 let PaneNodeKind::Split(split) = &root.kind else {
8361 unreachable!("root should be split");
8362 };
8363 assert_eq!(split.first, id(1));
8364 assert_eq!(split.second, id(3));
8365
8366 let original = tree.node(id(1)).expect("original leaf exists");
8367 assert_eq!(original.parent, Some(id(2)));
8368 assert!(matches!(original.kind, PaneNodeKind::Leaf(_)));
8369
8370 let new_leaf = tree.node(id(3)).expect("new leaf exists");
8371 assert_eq!(new_leaf.parent, Some(id(2)));
8372 let PaneNodeKind::Leaf(leaf) = &new_leaf.kind else {
8373 unreachable!("new node must be leaf");
8374 };
8375 assert_eq!(leaf.surface_key, "new");
8376 assert!(tree.validate().is_ok());
8377 }
8378
8379 #[test]
8380 fn touched_nodes_compact_storage_holds_correct_content() {
8381 let mut tree = PaneTree::singleton("root");
8384 let split = tree
8385 .apply_operation(
8386 1,
8387 PaneOperation::SplitLeaf {
8388 target: id(1),
8389 axis: SplitAxis::Horizontal,
8390 ratio: PaneSplitRatio::new(1, 1).expect("ratio"),
8391 placement: PanePlacement::ExistingFirst,
8392 new_leaf: PaneLeaf::new("b"),
8393 },
8394 )
8395 .expect("split should succeed");
8396 assert!(split.touched_nodes.contains(&id(1)));
8398
8399 let resize = tree
8401 .apply_operation(
8402 2,
8403 PaneOperation::SetSplitRatio {
8404 split: id(2),
8405 ratio: PaneSplitRatio::new(3, 1).expect("ratio"),
8406 },
8407 )
8408 .expect("resize should succeed");
8409 assert_eq!(resize.touched_nodes.to_vec(), vec![id(2)]);
8410
8411 let rejected = tree
8413 .apply_operation(
8414 3,
8415 PaneOperation::SetSplitRatio {
8416 split: id(999),
8417 ratio: PaneSplitRatio::new(1, 1).expect("ratio"),
8418 },
8419 )
8420 .expect_err("missing split must be rejected");
8421 assert_eq!(rejected.touched_nodes.to_vec(), vec![id(999)]);
8422 }
8423
8424 #[test]
8425 fn close_node_promotes_sibling_and_removes_split_parent() {
8426 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8427 let outcome = tree
8428 .apply_operation(8, PaneOperation::CloseNode { target: id(2) })
8429 .expect("close should succeed");
8430 assert_eq!(outcome.kind, PaneOperationKind::CloseNode);
8431
8432 assert_eq!(tree.root(), id(3));
8433 assert!(tree.node(id(1)).is_none());
8434 assert!(tree.node(id(2)).is_none());
8435 assert_eq!(tree.node(id(3)).and_then(|node| node.parent), None);
8436 assert!(tree.validate().is_ok());
8437 }
8438
8439 #[test]
8440 fn close_root_is_rejected_with_stable_hashes() {
8441 let mut tree = PaneTree::singleton("root");
8442 let err = tree
8443 .apply_operation(9, PaneOperation::CloseNode { target: id(1) })
8444 .expect_err("closing root must fail");
8445
8446 assert_eq!(err.operation_id, 9);
8447 assert_eq!(err.kind, PaneOperationKind::CloseNode);
8448 assert_eq!(
8449 err.reason,
8450 PaneOperationFailure::CannotCloseRoot { node_id: id(1) }
8451 );
8452 assert_eq!(err.before_hash, err.after_hash);
8453 assert_eq!(tree.root(), id(1));
8454 assert!(tree.validate().is_ok());
8455 }
8456
8457 #[test]
8458 fn move_subtree_wraps_target_and_detaches_old_parent() {
8459 let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
8460 let outcome = tree
8461 .apply_operation(
8462 10,
8463 PaneOperation::MoveSubtree {
8464 source: id(4),
8465 target: id(2),
8466 axis: SplitAxis::Vertical,
8467 ratio: PaneSplitRatio::new(2, 1).expect("valid ratio"),
8468 placement: PanePlacement::ExistingFirst,
8469 },
8470 )
8471 .expect("move should succeed");
8472 assert_eq!(outcome.kind, PaneOperationKind::MoveSubtree);
8473
8474 assert!(
8475 tree.node(id(3)).is_none(),
8476 "old split parent should be removed"
8477 );
8478 assert_eq!(tree.node(id(5)).and_then(|node| node.parent), Some(id(1)));
8479
8480 let inserted_split = tree
8481 .nodes()
8482 .find(|node| matches!(node.kind, PaneNodeKind::Split(_)) && node.id.get() >= 6)
8483 .expect("new split should exist");
8484 let PaneNodeKind::Split(split) = &inserted_split.kind else {
8485 unreachable!();
8486 };
8487 assert_eq!(split.first, id(2));
8488 assert_eq!(split.second, id(4));
8489 assert_eq!(
8490 tree.node(id(2)).and_then(|node| node.parent),
8491 Some(inserted_split.id)
8492 );
8493 assert_eq!(
8494 tree.node(id(4)).and_then(|node| node.parent),
8495 Some(inserted_split.id)
8496 );
8497 assert!(tree.validate().is_ok());
8498 }
8499
8500 #[test]
8501 fn move_subtree_rejects_ancestor_target() {
8502 let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
8503 let err = tree
8504 .apply_operation(
8505 11,
8506 PaneOperation::MoveSubtree {
8507 source: id(3),
8508 target: id(4),
8509 axis: SplitAxis::Horizontal,
8510 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
8511 placement: PanePlacement::ExistingFirst,
8512 },
8513 )
8514 .expect_err("ancestor move must fail");
8515
8516 assert_eq!(err.kind, PaneOperationKind::MoveSubtree);
8517 assert_eq!(
8518 err.reason,
8519 PaneOperationFailure::AncestorConflict {
8520 ancestor: id(3),
8521 descendant: id(4),
8522 }
8523 );
8524 assert!(tree.validate().is_ok());
8525 }
8526
8527 #[test]
8528 fn swap_nodes_exchanges_sibling_positions() {
8529 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8530 let outcome = tree
8531 .apply_operation(
8532 12,
8533 PaneOperation::SwapNodes {
8534 first: id(2),
8535 second: id(3),
8536 },
8537 )
8538 .expect("swap should succeed");
8539 assert_eq!(outcome.kind, PaneOperationKind::SwapNodes);
8540
8541 let root = tree.node(id(1)).expect("root exists");
8542 let PaneNodeKind::Split(split) = &root.kind else {
8543 unreachable!("root should remain split");
8544 };
8545 assert_eq!(split.first, id(3));
8546 assert_eq!(split.second, id(2));
8547 assert_eq!(tree.node(id(2)).and_then(|node| node.parent), Some(id(1)));
8548 assert_eq!(tree.node(id(3)).and_then(|node| node.parent), Some(id(1)));
8549 assert!(tree.validate().is_ok());
8550 }
8551
8552 #[test]
8553 fn swap_nodes_rejects_ancestor_relation() {
8554 let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
8555 let err = tree
8556 .apply_operation(
8557 13,
8558 PaneOperation::SwapNodes {
8559 first: id(3),
8560 second: id(4),
8561 },
8562 )
8563 .expect_err("ancestor swap must fail");
8564
8565 assert_eq!(err.kind, PaneOperationKind::SwapNodes);
8566 assert_eq!(
8567 err.reason,
8568 PaneOperationFailure::AncestorConflict {
8569 ancestor: id(3),
8570 descendant: id(4),
8571 }
8572 );
8573 assert!(tree.validate().is_ok());
8574 }
8575
8576 #[test]
8577 fn normalize_ratios_canonicalizes_non_reduced_values() {
8578 let mut snapshot = make_valid_snapshot();
8579 for node in &mut snapshot.nodes {
8580 if let PaneNodeKind::Split(split) = &mut node.kind {
8581 split.ratio = PaneSplitRatio {
8582 numerator: 12,
8583 denominator: 8,
8584 };
8585 }
8586 }
8587
8588 let mut tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
8589 let outcome = tree
8590 .apply_operation(14, PaneOperation::NormalizeRatios)
8591 .expect("normalize should succeed");
8592 assert_eq!(outcome.kind, PaneOperationKind::NormalizeRatios);
8593
8594 let root = tree.node(id(1)).expect("root exists");
8595 let PaneNodeKind::Split(split) = &root.kind else {
8596 unreachable!("root should be split");
8597 };
8598 assert_eq!(split.ratio.numerator(), 3);
8599 assert_eq!(split.ratio.denominator(), 2);
8600 }
8601
8602 #[test]
8603 fn transaction_commit_persists_mutations_and_journal_order() {
8604 let tree = PaneTree::singleton("root");
8605 let mut tx = tree.begin_transaction(77);
8606
8607 let split = tx
8608 .apply_operation(
8609 100,
8610 PaneOperation::SplitLeaf {
8611 target: id(1),
8612 axis: SplitAxis::Horizontal,
8613 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
8614 placement: PanePlacement::ExistingFirst,
8615 new_leaf: PaneLeaf::new("secondary"),
8616 },
8617 )
8618 .expect("split should succeed");
8619 assert_eq!(split.kind, PaneOperationKind::SplitLeaf);
8620
8621 let normalize = tx
8622 .apply_operation(101, PaneOperation::NormalizeRatios)
8623 .expect("normalize should succeed");
8624 assert_eq!(normalize.kind, PaneOperationKind::NormalizeRatios);
8625
8626 let outcome = tx.commit();
8627 assert!(outcome.committed);
8628 assert_eq!(outcome.transaction_id, 77);
8629 assert_eq!(outcome.tree.root(), id(2));
8630 assert_eq!(outcome.journal.len(), 2);
8631 assert_eq!(outcome.journal[0].sequence, 1);
8632 assert_eq!(outcome.journal[1].sequence, 2);
8633 assert_eq!(outcome.journal[0].operation_id, 100);
8634 assert_eq!(outcome.journal[1].operation_id, 101);
8635 assert_eq!(
8636 outcome.journal[0].result,
8637 PaneOperationJournalResult::Applied
8638 );
8639 assert_eq!(
8640 outcome.journal[1].result,
8641 PaneOperationJournalResult::Applied
8642 );
8643 }
8644
8645 #[test]
8646 fn transaction_rollback_discards_mutations() {
8647 let tree = PaneTree::singleton("root");
8648 let before_hash = tree.state_hash();
8649 let mut tx = tree.begin_transaction(78);
8650
8651 tx.apply_operation(
8652 200,
8653 PaneOperation::SplitLeaf {
8654 target: id(1),
8655 axis: SplitAxis::Vertical,
8656 ratio: PaneSplitRatio::new(2, 1).expect("valid ratio"),
8657 placement: PanePlacement::ExistingFirst,
8658 new_leaf: PaneLeaf::new("extra"),
8659 },
8660 )
8661 .expect("split should succeed");
8662
8663 let outcome = tx.rollback();
8664 assert!(!outcome.committed);
8665 assert_eq!(outcome.tree.state_hash(), before_hash);
8666 assert_eq!(outcome.tree.root(), id(1));
8667 assert_eq!(outcome.journal.len(), 1);
8668 assert_eq!(outcome.journal[0].operation_id, 200);
8669 }
8670
8671 #[test]
8672 fn transaction_journals_rejected_operation_without_mutation() {
8673 let tree = PaneTree::singleton("root");
8674 let mut tx = tree.begin_transaction(79);
8675 let before_hash = tx.tree().state_hash();
8676
8677 let err = tx
8678 .apply_operation(300, PaneOperation::CloseNode { target: id(1) })
8679 .expect_err("close root should fail");
8680 assert_eq!(err.before_hash, err.after_hash);
8681 assert_eq!(tx.tree().state_hash(), before_hash);
8682
8683 let journal = tx.journal();
8684 assert_eq!(journal.len(), 1);
8685 assert_eq!(journal[0].operation_id, 300);
8686 let PaneOperationJournalResult::Rejected { reason } = &journal[0].result else {
8687 unreachable!("journal entry should be rejected");
8688 };
8689 assert!(reason.contains("cannot close root"));
8690 }
8691
8692 #[test]
8693 fn transaction_journal_is_deterministic_for_equivalent_runs() {
8694 let base = PaneTree::singleton("root");
8695
8696 let mut first_tx = base.begin_transaction(80);
8697 first_tx
8698 .apply_operation(
8699 1,
8700 PaneOperation::SplitLeaf {
8701 target: id(1),
8702 axis: SplitAxis::Horizontal,
8703 ratio: PaneSplitRatio::new(3, 1).expect("valid ratio"),
8704 placement: PanePlacement::IncomingFirst,
8705 new_leaf: PaneLeaf::new("new"),
8706 },
8707 )
8708 .expect("split should succeed");
8709 first_tx
8710 .apply_operation(2, PaneOperation::NormalizeRatios)
8711 .expect("normalize should succeed");
8712 let first = first_tx.commit();
8713
8714 let mut second_tx = base.begin_transaction(80);
8715 second_tx
8716 .apply_operation(
8717 1,
8718 PaneOperation::SplitLeaf {
8719 target: id(1),
8720 axis: SplitAxis::Horizontal,
8721 ratio: PaneSplitRatio::new(3, 1).expect("valid ratio"),
8722 placement: PanePlacement::IncomingFirst,
8723 new_leaf: PaneLeaf::new("new"),
8724 },
8725 )
8726 .expect("split should succeed");
8727 second_tx
8728 .apply_operation(2, PaneOperation::NormalizeRatios)
8729 .expect("normalize should succeed");
8730 let second = second_tx.commit();
8731
8732 assert_eq!(first.tree.state_hash(), second.tree.state_hash());
8733 assert_eq!(first.journal, second.journal);
8734 }
8735
8736 #[test]
8737 fn invariant_report_detects_parent_mismatch_and_orphan() {
8738 let mut snapshot = make_valid_snapshot();
8739 for node in &mut snapshot.nodes {
8740 if node.id == id(2) {
8741 node.parent = Some(id(3));
8742 }
8743 }
8744 snapshot
8745 .nodes
8746 .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8747 snapshot.next_id = id(11);
8748
8749 let report = snapshot.invariant_report();
8750 assert!(report.has_errors());
8751 assert!(
8752 report
8753 .issues
8754 .iter()
8755 .any(|issue| issue.code == PaneInvariantCode::ParentMismatch)
8756 );
8757 assert!(
8758 report
8759 .issues
8760 .iter()
8761 .any(|issue| issue.code == PaneInvariantCode::UnreachableNode)
8762 );
8763 }
8764
8765 #[test]
8766 fn repair_safe_normalizes_ratio_repairs_parents_and_removes_orphans() {
8767 let mut snapshot = make_valid_snapshot();
8768 for node in &mut snapshot.nodes {
8769 if node.id == id(1) {
8770 node.parent = Some(id(3));
8771 let PaneNodeKind::Split(split) = &mut node.kind else {
8772 unreachable!("root should be split");
8773 };
8774 split.ratio = PaneSplitRatio {
8775 numerator: 12,
8776 denominator: 8,
8777 };
8778 }
8779 if node.id == id(2) {
8780 node.parent = Some(id(3));
8781 }
8782 }
8783 snapshot
8784 .nodes
8785 .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8786 snapshot.next_id = id(11);
8787
8788 let repaired = snapshot.repair_safe().expect("repair should succeed");
8789 assert_ne!(repaired.before_hash, repaired.after_hash);
8790 assert!(repaired.tree.validate().is_ok());
8791 assert!(!repaired.report_after.has_errors());
8792 assert!(
8793 repaired
8794 .actions
8795 .iter()
8796 .any(|action| matches!(action, PaneRepairAction::NormalizeRatio { node_id, .. } if *node_id == id(1)))
8797 );
8798 assert!(
8799 repaired
8800 .actions
8801 .iter()
8802 .any(|action| matches!(action, PaneRepairAction::ReparentNode { node_id, .. } if *node_id == id(1)))
8803 );
8804 assert!(
8805 repaired
8806 .actions
8807 .iter()
8808 .any(|action| matches!(action, PaneRepairAction::RemoveOrphanNode { node_id } if *node_id == id(10)))
8809 );
8810 }
8811
8812 #[test]
8813 fn repair_safe_rejects_unsafe_topology() {
8814 let mut snapshot = make_valid_snapshot();
8815 snapshot.nodes.retain(|node| node.id != id(3));
8816
8817 let err = snapshot
8818 .repair_safe()
8819 .expect_err("missing-child topology must be rejected");
8820 assert!(matches!(
8821 err.reason,
8822 PaneRepairFailure::UnsafeIssuesPresent { .. }
8823 ));
8824 let PaneRepairFailure::UnsafeIssuesPresent { codes } = err.reason else {
8825 unreachable!("expected unsafe issue failure");
8826 };
8827 assert!(codes.contains(&PaneInvariantCode::MissingChild));
8828 }
8829
8830 #[test]
8831 fn repair_safe_is_deterministic_for_equivalent_snapshot() {
8832 let mut snapshot = make_valid_snapshot();
8833 for node in &mut snapshot.nodes {
8834 if node.id == id(1) {
8835 let PaneNodeKind::Split(split) = &mut node.kind else {
8836 unreachable!("root should be split");
8837 };
8838 split.ratio = PaneSplitRatio {
8839 numerator: 12,
8840 denominator: 8,
8841 };
8842 }
8843 }
8844 snapshot
8845 .nodes
8846 .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8847 snapshot.next_id = id(11);
8848
8849 let first = snapshot.clone().repair_safe().expect("first repair");
8850 let second = snapshot.repair_safe().expect("second repair");
8851
8852 assert_eq!(first.tree.state_hash(), second.tree.state_hash());
8853 assert_eq!(first.actions, second.actions);
8854 assert_eq!(first.report_after, second.report_after);
8855 }
8856
8857 fn default_target() -> PaneResizeTarget {
8858 PaneResizeTarget {
8859 split_id: id(7),
8860 axis: SplitAxis::Horizontal,
8861 }
8862 }
8863
8864 #[test]
8865 fn semantic_input_event_fixture_round_trip_covers_all_variants() {
8866 let mut pointer_down = PaneSemanticInputEvent::new(
8867 1,
8868 PaneSemanticInputEventKind::PointerDown {
8869 target: default_target(),
8870 pointer_id: 11,
8871 button: PanePointerButton::Primary,
8872 position: PanePointerPosition::new(42, 9),
8873 },
8874 );
8875 pointer_down.modifiers = PaneModifierSnapshot {
8876 shift: true,
8877 alt: false,
8878 ctrl: true,
8879 meta: false,
8880 };
8881 let pointer_down_fixture = r#"{"schema_version":1,"sequence":1,"modifiers":{"shift":true,"alt":false,"ctrl":true,"meta":false},"event":"pointer_down","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":42,"y":9},"extensions":{}}"#;
8882
8883 let pointer_move = PaneSemanticInputEvent::new(
8884 2,
8885 PaneSemanticInputEventKind::PointerMove {
8886 target: default_target(),
8887 pointer_id: 11,
8888 position: PanePointerPosition::new(45, 8),
8889 delta_x: 3,
8890 delta_y: -1,
8891 },
8892 );
8893 let pointer_move_fixture = r#"{"schema_version":1,"sequence":2,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_move","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"position":{"x":45,"y":8},"delta_x":3,"delta_y":-1,"extensions":{}}"#;
8894
8895 let pointer_up = PaneSemanticInputEvent::new(
8896 3,
8897 PaneSemanticInputEventKind::PointerUp {
8898 target: default_target(),
8899 pointer_id: 11,
8900 button: PanePointerButton::Primary,
8901 position: PanePointerPosition::new(45, 8),
8902 },
8903 );
8904 let pointer_up_fixture = r#"{"schema_version":1,"sequence":3,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_up","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":45,"y":8},"extensions":{}}"#;
8905
8906 let wheel_nudge = PaneSemanticInputEvent::new(
8907 4,
8908 PaneSemanticInputEventKind::WheelNudge {
8909 target: default_target(),
8910 lines: -2,
8911 },
8912 );
8913 let wheel_nudge_fixture = r#"{"schema_version":1,"sequence":4,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"wheel_nudge","target":{"split_id":7,"axis":"horizontal"},"lines":-2,"extensions":{}}"#;
8914
8915 let keyboard_resize = PaneSemanticInputEvent::new(
8916 5,
8917 PaneSemanticInputEventKind::KeyboardResize {
8918 target: default_target(),
8919 direction: PaneResizeDirection::Increase,
8920 units: 3,
8921 },
8922 );
8923 let keyboard_resize_fixture = r#"{"schema_version":1,"sequence":5,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"keyboard_resize","target":{"split_id":7,"axis":"horizontal"},"direction":"increase","units":3,"extensions":{}}"#;
8924
8925 let cancel = PaneSemanticInputEvent::new(
8926 6,
8927 PaneSemanticInputEventKind::Cancel {
8928 target: Some(default_target()),
8929 reason: PaneCancelReason::PointerCancel,
8930 },
8931 );
8932 let cancel_fixture = r#"{"schema_version":1,"sequence":6,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"cancel","target":{"split_id":7,"axis":"horizontal"},"reason":"pointer_cancel","extensions":{}}"#;
8933
8934 let blur =
8935 PaneSemanticInputEvent::new(7, PaneSemanticInputEventKind::Blur { target: None });
8936 let blur_fixture = r#"{"schema_version":1,"sequence":7,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"blur","target":null,"extensions":{}}"#;
8937
8938 let fixtures = [
8939 ("pointer_down", pointer_down_fixture, pointer_down),
8940 ("pointer_move", pointer_move_fixture, pointer_move),
8941 ("pointer_up", pointer_up_fixture, pointer_up),
8942 ("wheel_nudge", wheel_nudge_fixture, wheel_nudge),
8943 ("keyboard_resize", keyboard_resize_fixture, keyboard_resize),
8944 ("cancel", cancel_fixture, cancel),
8945 ("blur", blur_fixture, blur),
8946 ];
8947
8948 for (name, fixture, expected) in fixtures {
8949 let parsed: PaneSemanticInputEvent =
8950 serde_json::from_str(fixture).expect("fixture should parse");
8951 assert_eq!(
8952 parsed, expected,
8953 "{name} fixture should match expected shape"
8954 );
8955 parsed.validate().expect("fixture should validate");
8956 let encoded = serde_json::to_string(&parsed).expect("event should encode");
8957 assert_eq!(encoded, fixture, "{name} fixture should be canonical");
8958 }
8959 }
8960
8961 #[test]
8962 fn semantic_input_event_defaults_schema_version_to_current() {
8963 let fixture = r#"{"sequence":9,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"blur","target":null,"extensions":{}}"#;
8964 let parsed: PaneSemanticInputEvent =
8965 serde_json::from_str(fixture).expect("fixture should parse");
8966 assert_eq!(
8967 parsed.schema_version,
8968 PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION
8969 );
8970 parsed.validate().expect("defaulted event should validate");
8971 }
8972
8973 #[test]
8974 fn semantic_input_event_rejects_invalid_invariants() {
8975 let target = default_target();
8976
8977 let mut schema_version = PaneSemanticInputEvent::new(
8978 1,
8979 PaneSemanticInputEventKind::Blur {
8980 target: Some(target),
8981 },
8982 );
8983 schema_version.schema_version = 99;
8984 assert_eq!(
8985 schema_version.validate(),
8986 Err(PaneSemanticInputEventError::UnsupportedSchemaVersion {
8987 version: 99,
8988 expected: PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION
8989 })
8990 );
8991
8992 let sequence = PaneSemanticInputEvent::new(
8993 0,
8994 PaneSemanticInputEventKind::Blur {
8995 target: Some(target),
8996 },
8997 );
8998 assert_eq!(
8999 sequence.validate(),
9000 Err(PaneSemanticInputEventError::ZeroSequence)
9001 );
9002
9003 let pointer = PaneSemanticInputEvent::new(
9004 2,
9005 PaneSemanticInputEventKind::PointerDown {
9006 target,
9007 pointer_id: 0,
9008 button: PanePointerButton::Primary,
9009 position: PanePointerPosition::new(0, 0),
9010 },
9011 );
9012 assert_eq!(
9013 pointer.validate(),
9014 Err(PaneSemanticInputEventError::ZeroPointerId)
9015 );
9016
9017 let wheel = PaneSemanticInputEvent::new(
9018 3,
9019 PaneSemanticInputEventKind::WheelNudge { target, lines: 0 },
9020 );
9021 assert_eq!(
9022 wheel.validate(),
9023 Err(PaneSemanticInputEventError::ZeroWheelLines)
9024 );
9025
9026 let keyboard = PaneSemanticInputEvent::new(
9027 4,
9028 PaneSemanticInputEventKind::KeyboardResize {
9029 target,
9030 direction: PaneResizeDirection::Decrease,
9031 units: 0,
9032 },
9033 );
9034 assert_eq!(
9035 keyboard.validate(),
9036 Err(PaneSemanticInputEventError::ZeroResizeUnits)
9037 );
9038 }
9039
9040 #[test]
9041 fn semantic_input_trace_fixture_round_trip_and_checksum_validation() {
9042 let fixture = r#"{"metadata":{"schema_version":1,"seed":7,"start_unix_ms":1700000000000,"host":"terminal","checksum":0},"events":[{"schema_version":1,"sequence":1,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_down","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":10,"y":4},"extensions":{}},{"schema_version":1,"sequence":2,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_move","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"position":{"x":13,"y":4},"delta_x":0,"delta_y":0,"extensions":{}},{"schema_version":1,"sequence":3,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_move","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"position":{"x":15,"y":6},"delta_x":0,"delta_y":0,"extensions":{}},{"schema_version":1,"sequence":4,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_up","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":16,"y":6},"extensions":{}}]}"#;
9043
9044 let parsed: PaneSemanticInputTrace =
9045 serde_json::from_str(fixture).expect("trace fixture should parse");
9046 let checksum_mismatch = parsed
9047 .validate()
9048 .expect_err("fixture checksum=0 should fail validation");
9049 assert!(matches!(
9050 checksum_mismatch,
9051 PaneSemanticInputTraceError::ChecksumMismatch { recorded: 0, .. }
9052 ));
9053
9054 let mut canonical = parsed;
9055 canonical.metadata.checksum = canonical.recompute_checksum();
9056 canonical
9057 .validate()
9058 .expect("canonicalized fixture should validate");
9059 let encoded = serde_json::to_string(&canonical).expect("trace should encode");
9060 let reparsed: PaneSemanticInputTrace =
9061 serde_json::from_str(&encoded).expect("encoded fixture should parse");
9062 assert_eq!(reparsed, canonical);
9063 assert_eq!(reparsed.metadata.checksum, reparsed.recompute_checksum());
9064 }
9065
9066 #[test]
9067 fn semantic_input_trace_rejects_out_of_order_sequence() {
9068 let target = default_target();
9069 let mut trace = PaneSemanticInputTrace::new(
9070 42,
9071 1_700_000_000_111,
9072 "web",
9073 vec![
9074 PaneSemanticInputEvent::new(
9075 1,
9076 PaneSemanticInputEventKind::PointerDown {
9077 target,
9078 pointer_id: 9,
9079 button: PanePointerButton::Primary,
9080 position: PanePointerPosition::new(0, 0),
9081 },
9082 ),
9083 PaneSemanticInputEvent::new(
9084 2,
9085 PaneSemanticInputEventKind::PointerMove {
9086 target,
9087 pointer_id: 9,
9088 position: PanePointerPosition::new(2, 0),
9089 delta_x: 0,
9090 delta_y: 0,
9091 },
9092 ),
9093 PaneSemanticInputEvent::new(
9094 3,
9095 PaneSemanticInputEventKind::PointerUp {
9096 target,
9097 pointer_id: 9,
9098 button: PanePointerButton::Primary,
9099 position: PanePointerPosition::new(2, 0),
9100 },
9101 ),
9102 ],
9103 )
9104 .expect("trace should construct");
9105
9106 trace.events[2].sequence = 2;
9107 trace.metadata.checksum = trace.recompute_checksum();
9108 assert_eq!(
9109 trace.validate(),
9110 Err(PaneSemanticInputTraceError::SequenceOutOfOrder {
9111 index: 2,
9112 previous: 2,
9113 current: 2
9114 })
9115 );
9116 }
9117
9118 #[test]
9119 fn semantic_replay_fixture_runner_produces_diff_artifacts() {
9120 let target = default_target();
9121 let trace = PaneSemanticInputTrace::new(
9122 99,
9123 1_700_000_000_222,
9124 "terminal",
9125 vec![
9126 PaneSemanticInputEvent::new(
9127 1,
9128 PaneSemanticInputEventKind::PointerDown {
9129 target,
9130 pointer_id: 11,
9131 button: PanePointerButton::Primary,
9132 position: PanePointerPosition::new(10, 4),
9133 },
9134 ),
9135 PaneSemanticInputEvent::new(
9136 2,
9137 PaneSemanticInputEventKind::PointerMove {
9138 target,
9139 pointer_id: 11,
9140 position: PanePointerPosition::new(13, 4),
9141 delta_x: 0,
9142 delta_y: 0,
9143 },
9144 ),
9145 PaneSemanticInputEvent::new(
9146 3,
9147 PaneSemanticInputEventKind::PointerMove {
9148 target,
9149 pointer_id: 11,
9150 position: PanePointerPosition::new(15, 6),
9151 delta_x: 0,
9152 delta_y: 0,
9153 },
9154 ),
9155 PaneSemanticInputEvent::new(
9156 4,
9157 PaneSemanticInputEventKind::PointerUp {
9158 target,
9159 pointer_id: 11,
9160 button: PanePointerButton::Primary,
9161 position: PanePointerPosition::new(16, 6),
9162 },
9163 ),
9164 ],
9165 )
9166 .expect("trace should construct");
9167
9168 let mut baseline_machine = PaneDragResizeMachine::default();
9169 let baseline = trace
9170 .replay(&mut baseline_machine)
9171 .expect("baseline replay should pass");
9172 let fixture = PaneSemanticReplayFixture {
9173 trace: trace.clone(),
9174 expected_transitions: baseline.transitions.clone(),
9175 expected_final_state: baseline.final_state,
9176 };
9177
9178 let mut pass_machine = PaneDragResizeMachine::default();
9179 let pass_report = fixture
9180 .run(&mut pass_machine)
9181 .expect("fixture replay should succeed");
9182 assert!(pass_report.passed);
9183 assert!(pass_report.diffs.is_empty());
9184
9185 let mut mismatch_fixture = fixture.clone();
9186 mismatch_fixture.expected_transitions[1].transition_id += 77;
9187 mismatch_fixture.expected_final_state = PaneDragResizeState::Armed {
9188 target,
9189 pointer_id: 11,
9190 origin: PanePointerPosition::new(10, 4),
9191 current: PanePointerPosition::new(10, 4),
9192 started_sequence: 1,
9193 };
9194
9195 let mut mismatch_machine = PaneDragResizeMachine::default();
9196 let mismatch_report = mismatch_fixture
9197 .run(&mut mismatch_machine)
9198 .expect("mismatch replay should still execute");
9199 assert!(!mismatch_report.passed);
9200 assert!(
9201 mismatch_report
9202 .diffs
9203 .iter()
9204 .any(|diff| diff.kind == PaneSemanticReplayDiffKind::TransitionMismatch)
9205 );
9206 assert!(
9207 mismatch_report
9208 .diffs
9209 .iter()
9210 .any(|diff| diff.kind == PaneSemanticReplayDiffKind::FinalStateMismatch)
9211 );
9212 }
9213
9214 fn default_coordinate_normalizer() -> PaneCoordinateNormalizer {
9215 PaneCoordinateNormalizer::new(
9216 PanePointerPosition::new(100, 50),
9217 PanePointerPosition::new(20, 10),
9218 8,
9219 16,
9220 PaneScaleFactor::new(2, 1).expect("valid dpr"),
9221 PaneScaleFactor::ONE,
9222 PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9223 )
9224 .expect("normalizer should be valid")
9225 }
9226
9227 #[test]
9228 fn coordinate_normalizer_css_device_and_cell_pipeline() {
9229 let normalizer = default_coordinate_normalizer();
9230
9231 let css = normalizer
9232 .normalize(PaneInputCoordinate::CssPixels {
9233 position: PanePointerPosition::new(116, 82),
9234 })
9235 .expect("css normalization should succeed");
9236 assert_eq!(
9237 css,
9238 PaneNormalizedCoordinate {
9239 global_cell: PanePointerPosition::new(22, 12),
9240 local_cell: PanePointerPosition::new(2, 2),
9241 local_css: PanePointerPosition::new(16, 32),
9242 }
9243 );
9244
9245 let device = normalizer
9246 .normalize(PaneInputCoordinate::DevicePixels {
9247 position: PanePointerPosition::new(232, 164),
9248 })
9249 .expect("device normalization should match css");
9250 assert_eq!(device, css);
9251
9252 let cell = normalizer
9253 .normalize(PaneInputCoordinate::Cell {
9254 position: PanePointerPosition::new(3, 1),
9255 })
9256 .expect("cell normalization should succeed");
9257 assert_eq!(
9258 cell,
9259 PaneNormalizedCoordinate {
9260 global_cell: PanePointerPosition::new(23, 11),
9261 local_cell: PanePointerPosition::new(3, 1),
9262 local_css: PanePointerPosition::new(24, 16),
9263 }
9264 );
9265 }
9266
9267 #[test]
9268 fn coordinate_normalizer_zoom_and_rounding_tie_breaks_are_deterministic() {
9269 let zoomed = PaneCoordinateNormalizer::new(
9270 PanePointerPosition::new(100, 50),
9271 PanePointerPosition::new(0, 0),
9272 8,
9273 8,
9274 PaneScaleFactor::ONE,
9275 PaneScaleFactor::new(5, 4).expect("valid zoom"),
9276 PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9277 )
9278 .expect("zoomed normalizer should be valid");
9279
9280 let zoomed_point = zoomed
9281 .normalize(PaneInputCoordinate::CssPixels {
9282 position: PanePointerPosition::new(120, 70),
9283 })
9284 .expect("zoomed normalization should succeed");
9285 assert_eq!(zoomed_point.local_css, PanePointerPosition::new(16, 16));
9286 assert_eq!(zoomed_point.local_cell, PanePointerPosition::new(2, 2));
9287
9288 let nearest = PaneCoordinateNormalizer::new(
9289 PanePointerPosition::new(0, 0),
9290 PanePointerPosition::new(0, 0),
9291 10,
9292 10,
9293 PaneScaleFactor::ONE,
9294 PaneScaleFactor::ONE,
9295 PaneCoordinateRoundingPolicy::NearestHalfTowardNegativeInfinity,
9296 )
9297 .expect("nearest normalizer should be valid");
9298
9299 let positive_tie = nearest
9300 .normalize(PaneInputCoordinate::CssPixels {
9301 position: PanePointerPosition::new(15, 0),
9302 })
9303 .expect("positive tie should normalize");
9304 let positive_above_tie = nearest
9305 .normalize(PaneInputCoordinate::CssPixels {
9306 position: PanePointerPosition::new(16, 0),
9307 })
9308 .expect("positive > half should normalize");
9309 let negative_tie = nearest
9310 .normalize(PaneInputCoordinate::CssPixels {
9311 position: PanePointerPosition::new(-15, 0),
9312 })
9313 .expect("negative tie should normalize");
9314
9315 assert_eq!(positive_tie.local_cell.x, 1);
9316 assert_eq!(positive_above_tie.local_cell.x, 2);
9317 assert_eq!(negative_tie.local_cell.x, -2);
9318 }
9319
9320 #[test]
9321 fn coordinate_normalizer_rejects_invalid_configuration() {
9322 assert_eq!(
9323 PaneScaleFactor::new(0, 1).expect_err("zero numerator must fail"),
9324 PaneCoordinateNormalizationError::InvalidScaleFactor {
9325 field: "scale_factor",
9326 numerator: 0,
9327 denominator: 1,
9328 }
9329 );
9330
9331 let err = PaneCoordinateNormalizer::new(
9332 PanePointerPosition::new(0, 0),
9333 PanePointerPosition::new(0, 0),
9334 0,
9335 10,
9336 PaneScaleFactor::ONE,
9337 PaneScaleFactor::ONE,
9338 PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9339 )
9340 .expect_err("zero width must fail");
9341 assert_eq!(
9342 err,
9343 PaneCoordinateNormalizationError::InvalidCellSize {
9344 width: 0,
9345 height: 10,
9346 }
9347 );
9348 }
9349
9350 #[test]
9351 fn coordinate_normalizer_repeated_device_updates_do_not_drift() {
9352 let normalizer = PaneCoordinateNormalizer::new(
9353 PanePointerPosition::new(0, 0),
9354 PanePointerPosition::new(0, 0),
9355 7,
9356 11,
9357 PaneScaleFactor::new(3, 2).expect("valid dpr"),
9358 PaneScaleFactor::new(5, 4).expect("valid zoom"),
9359 PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9360 )
9361 .expect("normalizer should be valid");
9362
9363 let mut prev = i32::MIN;
9364 for x in 150..190 {
9365 let first = normalizer
9366 .normalize(PaneInputCoordinate::DevicePixels {
9367 position: PanePointerPosition::new(x, 0),
9368 })
9369 .expect("first normalization should succeed");
9370 let second = normalizer
9371 .normalize(PaneInputCoordinate::DevicePixels {
9372 position: PanePointerPosition::new(x, 0),
9373 })
9374 .expect("second normalization should succeed");
9375
9376 assert_eq!(
9377 first, second,
9378 "normalization should be stable for same input"
9379 );
9380 assert!(
9381 first.global_cell.x >= prev,
9382 "cell coordinate should be monotonic"
9383 );
9384 if prev != i32::MIN {
9385 assert!(
9386 first.global_cell.x - prev <= 1,
9387 "cell coordinate should not jump by more than one per pixel step"
9388 );
9389 }
9390 prev = first.global_cell.x;
9391 }
9392 }
9393
9394 #[test]
9395 fn snap_tuning_is_deterministic_with_tie_breaks_and_hysteresis() {
9396 let tuning = PaneSnapTuning::default();
9397
9398 let tie = tuning.decide(3_250, None);
9399 assert_eq!(tie.nearest_ratio_bps, 3_000);
9400 assert_eq!(tie.snapped_ratio_bps, None);
9401 assert_eq!(tie.reason, PaneSnapReason::UnsnapOutsideWindow);
9402
9403 let snap = tuning.decide(3_499, None);
9404 assert_eq!(snap.nearest_ratio_bps, 3_500);
9405 assert_eq!(snap.snapped_ratio_bps, Some(3_500));
9406 assert_eq!(snap.reason, PaneSnapReason::SnappedNearest);
9407
9408 let retain = tuning.decide(3_390, Some(3_500));
9409 assert_eq!(retain.snapped_ratio_bps, Some(3_500));
9410 assert_eq!(retain.reason, PaneSnapReason::RetainedPrevious);
9411
9412 assert_eq!(
9413 PaneSnapTuning::new(0, 125).expect_err("step=0 must fail"),
9414 PaneInteractionPolicyError::InvalidSnapTuning {
9415 step_bps: 0,
9416 hysteresis_bps: 125
9417 }
9418 );
9419 }
9420
9421 #[test]
9422 fn precision_policy_applies_axis_lock_and_mode_scaling() {
9423 let fine = PanePrecisionPolicy::from_modifiers(
9424 PaneModifierSnapshot {
9425 shift: true,
9426 alt: true,
9427 ctrl: false,
9428 meta: false,
9429 },
9430 SplitAxis::Horizontal,
9431 );
9432 assert_eq!(fine.mode, PanePrecisionMode::Fine);
9433 assert_eq!(fine.axis_lock, Some(SplitAxis::Horizontal));
9434 assert_eq!(fine.apply_delta(5, 3).expect("fine delta"), (2, 0));
9435
9436 let coarse = PanePrecisionPolicy::from_modifiers(
9437 PaneModifierSnapshot {
9438 shift: false,
9439 alt: false,
9440 ctrl: true,
9441 meta: false,
9442 },
9443 SplitAxis::Vertical,
9444 );
9445 assert_eq!(coarse.mode, PanePrecisionMode::Coarse);
9446 assert_eq!(coarse.axis_lock, None);
9447 assert_eq!(coarse.apply_delta(2, -3).expect("coarse delta"), (4, -6));
9448 }
9449
9450 #[test]
9451 fn drag_behavior_tuning_validates_and_threshold_helpers_are_stable() {
9452 let tuning = PaneDragBehaviorTuning::new(3, 2, PaneSnapTuning::default())
9453 .expect("valid tuning should construct");
9454 assert!(tuning.should_start_drag(
9455 PanePointerPosition::new(0, 0),
9456 PanePointerPosition::new(3, 0)
9457 ));
9458 assert!(!tuning.should_start_drag(
9459 PanePointerPosition::new(0, 0),
9460 PanePointerPosition::new(2, 0)
9461 ));
9462 assert!(tuning.should_emit_drag_update(
9463 PanePointerPosition::new(10, 10),
9464 PanePointerPosition::new(12, 10)
9465 ));
9466 assert!(!tuning.should_emit_drag_update(
9467 PanePointerPosition::new(10, 10),
9468 PanePointerPosition::new(11, 10)
9469 ));
9470
9471 assert_eq!(
9472 PaneDragBehaviorTuning::new(0, 2, PaneSnapTuning::default())
9473 .expect_err("activation threshold=0 must fail"),
9474 PaneInteractionPolicyError::InvalidThreshold {
9475 field: "activation_threshold",
9476 value: 0
9477 }
9478 );
9479 assert_eq!(
9480 PaneDragBehaviorTuning::new(2, 0, PaneSnapTuning::default())
9481 .expect_err("hysteresis=0 must fail"),
9482 PaneInteractionPolicyError::InvalidThreshold {
9483 field: "update_hysteresis",
9484 value: 0
9485 }
9486 );
9487 }
9488
9489 fn pointer_down_event(
9490 sequence: u64,
9491 target: PaneResizeTarget,
9492 pointer_id: u32,
9493 x: i32,
9494 y: i32,
9495 ) -> PaneSemanticInputEvent {
9496 PaneSemanticInputEvent::new(
9497 sequence,
9498 PaneSemanticInputEventKind::PointerDown {
9499 target,
9500 pointer_id,
9501 button: PanePointerButton::Primary,
9502 position: PanePointerPosition::new(x, y),
9503 },
9504 )
9505 }
9506
9507 fn pointer_move_event(
9508 sequence: u64,
9509 target: PaneResizeTarget,
9510 pointer_id: u32,
9511 x: i32,
9512 y: i32,
9513 ) -> PaneSemanticInputEvent {
9514 PaneSemanticInputEvent::new(
9515 sequence,
9516 PaneSemanticInputEventKind::PointerMove {
9517 target,
9518 pointer_id,
9519 position: PanePointerPosition::new(x, y),
9520 delta_x: 0,
9521 delta_y: 0,
9522 },
9523 )
9524 }
9525
9526 fn pointer_up_event(
9527 sequence: u64,
9528 target: PaneResizeTarget,
9529 pointer_id: u32,
9530 x: i32,
9531 y: i32,
9532 ) -> PaneSemanticInputEvent {
9533 PaneSemanticInputEvent::new(
9534 sequence,
9535 PaneSemanticInputEventKind::PointerUp {
9536 target,
9537 pointer_id,
9538 button: PanePointerButton::Primary,
9539 position: PanePointerPosition::new(x, y),
9540 },
9541 )
9542 }
9543
9544 #[test]
9545 fn drag_resize_machine_full_lifecycle_commit() {
9546 let mut machine = PaneDragResizeMachine::default();
9547 let target = default_target();
9548
9549 let down = machine
9550 .apply_event(&pointer_down_event(1, target, 10, 10, 4))
9551 .expect("down should arm");
9552 assert_eq!(down.transition_id, 1);
9553 assert_eq!(down.sequence, 1);
9554 assert_eq!(machine.state(), down.to);
9555 assert!(matches!(
9556 down.effect,
9557 PaneDragResizeEffect::Armed {
9558 target: t,
9559 pointer_id: 10,
9560 origin: PanePointerPosition { x: 10, y: 4 }
9561 } if t == target
9562 ));
9563
9564 let below_threshold = machine
9565 .apply_event(&pointer_move_event(2, target, 10, 11, 4))
9566 .expect("small move should not start drag");
9567 assert_eq!(
9568 below_threshold.effect,
9569 PaneDragResizeEffect::Noop {
9570 reason: PaneDragResizeNoopReason::ThresholdNotReached
9571 }
9572 );
9573 assert!(matches!(machine.state(), PaneDragResizeState::Armed { .. }));
9574
9575 let drag_start = machine
9576 .apply_event(&pointer_move_event(3, target, 10, 13, 4))
9577 .expect("large move should start drag");
9578 assert!(matches!(
9579 drag_start.effect,
9580 PaneDragResizeEffect::DragStarted {
9581 target: t,
9582 pointer_id: 10,
9583 total_delta_x: 3,
9584 total_delta_y: 0,
9585 ..
9586 } if t == target
9587 ));
9588 assert!(matches!(
9589 machine.state(),
9590 PaneDragResizeState::Dragging { .. }
9591 ));
9592
9593 let drag_update = machine
9594 .apply_event(&pointer_move_event(4, target, 10, 15, 6))
9595 .expect("drag move should update");
9596 assert!(matches!(
9597 drag_update.effect,
9598 PaneDragResizeEffect::DragUpdated {
9599 target: t,
9600 pointer_id: 10,
9601 delta_x: 2,
9602 delta_y: 2,
9603 total_delta_x: 5,
9604 total_delta_y: 2,
9605 ..
9606 } if t == target
9607 ));
9608
9609 let commit = machine
9610 .apply_event(&pointer_up_event(5, target, 10, 16, 6))
9611 .expect("up should commit drag");
9612 assert!(matches!(
9613 commit.effect,
9614 PaneDragResizeEffect::Committed {
9615 target: t,
9616 pointer_id: 10,
9617 total_delta_x: 6,
9618 total_delta_y: 2,
9619 ..
9620 } if t == target
9621 ));
9622 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9623 }
9624
9625 #[test]
9626 fn drag_resize_machine_cancel_and_blur_paths_are_reason_coded() {
9627 let target = default_target();
9628
9629 let mut cancel_machine = PaneDragResizeMachine::default();
9630 cancel_machine
9631 .apply_event(&pointer_down_event(1, target, 1, 2, 2))
9632 .expect("down should arm");
9633 let cancel = cancel_machine
9634 .apply_event(&PaneSemanticInputEvent::new(
9635 2,
9636 PaneSemanticInputEventKind::Cancel {
9637 target: Some(target),
9638 reason: PaneCancelReason::FocusLost,
9639 },
9640 ))
9641 .expect("cancel should reset to idle");
9642 assert_eq!(cancel_machine.state(), PaneDragResizeState::Idle);
9643 assert_eq!(
9644 cancel.effect,
9645 PaneDragResizeEffect::Canceled {
9646 target: Some(target),
9647 pointer_id: Some(1),
9648 reason: PaneCancelReason::FocusLost
9649 }
9650 );
9651
9652 let mut blur_machine = PaneDragResizeMachine::default();
9653 blur_machine
9654 .apply_event(&pointer_down_event(3, target, 2, 5, 5))
9655 .expect("down should arm");
9656 blur_machine
9657 .apply_event(&pointer_move_event(4, target, 2, 8, 5))
9658 .expect("move should start dragging");
9659 let blur = blur_machine
9660 .apply_event(&PaneSemanticInputEvent::new(
9661 5,
9662 PaneSemanticInputEventKind::Blur {
9663 target: Some(target),
9664 },
9665 ))
9666 .expect("blur should cancel active drag");
9667 assert_eq!(blur_machine.state(), PaneDragResizeState::Idle);
9668 assert_eq!(
9669 blur.effect,
9670 PaneDragResizeEffect::Canceled {
9671 target: Some(target),
9672 pointer_id: Some(2),
9673 reason: PaneCancelReason::Blur
9674 }
9675 );
9676 }
9677
9678 #[test]
9679 fn drag_resize_machine_duplicate_end_and_pointer_mismatch_are_safe_noops() {
9680 let mut machine = PaneDragResizeMachine::default();
9681 let target = default_target();
9682
9683 machine
9684 .apply_event(&pointer_down_event(1, target, 9, 0, 0))
9685 .expect("down should arm");
9686
9687 let mismatch = machine
9688 .apply_event(&pointer_move_event(2, target, 99, 3, 0))
9689 .expect("mismatch should be ignored");
9690 assert_eq!(
9691 mismatch.effect,
9692 PaneDragResizeEffect::Noop {
9693 reason: PaneDragResizeNoopReason::PointerMismatch
9694 }
9695 );
9696 assert!(matches!(machine.state(), PaneDragResizeState::Armed { .. }));
9697
9698 machine
9699 .apply_event(&pointer_move_event(3, target, 9, 3, 0))
9700 .expect("drag should start");
9701 machine
9702 .apply_event(&pointer_up_event(4, target, 9, 3, 0))
9703 .expect("up should commit");
9704 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9705
9706 let duplicate_end = machine
9707 .apply_event(&pointer_up_event(5, target, 9, 3, 0))
9708 .expect("duplicate end should noop");
9709 assert_eq!(
9710 duplicate_end.effect,
9711 PaneDragResizeEffect::Noop {
9712 reason: PaneDragResizeNoopReason::IdleWithoutActiveDrag
9713 }
9714 );
9715 }
9716
9717 #[test]
9718 fn drag_resize_machine_discrete_inputs_in_idle_and_validation_errors() {
9719 let mut machine = PaneDragResizeMachine::default();
9720 let target = default_target();
9721
9722 let keyboard = machine
9723 .apply_event(&PaneSemanticInputEvent::new(
9724 1,
9725 PaneSemanticInputEventKind::KeyboardResize {
9726 target,
9727 direction: PaneResizeDirection::Increase,
9728 units: 2,
9729 },
9730 ))
9731 .expect("keyboard resize should apply in idle");
9732 assert_eq!(
9733 keyboard.effect,
9734 PaneDragResizeEffect::KeyboardApplied {
9735 target,
9736 direction: PaneResizeDirection::Increase,
9737 units: 2
9738 }
9739 );
9740 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9741
9742 let wheel = machine
9743 .apply_event(&PaneSemanticInputEvent::new(
9744 2,
9745 PaneSemanticInputEventKind::WheelNudge { target, lines: -1 },
9746 ))
9747 .expect("wheel nudge should apply in idle");
9748 assert_eq!(
9749 wheel.effect,
9750 PaneDragResizeEffect::WheelApplied { target, lines: -1 }
9751 );
9752
9753 let invalid_pointer = PaneSemanticInputEvent::new(
9754 3,
9755 PaneSemanticInputEventKind::PointerDown {
9756 target,
9757 pointer_id: 0,
9758 button: PanePointerButton::Primary,
9759 position: PanePointerPosition::new(0, 0),
9760 },
9761 );
9762 let err = machine
9763 .apply_event(&invalid_pointer)
9764 .expect_err("invalid input should be rejected");
9765 assert_eq!(
9766 err,
9767 PaneDragResizeMachineError::InvalidEvent(PaneSemanticInputEventError::ZeroPointerId)
9768 );
9769
9770 assert_eq!(
9771 PaneDragResizeMachine::new(0).expect_err("zero threshold should fail"),
9772 PaneDragResizeMachineError::InvalidDragThreshold { threshold: 0 }
9773 );
9774 }
9775
9776 #[test]
9777 fn drag_resize_machine_hysteresis_suppresses_micro_jitter() {
9778 let target = default_target();
9779 let mut machine = PaneDragResizeMachine::new_with_hysteresis(2, 2)
9780 .expect("explicit machine tuning should construct");
9781 machine
9782 .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9783 .expect("down should arm");
9784 machine
9785 .apply_event(&pointer_move_event(2, target, 22, 2, 0))
9786 .expect("move should start dragging");
9787
9788 let jitter = machine
9789 .apply_event(&pointer_move_event(3, target, 22, 3, 0))
9790 .expect("small move should be ignored");
9791 assert_eq!(
9792 jitter.effect,
9793 PaneDragResizeEffect::Noop {
9794 reason: PaneDragResizeNoopReason::BelowHysteresis
9795 }
9796 );
9797
9798 let update = machine
9799 .apply_event(&pointer_move_event(4, target, 22, 4, 0))
9800 .expect("larger move should update drag");
9801 assert!(matches!(
9802 update.effect,
9803 PaneDragResizeEffect::DragUpdated { .. }
9804 ));
9805 assert_eq!(
9806 PaneDragResizeMachine::new_with_hysteresis(2, 0)
9807 .expect_err("zero hysteresis must fail"),
9808 PaneDragResizeMachineError::InvalidUpdateHysteresis { hysteresis: 0 }
9809 );
9810 }
9811
9812 #[test]
9817 fn force_cancel_idle_is_noop() {
9818 let mut machine = PaneDragResizeMachine::default();
9819 assert!(!machine.is_active());
9820 assert!(machine.force_cancel().is_none());
9821 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9822 }
9823
9824 #[test]
9825 fn force_cancel_from_armed_resets_to_idle() {
9826 let target = default_target();
9827 let mut machine = PaneDragResizeMachine::default();
9828 machine
9829 .apply_event(&pointer_down_event(1, target, 22, 5, 5))
9830 .expect("down should arm");
9831 assert!(machine.is_active());
9832
9833 let transition = machine
9834 .force_cancel()
9835 .expect("armed machine should produce transition");
9836 assert_eq!(transition.to, PaneDragResizeState::Idle);
9837 assert!(matches!(
9838 transition.effect,
9839 PaneDragResizeEffect::Canceled {
9840 reason: PaneCancelReason::Programmatic,
9841 ..
9842 }
9843 ));
9844 assert!(!machine.is_active());
9845 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9846 }
9847
9848 #[test]
9849 fn force_cancel_from_dragging_resets_to_idle() {
9850 let target = default_target();
9851 let mut machine = PaneDragResizeMachine::default();
9852 machine
9853 .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9854 .expect("down");
9855 machine
9856 .apply_event(&pointer_move_event(2, target, 22, 5, 0))
9857 .expect("move past threshold to start drag");
9858 assert!(matches!(
9859 machine.state(),
9860 PaneDragResizeState::Dragging { .. }
9861 ));
9862 assert!(machine.is_active());
9863
9864 let transition = machine
9865 .force_cancel()
9866 .expect("dragging machine should produce transition");
9867 assert_eq!(transition.to, PaneDragResizeState::Idle);
9868 assert!(matches!(
9869 transition.effect,
9870 PaneDragResizeEffect::Canceled {
9871 target: Some(_),
9872 pointer_id: Some(22),
9873 reason: PaneCancelReason::Programmatic,
9874 }
9875 ));
9876 assert!(!machine.is_active());
9877 }
9878
9879 #[test]
9880 fn force_cancel_is_idempotent() {
9881 let target = default_target();
9882 let mut machine = PaneDragResizeMachine::default();
9883 machine
9884 .apply_event(&pointer_down_event(1, target, 22, 5, 5))
9885 .expect("down should arm");
9886
9887 let first = machine.force_cancel();
9888 assert!(first.is_some());
9889 let second = machine.force_cancel();
9890 assert!(second.is_none());
9891 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9892 }
9893
9894 #[test]
9895 fn force_cancel_preserves_transition_counter_monotonicity() {
9896 let target = default_target();
9897 let mut machine = PaneDragResizeMachine::default();
9898
9899 let t1 = machine
9900 .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9901 .expect("arm");
9902 let t2 = machine.force_cancel().expect("force cancel from armed");
9903 assert!(t2.transition_id > t1.transition_id);
9904
9905 let t3 = machine
9907 .apply_event(&pointer_down_event(2, target, 22, 10, 10))
9908 .expect("re-arm");
9909 let t4 = machine.force_cancel().expect("second force cancel");
9910 assert!(t3.transition_id > t2.transition_id);
9911 assert!(t4.transition_id > t3.transition_id);
9912 }
9913
9914 #[test]
9915 fn force_cancel_records_prior_state_in_from_field() {
9916 let target = default_target();
9917 let mut machine = PaneDragResizeMachine::default();
9918 machine
9919 .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9920 .expect("arm");
9921
9922 let armed_state = machine.state();
9923 let transition = machine.force_cancel().expect("force cancel");
9924 assert_eq!(transition.from, armed_state);
9925 }
9926
9927 #[test]
9928 fn machine_usable_after_force_cancel() {
9929 let target = default_target();
9930 let mut machine = PaneDragResizeMachine::default();
9931
9932 machine
9934 .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9935 .expect("arm");
9936 machine.force_cancel();
9937
9938 machine
9939 .apply_event(&pointer_down_event(2, target, 22, 10, 10))
9940 .expect("re-arm after force cancel");
9941 machine
9942 .apply_event(&pointer_move_event(3, target, 22, 15, 10))
9943 .expect("move to drag");
9944 let commit = machine
9945 .apply_event(&pointer_up_event(4, target, 22, 15, 10))
9946 .expect("commit");
9947 assert!(matches!(
9948 commit.effect,
9949 PaneDragResizeEffect::Committed { .. }
9950 ));
9951 assert_eq!(machine.state(), PaneDragResizeState::Idle);
9952 }
9953
9954 proptest! {
9955 #[test]
9956 fn ratio_is_always_reduced(numerator in 1u32..100_000, denominator in 1u32..100_000) {
9957 let ratio = PaneSplitRatio::new(numerator, denominator).expect("positive ratio must be valid");
9958 let gcd = gcd_u32(ratio.numerator(), ratio.denominator());
9959 prop_assert_eq!(gcd, 1);
9960 }
9961
9962 #[test]
9963 fn allocator_produces_monotonic_ids(
9964 start in 1u64..1_000_000,
9965 count in 1usize..64,
9966 ) {
9967 let mut allocator = PaneIdAllocator::with_next(PaneId::new(start).expect("start must be valid"));
9968 let mut prev = 0u64;
9969 for _ in 0..count {
9970 let current = allocator.allocate().expect("allocation must succeed").get();
9971 prop_assert!(current > prev);
9972 prev = current;
9973 }
9974 }
9975
9976 #[test]
9977 fn split_solver_preserves_available_space(
9978 numerator in 1u32..64,
9979 denominator in 1u32..64,
9980 first_min in 0u16..40,
9981 second_min in 0u16..40,
9982 available in 0u16..80,
9983 ) {
9984 let ratio = PaneSplitRatio::new(numerator, denominator).expect("ratio must be valid");
9985 prop_assume!(first_min.saturating_add(second_min) <= available);
9986
9987 let (first_size, second_size) = solve_split_sizes(
9988 id(1),
9989 SplitAxis::Horizontal,
9990 available,
9991 ratio,
9992 AxisBounds { min: first_min, max: None },
9993 AxisBounds { min: second_min, max: None },
9994 ).expect("feasible split should solve");
9995
9996 prop_assert_eq!(first_size.saturating_add(second_size), available);
9997 prop_assert!(first_size >= first_min);
9998 prop_assert!(second_size >= second_min);
9999 }
10000
10001 #[test]
10002 fn split_then_close_round_trip_preserves_validity(
10003 numerator in 1u32..32,
10004 denominator in 1u32..32,
10005 incoming_first in any::<bool>(),
10006 ) {
10007 let mut tree = PaneTree::singleton("root");
10008 let placement = if incoming_first {
10009 PanePlacement::IncomingFirst
10010 } else {
10011 PanePlacement::ExistingFirst
10012 };
10013 let ratio = PaneSplitRatio::new(numerator, denominator).expect("ratio must be valid");
10014
10015 tree.apply_operation(
10016 1,
10017 PaneOperation::SplitLeaf {
10018 target: id(1),
10019 axis: SplitAxis::Horizontal,
10020 ratio,
10021 placement,
10022 new_leaf: PaneLeaf::new("extra"),
10023 },
10024 ).expect("split should succeed");
10025
10026 let split_root_id = tree.root();
10027 let split_root = tree.node(split_root_id).expect("split root exists");
10028 let PaneNodeKind::Split(split) = &split_root.kind else {
10029 unreachable!("root should be split");
10030 };
10031 let extra_leaf_id = if split.first == id(1) {
10032 split.second
10033 } else {
10034 split.first
10035 };
10036
10037 tree.apply_operation(2, PaneOperation::CloseNode { target: extra_leaf_id })
10038 .expect("close should succeed");
10039
10040 prop_assert_eq!(tree.root(), id(1));
10041 prop_assert!(matches!(
10042 tree.node(id(1)).map(|node| &node.kind),
10043 Some(PaneNodeKind::Leaf(_))
10044 ));
10045 prop_assert!(tree.validate().is_ok());
10046 }
10047
10048 #[test]
10049 fn transaction_rollback_restores_initial_state_hash(
10050 numerator in 1u32..64,
10051 denominator in 1u32..64,
10052 incoming_first in any::<bool>(),
10053 ) {
10054 let base = PaneTree::singleton("root");
10055 let initial_hash = base.state_hash();
10056 let mut tx = base.begin_transaction(90);
10057 let placement = if incoming_first {
10058 PanePlacement::IncomingFirst
10059 } else {
10060 PanePlacement::ExistingFirst
10061 };
10062
10063 tx.apply_operation(
10064 1,
10065 PaneOperation::SplitLeaf {
10066 target: id(1),
10067 axis: SplitAxis::Horizontal,
10068 ratio: PaneSplitRatio::new(numerator, denominator).expect("valid ratio"),
10069 placement,
10070 new_leaf: PaneLeaf::new("new"),
10071 },
10072 ).expect("split should succeed");
10073
10074 let rolled_back = tx.rollback();
10075 prop_assert_eq!(rolled_back.tree.state_hash(), initial_hash);
10076 prop_assert_eq!(rolled_back.tree.root(), id(1));
10077 prop_assert!(rolled_back.tree.validate().is_ok());
10078 }
10079
10080 #[test]
10081 fn repair_safe_is_deterministic_under_recoverable_damage(
10082 numerator in 1u32..32,
10083 denominator in 1u32..32,
10084 add_orphan in any::<bool>(),
10085 mismatch_parent in any::<bool>(),
10086 ) {
10087 let mut snapshot = make_valid_snapshot();
10088 for node in &mut snapshot.nodes {
10089 if node.id == id(1) {
10090 let PaneNodeKind::Split(split) = &mut node.kind else {
10091 unreachable!("root should be split");
10092 };
10093 split.ratio = PaneSplitRatio {
10094 numerator: numerator.saturating_mul(2),
10095 denominator: denominator.saturating_mul(2),
10096 };
10097 }
10098 if mismatch_parent && node.id == id(2) {
10099 node.parent = Some(id(3));
10100 }
10101 }
10102 if add_orphan {
10103 snapshot
10104 .nodes
10105 .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
10106 snapshot.next_id = id(11);
10107 }
10108
10109 let first = snapshot.clone().repair_safe().expect("first repair should succeed");
10110 let second = snapshot.repair_safe().expect("second repair should succeed");
10111
10112 prop_assert_eq!(first.tree.state_hash(), second.tree.state_hash());
10113 prop_assert_eq!(first.actions, second.actions);
10114 prop_assert_eq!(first.report_after, second.report_after);
10115 }
10116 }
10117
10118 #[test]
10119 fn set_split_ratio_operation_updates_existing_split() {
10120 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10121 tree.apply_operation(
10122 900,
10123 PaneOperation::SetSplitRatio {
10124 split: id(1),
10125 ratio: PaneSplitRatio::new(5, 3).expect("valid ratio"),
10126 },
10127 )
10128 .expect("set split ratio should succeed");
10129
10130 let root = tree.node(id(1)).expect("root exists");
10131 let PaneNodeKind::Split(split) = &root.kind else {
10132 unreachable!("root should be split");
10133 };
10134 assert_eq!(split.ratio.numerator(), 5);
10135 assert_eq!(split.ratio.denominator(), 3);
10136 }
10137
10138 #[test]
10139 fn layout_classifies_any_edge_grips_and_edge_resize_plans_apply() {
10140 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10141 let layout = tree
10142 .solve_layout(Rect::new(0, 0, 120, 48))
10143 .expect("layout should solve");
10144 let left_rect = layout.rect(id(2)).expect("leaf 2 rect");
10145 let pointer = PanePointerPosition::new(
10146 i32::from(
10147 left_rect
10148 .x
10149 .saturating_add(left_rect.width.saturating_sub(1)),
10150 ),
10151 i32::from(left_rect.y.saturating_add(left_rect.height / 2)),
10152 );
10153 let grip = layout
10154 .classify_resize_grip(id(2), pointer, PANE_EDGE_GRIP_INSET_CELLS)
10155 .expect("grip should classify");
10156 assert!(matches!(
10157 grip,
10158 PaneResizeGrip::Right | PaneResizeGrip::TopRight | PaneResizeGrip::BottomRight
10159 ));
10160
10161 let plan = tree
10162 .plan_edge_resize(
10163 id(2),
10164 &layout,
10165 grip,
10166 pointer,
10167 PanePressureSnapProfile {
10168 strength_bps: 8_000,
10169 hysteresis_bps: 250,
10170 },
10171 )
10172 .expect("edge resize plan should build");
10173 assert!(!plan.operations.is_empty());
10174 tree.apply_edge_resize_plan(901, &plan)
10175 .expect("edge resize plan should apply");
10176 assert!(tree.validate().is_ok());
10177 }
10178
10179 #[test]
10180 fn pane_layout_visual_rect_applies_default_margin_and_padding() {
10181 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10182 let layout = tree
10183 .solve_layout(Rect::new(0, 0, 120, 48))
10184 .expect("layout should solve");
10185 let raw = layout.rect(id(2)).expect("leaf rect exists");
10186 let visual = layout.visual_rect(id(2)).expect("visual rect exists");
10187 assert!(visual.width <= raw.width);
10188 assert!(visual.height <= raw.height);
10189 assert!(visual.width > 0);
10190 assert!(visual.height > 0);
10191 }
10192
10193 #[test]
10194 fn magnetic_docking_preview_and_reflow_plan_are_generated() {
10195 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10196 let layout = tree
10197 .solve_layout(Rect::new(0, 0, 100, 40))
10198 .expect("layout should solve");
10199 let right_rect = layout.rect(id(3)).expect("leaf 3 rect");
10200 let pointer = PanePointerPosition::new(
10201 i32::from(right_rect.x),
10202 i32::from(right_rect.y.saturating_add(right_rect.height / 2)),
10203 );
10204 let preview = tree
10205 .choose_dock_preview(&layout, pointer, PANE_MAGNETIC_FIELD_CELLS)
10206 .expect("magnetic preview should exist");
10207 assert!(preview.score > 0.0);
10208
10209 let plan = tree
10210 .plan_reflow_move_with_preview(
10211 id(2),
10212 &layout,
10213 pointer,
10214 PaneMotionVector::from_delta(24, 0, 48, 0),
10215 Some(PaneInertialThrow::from_motion(
10216 PaneMotionVector::from_delta(24, 0, 48, 0),
10217 )),
10218 PANE_MAGNETIC_FIELD_CELLS,
10219 )
10220 .expect("reflow plan should build");
10221 assert!(!plan.operations.is_empty());
10222 }
10223
10224 #[test]
10225 fn group_move_and_group_resize_plan_generation() {
10226 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10227 let layout = tree
10228 .solve_layout(Rect::new(0, 0, 100, 40))
10229 .expect("layout should solve");
10230 let mut selection = PaneSelectionState::default();
10231 selection.shift_toggle(id(2));
10232 assert_eq!(selection.selected.len(), 1);
10233
10234 let move_plan = tree
10235 .plan_group_move(
10236 &selection,
10237 &layout,
10238 PanePointerPosition::new(80, 4),
10239 PaneMotionVector::from_delta(30, 2, 64, 1),
10240 None,
10241 PANE_MAGNETIC_FIELD_CELLS,
10242 )
10243 .expect("group move plan should build");
10244 assert!(!move_plan.operations.is_empty());
10245
10246 let resize_plan = tree
10247 .plan_group_resize(
10248 &selection,
10249 &layout,
10250 PaneResizeGrip::Right,
10251 PanePointerPosition::new(70, 20),
10252 PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(40, 1, 32, 0)),
10253 )
10254 .expect("group resize plan should build");
10255 assert!(!resize_plan.operations.is_empty());
10256 }
10257
10258 #[test]
10259 fn classify_resize_grip_handles_small_panes() {
10260 let rect = Rect::new(10, 10, 1, 1);
10262 let pointer = PanePointerPosition::new(10, 10);
10263 let grip = classify_resize_grip(rect, pointer, 1.5).expect("should classify");
10264 assert_eq!(grip, PaneResizeGrip::BottomRight);
10266
10267 let rect2 = Rect::new(10, 10, 2, 1);
10269 let ptr_left = PanePointerPosition::new(10, 10);
10271 let grip_left = classify_resize_grip(rect2, ptr_left, 1.5).expect("left pixel");
10272 assert_eq!(grip_left, PaneResizeGrip::BottomLeft);
10273
10274 let ptr_right = PanePointerPosition::new(11, 10);
10276 let grip_right = classify_resize_grip(rect2, ptr_right, 1.5).expect("right pixel");
10277 assert_eq!(grip_right, PaneResizeGrip::BottomRight);
10278 }
10279
10280 #[test]
10281 fn pressure_sensitive_snap_prefers_fast_straight_drags() {
10282 let slow = PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(4, 1, 300, 3));
10283 let fast = PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(40, 2, 48, 0));
10284 assert!(fast.strength_bps > slow.strength_bps);
10285 assert!(fast.hysteresis_bps >= slow.hysteresis_bps);
10286 }
10287
10288 #[test]
10289 fn pressure_sensitive_snap_penalizes_direction_noise() {
10290 let stable =
10291 PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(32, 2, 60, 0));
10292 let noisy =
10293 PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(32, 2, 60, 7));
10294 assert!(stable.strength_bps > noisy.strength_bps);
10295 }
10296
10297 #[test]
10298 fn dock_zone_motion_intent_prefers_directionally_aligned_zones() {
10299 let rightward = PaneMotionVector::from_delta(36, 2, 50, 0);
10300 let left_bias = dock_zone_motion_intent(PaneDockZone::Left, rightward);
10301 let right_bias = dock_zone_motion_intent(PaneDockZone::Right, rightward);
10302 assert!(right_bias > left_bias);
10303
10304 let downward = PaneMotionVector::from_delta(2, 32, 52, 0);
10305 let top_bias = dock_zone_motion_intent(PaneDockZone::Top, downward);
10306 let bottom_bias = dock_zone_motion_intent(PaneDockZone::Bottom, downward);
10307 assert!(bottom_bias > top_bias);
10308 }
10309
10310 #[test]
10311 fn dock_zone_motion_intent_noise_reduces_alignment_confidence() {
10312 let stable = dock_zone_motion_intent(
10313 PaneDockZone::Right,
10314 PaneMotionVector::from_delta(40, 1, 45, 0),
10315 );
10316 let noisy = dock_zone_motion_intent(
10317 PaneDockZone::Right,
10318 PaneMotionVector::from_delta(40, 1, 45, 8),
10319 );
10320 assert!(stable > noisy);
10321 }
10322
10323 #[test]
10324 fn elastic_ratio_bps_resists_extreme_edges_more_at_low_confidence() {
10325 let near_edge = 350;
10326 let low_confidence = elastic_ratio_bps(
10327 near_edge,
10328 PanePressureSnapProfile {
10329 strength_bps: 1_800,
10330 hysteresis_bps: 120,
10331 },
10332 );
10333 let high_confidence = elastic_ratio_bps(
10334 near_edge,
10335 PanePressureSnapProfile {
10336 strength_bps: 8_600,
10337 hysteresis_bps: 520,
10338 },
10339 );
10340 assert!(low_confidence > near_edge);
10341 assert!(high_confidence <= low_confidence);
10342 }
10343
10344 #[test]
10345 fn ranked_dock_previews_with_motion_returns_descending_scores() {
10346 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10347 let layout = tree
10348 .solve_layout(Rect::new(0, 0, 100, 40))
10349 .expect("layout should solve");
10350 let right_rect = layout.rect(id(3)).expect("leaf 3 rect");
10351 let pointer = PanePointerPosition::new(
10352 i32::from(right_rect.x),
10353 i32::from(right_rect.y.saturating_add(right_rect.height / 2)),
10354 );
10355 let ranked = tree.ranked_dock_previews_with_motion(
10356 &layout,
10357 pointer,
10358 PaneMotionVector::from_delta(28, 2, 48, 0),
10359 PANE_MAGNETIC_FIELD_CELLS,
10360 Some(id(2)),
10361 3,
10362 );
10363 assert!(!ranked.is_empty());
10364 for pair in ranked.windows(2) {
10365 assert!(pair[0].score >= pair[1].score);
10366 }
10367 }
10368
10369 #[test]
10370 fn inertial_throw_projects_farther_for_faster_motion() {
10371 let start = PanePointerPosition::new(40, 12);
10372 let slow = PaneInertialThrow::from_motion(PaneMotionVector::from_delta(6, 0, 220, 1))
10373 .projected_pointer(start);
10374 let fast = PaneInertialThrow::from_motion(PaneMotionVector::from_delta(42, 0, 40, 0))
10375 .projected_pointer(start);
10376 assert!(fast.x > slow.x);
10377 }
10378
10379 #[test]
10380 fn affordance_hover_emphasis_ramps_monotonically_to_full() {
10381 let motion = PaneAffordanceMotion::default();
10382 let mut prev = 0u16;
10383 for frame in 0..=motion.fade_in_frames {
10384 let bps = motion.hover_emphasis_bps(frame);
10385 assert!(bps >= prev, "ramp must be monotonic non-decreasing");
10386 assert!(bps <= PANE_AFFORDANCE_EMPHASIS_FULL_BPS);
10387 prev = bps;
10388 }
10389 assert_eq!(
10391 motion.hover_emphasis_bps(motion.fade_in_frames),
10392 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10393 );
10394 assert_eq!(
10395 motion.hover_emphasis_bps(motion.fade_in_frames + 50),
10396 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10397 );
10398 let half = motion.fade_in_frames / 2;
10400 let first_half_gain = motion.hover_emphasis_bps(half);
10401 let second_half_gain = PANE_AFFORDANCE_EMPHASIS_FULL_BPS - first_half_gain;
10402 assert!(
10403 first_half_gain >= second_half_gain,
10404 "ease-out should front-load the ramp ({first_half_gain} vs {second_half_gain})"
10405 );
10406 }
10407
10408 #[test]
10409 fn affordance_reduced_motion_steps_instantly_without_losing_the_cue() {
10410 let reduced = PaneAffordanceMotion::reduced();
10411 assert!(reduced.reduced_motion);
10412 assert_eq!(
10415 reduced.hover_emphasis_bps(0),
10416 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10417 );
10418 for phase in [0u64, 1, 12, 24, 47, 1_000_000] {
10420 assert_eq!(
10421 reduced.active_pulse_bps(phase),
10422 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10423 );
10424 }
10425 let derived = PaneAffordanceMotion::default().with_reduced_motion(true);
10427 assert_eq!(derived.hover_emphasis_bps(0), reduced.hover_emphasis_bps(0));
10428 }
10429
10430 #[test]
10431 fn affordance_active_pulse_oscillates_within_bounds_and_is_periodic() {
10432 let motion = PaneAffordanceMotion::default();
10433 let period = u64::from(motion.pulse_period_frames);
10434 let mut min = u16::MAX;
10435 let mut max = 0u16;
10436 for phase in 0..period {
10437 let bps = motion.active_pulse_bps(phase);
10438 assert!(bps >= motion.pulse_floor_bps, "never below the floor");
10439 assert!(bps <= PANE_AFFORDANCE_EMPHASIS_FULL_BPS, "never above full");
10440 min = min.min(bps);
10441 max = max.max(bps);
10442 assert_eq!(bps, motion.active_pulse_bps(phase + period));
10444 assert_eq!(bps, motion.active_pulse_bps(phase + 5 * period));
10445 }
10446 assert_eq!(min, motion.pulse_floor_bps, "trough sits at the floor");
10447 assert_eq!(max, PANE_AFFORDANCE_EMPHASIS_FULL_BPS, "peak reaches full");
10448 assert_eq!(
10450 motion.active_pulse_bps(u64::from(motion.pulse_period_frames / 2)),
10451 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10452 );
10453 }
10454
10455 #[test]
10456 fn affordance_motion_is_deterministic_and_clock_free() {
10457 let motion = PaneAffordanceMotion::default();
10458 for frame in 0..200u64 {
10461 assert_eq!(
10462 motion.active_pulse_bps(frame),
10463 motion.active_pulse_bps(frame)
10464 );
10465 }
10466 for frame in 0..50u16 {
10467 assert_eq!(
10468 motion.hover_emphasis_bps(frame),
10469 motion.hover_emphasis_bps(frame)
10470 );
10471 }
10472 }
10473
10474 #[test]
10475 fn affordance_zero_timing_fields_degrade_to_full() {
10476 let instant = PaneAffordanceMotion {
10477 fade_in_frames: 0,
10478 pulse_period_frames: 0,
10479 ..PaneAffordanceMotion::default()
10480 };
10481 assert_eq!(
10482 instant.hover_emphasis_bps(0),
10483 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10484 );
10485 assert_eq!(
10486 instant.active_pulse_bps(7),
10487 PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10488 );
10489 }
10490
10491 #[test]
10492 fn intelligence_mode_compact_emits_ratio_normalization_ops() {
10493 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10494 let ops = tree
10495 .plan_intelligence_mode(PaneLayoutIntelligenceMode::Compact, id(2))
10496 .expect("compact mode should plan");
10497 assert!(
10498 ops.iter()
10499 .any(|op| matches!(op, PaneOperation::NormalizeRatios))
10500 );
10501 assert!(
10502 ops.iter()
10503 .any(|op| matches!(op, PaneOperation::SetSplitRatio { .. }))
10504 );
10505 }
10506
10507 #[test]
10508 fn interaction_timeline_supports_undo_redo_and_replay() {
10509 let mut tree = PaneTree::singleton("root");
10510 let mut timeline = PaneInteractionTimeline::default();
10511
10512 timeline
10513 .apply_and_record(
10514 &mut tree,
10515 1,
10516 1000,
10517 PaneOperation::SplitLeaf {
10518 target: id(1),
10519 axis: SplitAxis::Horizontal,
10520 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
10521 placement: PanePlacement::ExistingFirst,
10522 new_leaf: PaneLeaf::new("aux"),
10523 },
10524 )
10525 .expect("split should apply");
10526 let split_hash = tree.state_hash();
10527 assert_eq!(timeline.applied_len(), 1);
10528
10529 let undone = timeline.undo(&mut tree).expect("undo should succeed");
10530 assert!(undone);
10531 assert_eq!(tree.root(), id(1));
10532
10533 let redone = timeline.redo(&mut tree).expect("redo should succeed");
10534 assert!(redone);
10535 assert_eq!(tree.state_hash(), split_hash);
10536
10537 let replayed = timeline.replay().expect("replay should succeed");
10538 assert_eq!(replayed.state_hash(), tree.state_hash());
10539 }
10540
10541 #[test]
10542 fn interaction_timeline_replay_matches_recorded_ratio_updates() {
10543 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10544 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10545 let split_ids: Vec<_> = tree
10546 .nodes()
10547 .filter_map(|node| match node.kind {
10548 PaneNodeKind::Split(_) => Some(node.id),
10549 PaneNodeKind::Leaf(_) => None,
10550 })
10551 .collect();
10552 assert!(!split_ids.is_empty());
10553 let ratios = [
10554 PaneSplitRatio::new(3, 2).expect("valid ratio"),
10555 PaneSplitRatio::new(2, 3).expect("valid ratio"),
10556 PaneSplitRatio::new(5, 4).expect("valid ratio"),
10557 PaneSplitRatio::new(4, 5).expect("valid ratio"),
10558 ];
10559
10560 for idx in 0..16u64 {
10561 timeline
10562 .apply_and_record(
10563 &mut tree,
10564 idx,
10565 20_000 + idx,
10566 PaneOperation::SetSplitRatio {
10567 split: split_ids[idx as usize % split_ids.len()],
10568 ratio: ratios[idx as usize % ratios.len()],
10569 },
10570 )
10571 .expect("ratio update should apply");
10572 }
10573
10574 let replayed = timeline.replay().expect("replay should succeed");
10575 assert_eq!(replayed.state_hash(), tree.state_hash());
10576 assert_eq!(replayed.to_snapshot(), tree.to_snapshot());
10577 }
10578
10579 fn timeline_with_redo_entry(
10580 checkpoint_interval: usize,
10581 ) -> (PaneTree, PaneInteractionTimeline, Vec<PaneTreeSnapshot>) {
10582 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10583 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10584 timeline.checkpoint_interval = checkpoint_interval;
10585 let mut states = vec![tree.to_snapshot()];
10586 for (operation_id, numerator) in [(1, 4), (2, 5), (3, 6), (4, 7)] {
10587 timeline
10588 .apply_and_record(
10589 &mut tree,
10590 operation_id,
10591 operation_id,
10592 PaneOperation::SetSplitRatio {
10593 split: id(1),
10594 ratio: PaneSplitRatio::new(numerator, 10).expect("valid ratio"),
10595 },
10596 )
10597 .expect("valid recorded edit");
10598 states.push(tree.to_snapshot());
10599 }
10600 assert!(timeline.undo(&mut tree).expect("retain a redo entry"));
10601 assert_eq!(timeline.applied_len(), 3);
10602 assert_eq!(tree.to_snapshot(), states[3]);
10603 (tree, timeline, states)
10604 }
10605
10606 fn assert_timeline_navigation_failure_is_atomic(redo: bool, invalid_operation: bool) {
10607 let (mut tree, mut timeline, states) = timeline_with_redo_entry(0);
10608 let valid_history = timeline.clone();
10609 let missing = id(u64::MAX);
10610 let expected_error = if invalid_operation {
10611 timeline.entries[1].operation = PaneOperation::CloseNode { target: missing };
10614 let before_hash = timeline.entries[0].after_hash;
10615 PaneInteractionTimelineError::ApplyFailed {
10616 source: PaneOperationError {
10617 operation_id: 2,
10618 kind: PaneOperationKind::CloseNode,
10619 touched_nodes: smallvec![missing],
10620 before_hash,
10621 after_hash: before_hash,
10622 reason: PaneOperationFailure::MissingNode { node_id: missing },
10623 },
10624 }
10625 } else {
10626 timeline.baseline.as_mut().expect("baseline").root = missing;
10627 PaneInteractionTimelineError::BaselineInvalid {
10628 source: PaneModelError::MissingRoot { root: missing },
10629 }
10630 };
10631 let before_tree = tree.to_snapshot();
10632 let before_history = timeline.clone();
10633 let before_redo = timeline.entries[timeline.cursor..].to_vec();
10634 let error = if redo {
10635 timeline.redo(&mut tree)
10636 } else {
10637 timeline.undo(&mut tree)
10638 }
10639 .expect_err("invalid replay input must be rejected");
10640 assert_eq!(error, expected_error, "original replay error must survive");
10641 assert_eq!(
10642 tree.to_snapshot(),
10643 before_tree,
10644 "failed navigation changed tree"
10645 );
10646 assert_eq!(timeline.cursor, 3, "failed navigation changed cursor");
10647 assert_eq!(timeline.entries[timeline.cursor..], before_redo);
10648 assert_eq!(
10649 timeline, before_history,
10650 "failed navigation changed history"
10651 );
10652
10653 if invalid_operation {
10656 timeline.entries[1] = valid_history.entries[1].clone();
10657 } else {
10658 timeline.baseline = valid_history.baseline;
10659 }
10660 let target = if redo { 4 } else { 2 };
10661 assert!(if redo {
10662 timeline.redo(&mut tree).expect("redo after input repair")
10663 } else {
10664 timeline.undo(&mut tree).expect("undo after input repair")
10665 });
10666 assert_eq!(timeline.cursor, target);
10667 assert_eq!(tree.to_snapshot(), states[target]);
10668 assert!(if redo {
10669 timeline.undo(&mut tree).expect("undo restored navigation")
10670 } else {
10671 timeline.redo(&mut tree).expect("redo restored navigation")
10672 });
10673 assert_eq!(timeline.cursor, 3);
10674 assert_eq!(tree.to_snapshot(), before_tree);
10675 assert_eq!(timeline.entries[timeline.cursor..], before_redo);
10676 }
10677
10678 #[test]
10679 fn interaction_timeline_undo_invalid_baseline_is_atomic() {
10680 assert_timeline_navigation_failure_is_atomic(false, false);
10681 }
10682
10683 #[test]
10684 fn interaction_timeline_redo_invalid_baseline_is_atomic() {
10685 assert_timeline_navigation_failure_is_atomic(true, false);
10686 }
10687
10688 #[test]
10689 fn interaction_timeline_undo_invalid_operation_is_atomic() {
10690 assert_timeline_navigation_failure_is_atomic(false, true);
10691 }
10692
10693 #[test]
10694 fn interaction_timeline_redo_invalid_operation_is_atomic() {
10695 assert_timeline_navigation_failure_is_atomic(true, true);
10696 }
10697
10698 #[test]
10699 fn interaction_timeline_navigation_boundaries_preserve_state() {
10700 let mut empty_tree = PaneTree::singleton("empty history");
10701 let mut empty_timeline = PaneInteractionTimeline::default();
10702 let empty_snapshot = empty_tree.to_snapshot();
10703 assert_eq!(empty_timeline.undo(&mut empty_tree), Ok(false));
10704 assert_eq!(empty_timeline.redo(&mut empty_tree), Ok(false));
10705 assert_eq!(empty_tree.to_snapshot(), empty_snapshot);
10706 assert_eq!(empty_timeline, PaneInteractionTimeline::default());
10707
10708 for checkpoint_interval in [0, 1] {
10709 let (mut tree, mut timeline, states) = timeline_with_redo_entry(checkpoint_interval);
10710 for cursor in (0..3).rev() {
10711 assert_eq!(timeline.undo(&mut tree), Ok(true));
10712 assert_eq!(timeline.applied_len(), cursor);
10713 assert_eq!(tree.to_snapshot(), states[cursor]);
10714 }
10715 let before_history = timeline.clone();
10716 assert_eq!(timeline.undo(&mut tree), Ok(false));
10717 assert_eq!(timeline, before_history);
10718 assert_eq!(tree.to_snapshot(), states[0]);
10719 for (cursor, state) in states.iter().enumerate().skip(1) {
10720 assert_eq!(timeline.redo(&mut tree), Ok(true));
10721 assert_eq!(timeline.applied_len(), cursor);
10722 assert_eq!(&tree.to_snapshot(), state);
10723 }
10724 let before_history = timeline.clone();
10725 assert_eq!(timeline.redo(&mut tree), Ok(false));
10726 assert_eq!(timeline, before_history);
10727 assert_eq!(tree.to_snapshot(), states[4]);
10728 }
10729 }
10730
10731 #[test]
10732 fn rejected_timeline_operation_preserves_redo_branch() {
10733 for coalesced in [false, true] {
10734 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10735 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10736 timeline.checkpoint_interval = 1;
10737 for (operation_id, numerator) in [(1, 4), (2, 5)] {
10738 timeline
10739 .apply_and_record(
10740 &mut tree,
10741 operation_id,
10742 operation_id,
10743 PaneOperation::SetSplitRatio {
10744 split: id(1),
10745 ratio: PaneSplitRatio::new(numerator, 2).expect("valid ratio"),
10746 },
10747 )
10748 .expect("valid edit");
10749 }
10750 let head = tree.to_snapshot();
10751 assert!(timeline.undo(&mut tree).expect("undo"));
10752 let before_tree = tree.to_snapshot();
10753 let before_history = timeline.clone();
10754 let invalid = PaneOperation::SetSplitRatio {
10755 split: id(u64::MAX),
10756 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
10757 };
10758 let result = if coalesced {
10759 timeline.apply_and_record_coalesced_resize_delta(&mut tree, 3, 3, invalid, 0)
10760 } else {
10761 timeline.apply_and_record(&mut tree, 3, 3, invalid)
10762 };
10763 assert!(result.is_err(), "missing split must be rejected");
10764 assert_eq!(tree.to_snapshot(), before_tree);
10765 assert_eq!(
10766 timeline, before_history,
10767 "rejection lost redo; coalesced={coalesced}"
10768 );
10769 assert!(timeline.redo(&mut tree).expect("redo survived rejection"));
10770 assert_eq!(tree.to_snapshot(), head);
10771 assert!(timeline.undo(&mut tree).expect("undo before valid branch"));
10772 let replacement = PaneOperation::SetSplitRatio {
10773 split: id(1),
10774 ratio: PaneSplitRatio::new(7, 2).expect("valid ratio"),
10775 };
10776 if coalesced {
10777 timeline.apply_and_record_coalesced_resize_delta(&mut tree, 4, 4, replacement, 2)
10778 } else {
10779 timeline.apply_and_record(&mut tree, 4, 4, replacement)
10780 }
10781 .expect("a valid edit replaces the redo branch");
10782 assert!(
10783 !timeline
10784 .redo(&mut tree)
10785 .expect("no stale redo after valid branch")
10786 );
10787 assert_eq!(timeline.entries.len(), 2);
10788 assert_eq!(timeline.entries.last().unwrap().operation_id, 4);
10789 assert_eq!(
10790 timeline
10791 .replay()
10792 .expect("valid branch replay")
10793 .to_snapshot(),
10794 tree.to_snapshot()
10795 );
10796 }
10797 }
10798
10799 #[test]
10800 fn rejected_initial_timeline_operation_does_not_install_a_baseline() {
10801 for coalesced in [false, true] {
10802 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10803 let before_tree = tree.to_snapshot();
10804 let mut timeline = PaneInteractionTimeline::default();
10805 let before_history = timeline.clone();
10806 let invalid = PaneOperation::CloseNode {
10807 target: id(u64::MAX),
10808 };
10809 let result = if coalesced {
10810 timeline.apply_and_record_coalesced_resize_delta(&mut tree, 1, 1, invalid, 0)
10811 } else {
10812 timeline.apply_and_record(&mut tree, 1, 1, invalid)
10813 };
10814 assert!(result.is_err());
10815 assert_eq!(tree.to_snapshot(), before_tree);
10816 assert_eq!(
10817 timeline, before_history,
10818 "rejection changed baseline; coalesced={coalesced}"
10819 );
10820 }
10821 }
10822
10823 #[test]
10824 fn interaction_timeline_coalesces_resize_deltas_for_same_split() {
10825 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10826 let initial_hash = tree.state_hash();
10827 let split = id(1);
10828 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10829 let ratios = [
10830 PaneSplitRatio::new(4, 6).expect("valid ratio"),
10831 PaneSplitRatio::new(7, 3).expect("valid ratio"),
10832 PaneSplitRatio::new(2, 5).expect("valid ratio"),
10833 ];
10834
10835 for (index, ratio) in ratios.into_iter().enumerate() {
10836 timeline
10837 .apply_and_record_coalesced_resize_delta(
10838 &mut tree,
10839 index as u64 + 1,
10840 100 + index as u64,
10841 PaneOperation::SetSplitRatio { split, ratio },
10842 0,
10843 )
10844 .expect("ratio update should apply");
10845 }
10846
10847 assert_eq!(timeline.entries.len(), 1);
10848 assert_eq!(timeline.cursor, 1);
10849 assert_eq!(timeline.entries[0].operation_id, 102);
10850 assert_eq!(timeline.entries[0].before_hash, initial_hash);
10851 assert_eq!(split_ratio(&tree, split), ratios[2]);
10852 assert_eq!(timeline.next_operation_id(), 103);
10853
10854 let replayed = timeline.replay().expect("replay should succeed");
10855 assert_eq!(replayed.to_snapshot(), tree.to_snapshot());
10856
10857 assert!(timeline.undo(&mut tree).expect("undo should succeed"));
10858 assert_eq!(tree.state_hash(), initial_hash);
10859 assert!(timeline.redo(&mut tree).expect("redo should succeed"));
10860 assert_eq!(split_ratio(&tree, split), ratios[2]);
10861 }
10862
10863 #[test]
10864 fn interaction_timeline_keeps_separate_resize_gestures_distinct() {
10865 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10866 let split = id(1);
10867 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10868 let first_ratio = PaneSplitRatio::new(4, 6).expect("valid ratio");
10869 let second_ratio = PaneSplitRatio::new(7, 3).expect("valid ratio");
10870
10871 timeline
10872 .apply_and_record_coalesced_resize_delta(
10873 &mut tree,
10874 1,
10875 101,
10876 PaneOperation::SetSplitRatio {
10877 split,
10878 ratio: first_ratio,
10879 },
10880 100,
10881 )
10882 .expect("first gesture should apply");
10883 timeline
10884 .apply_and_record_coalesced_resize_delta(
10885 &mut tree,
10886 2,
10887 102,
10888 PaneOperation::SetSplitRatio {
10889 split,
10890 ratio: second_ratio,
10891 },
10892 101,
10893 )
10894 .expect("second gesture should apply");
10895
10896 assert_eq!(timeline.entries.len(), 2);
10897 assert_eq!(timeline.cursor, 2);
10898 assert_eq!(split_ratio(&tree, split), second_ratio);
10899 assert!(timeline.undo(&mut tree).expect("undo should succeed"));
10900 assert_eq!(split_ratio(&tree, split), first_ratio);
10901 }
10902
10903 #[test]
10904 fn interaction_timeline_refreshes_checkpoint_when_coalescing_head() {
10905 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10906 let split = id(1);
10907 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10908 timeline.checkpoint_interval = 1;
10909
10910 timeline
10911 .apply_and_record_coalesced_resize_delta(
10912 &mut tree,
10913 1,
10914 201,
10915 PaneOperation::SetSplitRatio {
10916 split,
10917 ratio: PaneSplitRatio::new(6, 4).expect("valid ratio"),
10918 },
10919 200,
10920 )
10921 .expect("first ratio should apply");
10922 timeline
10923 .apply_and_record_coalesced_resize_delta(
10924 &mut tree,
10925 2,
10926 202,
10927 PaneOperation::SetSplitRatio {
10928 split,
10929 ratio: PaneSplitRatio::new(8, 2).expect("valid ratio"),
10930 },
10931 200,
10932 )
10933 .expect("second ratio should apply");
10934
10935 assert_eq!(timeline.entries.len(), 1);
10936 assert_eq!(timeline.checkpoints.len(), 1);
10937 assert_eq!(timeline.checkpoints[0].applied_len, 1);
10938 assert_eq!(timeline.checkpoints[0].snapshot, tree.to_snapshot());
10939 }
10940
10941 #[test]
10942 fn interaction_timeline_enforces_configured_max_entries() {
10943 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10944 let mut timeline = PaneInteractionTimeline::with_baseline(&tree).with_max_entries(3);
10945 let split = id(1);
10946 let ratios = [
10947 PaneSplitRatio::new(4, 6).expect("valid ratio"),
10948 PaneSplitRatio::new(5, 5).expect("valid ratio"),
10949 PaneSplitRatio::new(6, 4).expect("valid ratio"),
10950 PaneSplitRatio::new(7, 3).expect("valid ratio"),
10951 PaneSplitRatio::new(8, 2).expect("valid ratio"),
10952 ];
10953
10954 for (index, ratio) in ratios.into_iter().enumerate() {
10955 timeline
10956 .apply_and_record(
10957 &mut tree,
10958 index as u64 + 1,
10959 300 + index as u64,
10960 PaneOperation::SetSplitRatio { split, ratio },
10961 )
10962 .expect("ratio update should apply");
10963 }
10964
10965 assert_eq!(timeline.entries.len(), 3);
10966 assert_eq!(timeline.cursor, 3);
10967 assert_eq!(timeline.entries[0].operation_id, 302);
10968 assert_eq!(timeline.entries[2].operation_id, 304);
10969 assert_eq!(timeline.next_operation_id(), 305);
10970 let replayed = timeline.replay().expect("replay should succeed");
10971 assert_eq!(replayed.to_snapshot(), tree.to_snapshot());
10972 }
10973
10974 #[test]
10975 fn interaction_timeline_records_checkpoints_at_default_interval() {
10976 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10977 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10978 let split_ids: Vec<_> = tree
10979 .nodes()
10980 .filter_map(|node| match node.kind {
10981 PaneNodeKind::Split(_) => Some(node.id),
10982 PaneNodeKind::Leaf(_) => None,
10983 })
10984 .collect();
10985 let ratios = [
10986 PaneSplitRatio::new(3, 2).expect("valid ratio"),
10987 PaneSplitRatio::new(2, 3).expect("valid ratio"),
10988 PaneSplitRatio::new(5, 4).expect("valid ratio"),
10989 PaneSplitRatio::new(4, 5).expect("valid ratio"),
10990 ];
10991
10992 for idx in 0..16u64 {
10993 timeline
10994 .apply_and_record(
10995 &mut tree,
10996 idx,
10997 30_000 + idx,
10998 PaneOperation::SetSplitRatio {
10999 split: split_ids[idx as usize % split_ids.len()],
11000 ratio: ratios[idx as usize % ratios.len()],
11001 },
11002 )
11003 .expect("ratio update should apply");
11004 }
11005
11006 assert_eq!(timeline.checkpoints.len(), 1);
11007 assert_eq!(timeline.checkpoints[0].applied_len, 16);
11008 assert_eq!(timeline.checkpoints[0].snapshot, tree.to_snapshot());
11009 }
11010
11011 #[test]
11012 fn interaction_timeline_discards_stale_checkpoints_after_branching() {
11013 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11014 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
11015 let split_ids: Vec<_> = tree
11016 .nodes()
11017 .filter_map(|node| match node.kind {
11018 PaneNodeKind::Split(_) => Some(node.id),
11019 PaneNodeKind::Leaf(_) => None,
11020 })
11021 .collect();
11022 let ratios = [
11023 PaneSplitRatio::new(3, 2).expect("valid ratio"),
11024 PaneSplitRatio::new(2, 3).expect("valid ratio"),
11025 PaneSplitRatio::new(5, 4).expect("valid ratio"),
11026 PaneSplitRatio::new(4, 5).expect("valid ratio"),
11027 ];
11028
11029 for idx in 0..32u64 {
11030 timeline
11031 .apply_and_record(
11032 &mut tree,
11033 idx,
11034 40_000 + idx,
11035 PaneOperation::SetSplitRatio {
11036 split: split_ids[idx as usize % split_ids.len()],
11037 ratio: ratios[idx as usize % ratios.len()],
11038 },
11039 )
11040 .expect("ratio update should apply");
11041 }
11042
11043 assert_eq!(timeline.checkpoints.len(), 2);
11044 timeline.undo(&mut tree).expect("undo should succeed");
11045 timeline.undo(&mut tree).expect("undo should succeed");
11046 timeline.undo(&mut tree).expect("undo should succeed");
11047 timeline.undo(&mut tree).expect("undo should succeed");
11048 timeline.undo(&mut tree).expect("undo should succeed");
11049
11050 timeline
11051 .apply_and_record(
11052 &mut tree,
11053 99,
11054 99_999,
11055 PaneOperation::SetSplitRatio {
11056 split: split_ids[0],
11057 ratio: PaneSplitRatio::new(7, 5).expect("valid ratio"),
11058 },
11059 )
11060 .expect("branching update should apply");
11061
11062 assert_eq!(timeline.cursor, 28);
11063 assert_eq!(timeline.entries.len(), 28);
11064 assert_eq!(timeline.checkpoints.len(), 1);
11065 assert_eq!(timeline.checkpoints[0].applied_len, 16);
11066 }
11067
11068 #[test]
11069 fn interaction_timeline_replay_diagnostics_report_checkpoint_hit_and_depth() {
11070 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11071 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
11072 let split_ids: Vec<_> = tree
11073 .nodes()
11074 .filter_map(|node| match node.kind {
11075 PaneNodeKind::Split(_) => Some(node.id),
11076 PaneNodeKind::Leaf(_) => None,
11077 })
11078 .collect();
11079
11080 for idx in 0..20u64 {
11081 timeline
11082 .apply_and_record(
11083 &mut tree,
11084 idx,
11085 50_000 + idx,
11086 PaneOperation::SetSplitRatio {
11087 split: split_ids[idx as usize % split_ids.len()],
11088 ratio: PaneSplitRatio::new(3, 2).expect("valid ratio"),
11089 },
11090 )
11091 .expect("ratio update should apply");
11092 }
11093
11094 let diagnostics = timeline.replay_diagnostics();
11095 assert_eq!(diagnostics.entry_count, 20);
11096 assert_eq!(diagnostics.cursor, 20);
11097 assert_eq!(diagnostics.checkpoint_interval, 16);
11098 assert_eq!(diagnostics.checkpoint_count, 1);
11099 assert!(diagnostics.checkpoint_hit);
11100 assert_eq!(diagnostics.replay_start_idx, 16);
11101 assert_eq!(diagnostics.replay_depth, 4);
11102 }
11103
11104 #[test]
11105 fn interaction_timeline_retention_diagnostics_reports_entry_and_snapshot_footprint() {
11106 let mut tree = PaneTree::singleton("root");
11107 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
11108 timeline.checkpoint_interval = 1;
11109
11110 timeline
11111 .apply_and_record(
11112 &mut tree,
11113 1,
11114 60_000,
11115 PaneOperation::SplitLeaf {
11116 target: id(1),
11117 axis: SplitAxis::Horizontal,
11118 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
11119 placement: PanePlacement::ExistingFirst,
11120 new_leaf: PaneLeaf::new("aux"),
11121 },
11122 )
11123 .expect("split should apply");
11124
11125 let diagnostics = timeline.retention_diagnostics();
11126 assert_eq!(diagnostics.entry_count, 1);
11127 assert_eq!(diagnostics.cursor, 1);
11128 assert_eq!(diagnostics.redo_entry_count, 0);
11129 assert_eq!(diagnostics.checkpoint_count, 1);
11130 assert_eq!(diagnostics.checkpoint_interval, 1);
11131 assert!(diagnostics.baseline_present);
11132 assert_eq!(diagnostics.retained_snapshot_count, 2);
11133 assert_eq!(diagnostics.baseline_node_count, 1);
11134 assert_eq!(diagnostics.checkpoint_node_count, 3);
11135 assert_eq!(diagnostics.retained_snapshot_node_count, 4);
11136 assert_eq!(diagnostics.retained_operation_payload_bytes, "aux".len());
11137 assert!(
11138 diagnostics.retained_leaf_payload_bytes >= "root".len() + "aux".len(),
11139 "leaf payload bytes should include retained surface keys"
11140 );
11141 assert!(
11142 diagnostics.estimated_total_retained_bytes
11143 >= diagnostics.estimated_entry_struct_bytes
11144 + diagnostics.estimated_checkpoint_struct_bytes
11145 + diagnostics.estimated_snapshot_struct_bytes
11146 );
11147 }
11148
11149 #[test]
11150 fn interaction_timeline_retention_diagnostics_separates_leaf_keys_from_extensions() {
11151 let mut snapshot = make_valid_snapshot();
11152 snapshot
11153 .extensions
11154 .insert("tree".to_string(), "wide".to_string());
11155
11156 let left_node = snapshot
11157 .nodes
11158 .iter_mut()
11159 .find(|node| node.id == id(2))
11160 .expect("left leaf should be present");
11161 left_node
11162 .extensions
11163 .insert("node".to_string(), "hot".to_string());
11164 let PaneNodeKind::Leaf(leaf) = &mut left_node.kind else {
11165 let expected_leaf_node = false;
11166 assert!(expected_leaf_node, "left node should be a leaf");
11167 return;
11168 };
11169 leaf.extensions
11170 .insert("leaf".to_string(), "memo".to_string());
11171
11172 let tree = PaneTree::from_snapshot(snapshot).expect("snapshot should validate");
11173 let timeline = PaneInteractionTimeline::with_baseline(&tree);
11174 let diagnostics = timeline.retention_diagnostics();
11175
11176 assert_eq!(diagnostics.retained_snapshot_count, 1);
11177 assert_eq!(
11178 diagnostics.retained_leaf_payload_bytes,
11179 "left".len() + "right".len()
11180 );
11181 assert_eq!(diagnostics.retained_extension_entry_count, 3);
11182 assert_eq!(
11183 diagnostics.retained_extension_payload_bytes,
11184 "tree".len() + "wide".len() + "node".len() + "hot".len() + "leaf".len() + "memo".len()
11185 );
11186 }
11187
11188 #[test]
11189 fn interaction_timeline_retention_diagnostics_reports_redo_entries() {
11190 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11191 let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
11192 let split = id(1);
11193
11194 for (idx, ratio) in [
11195 PaneSplitRatio::new(4, 6).expect("valid ratio"),
11196 PaneSplitRatio::new(6, 4).expect("valid ratio"),
11197 ]
11198 .into_iter()
11199 .enumerate()
11200 {
11201 timeline
11202 .apply_and_record(
11203 &mut tree,
11204 idx as u64 + 1,
11205 70_000 + idx as u64,
11206 PaneOperation::SetSplitRatio { split, ratio },
11207 )
11208 .expect("ratio update should apply");
11209 }
11210
11211 assert!(timeline.undo(&mut tree).expect("undo should succeed"));
11212 let diagnostics = timeline.retention_diagnostics();
11213 assert_eq!(diagnostics.entry_count, 2);
11214 assert_eq!(diagnostics.cursor, 1);
11215 assert_eq!(diagnostics.redo_entry_count, 1);
11216 }
11217
11218 #[test]
11219 fn interaction_timeline_checkpoint_decision_prefers_shorter_interval_for_expensive_replay_steps()
11220 {
11221 let slow_replay =
11222 PaneInteractionTimeline::checkpoint_decision(10_000, 2_500).checkpoint_interval;
11223 let cheap_replay =
11224 PaneInteractionTimeline::checkpoint_decision(10_000, 100).checkpoint_interval;
11225
11226 assert!(slow_replay < cheap_replay);
11227 assert!(slow_replay >= 1);
11228 assert!(cheap_replay >= 1);
11229 }
11230
11231 #[test]
11232 fn set_split_ratio_uses_local_validation_strategy() {
11233 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11234 assert_eq!(
11235 tree.validation_strategy_for_operation(PaneOperationKind::SetSplitRatio),
11236 PaneValidationStrategy::LocalClosure
11237 );
11238 assert_eq!(
11239 tree.validation_strategy_for_operation(PaneOperationKind::NormalizeRatios),
11240 PaneValidationStrategy::FullTree
11241 );
11242 }
11243
11244 #[test]
11245 fn local_validation_closure_rejects_parent_mismatch_for_touched_split() {
11246 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11247 let split_id = id(1);
11248 let child_id = id(2);
11249 tree.nodes.get_mut(&child_id).expect("child present").parent = None;
11250
11251 let err = tree
11252 .validate_local_closure(&[split_id])
11253 .expect_err("local closure should detect broken child parent");
11254 assert!(matches!(
11255 err,
11256 PaneModelError::ParentMismatch {
11257 node_id,
11258 expected: Some(expected),
11259 actual: None,
11260 } if node_id == child_id && expected == split_id
11261 ));
11262 }
11263
11264 #[test]
11265 fn operation_family_classifier_partitions_local_and_structural_kinds() {
11266 assert_eq!(
11267 PaneOperationKind::SetSplitRatio.family(),
11268 PaneOperationFamily::Local
11269 );
11270 for kind in [
11271 PaneOperationKind::SplitLeaf,
11272 PaneOperationKind::CloseNode,
11273 PaneOperationKind::MoveSubtree,
11274 PaneOperationKind::SwapNodes,
11275 PaneOperationKind::NormalizeRatios,
11276 ] {
11277 assert_eq!(
11278 kind.family(),
11279 PaneOperationFamily::Structural,
11280 "operation kind {kind:?} must be structural"
11281 );
11282 }
11283 let op = PaneOperation::SetSplitRatio {
11285 split: id(1),
11286 ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
11287 };
11288 assert_eq!(op.family(), PaneOperationFamily::Local);
11289 assert_eq!(op.family(), op.kind().family());
11290 }
11291
11292 #[test]
11293 fn validation_strategy_is_derived_from_operation_family() {
11294 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11295 assert_eq!(
11296 tree.validation_strategy_for_operation(PaneOperationKind::SetSplitRatio),
11297 PaneValidationStrategy::LocalClosure
11298 );
11299 for kind in [
11300 PaneOperationKind::SplitLeaf,
11301 PaneOperationKind::CloseNode,
11302 PaneOperationKind::MoveSubtree,
11303 PaneOperationKind::SwapNodes,
11304 PaneOperationKind::NormalizeRatios,
11305 ] {
11306 assert_eq!(
11307 tree.validation_strategy_for_operation(kind),
11308 PaneValidationStrategy::FullTree,
11309 "structural kind {kind:?} must use whole-tree validation"
11310 );
11311 }
11312 }
11313
11314 #[test]
11315 fn always_full_validation_mode_catches_corruption_outside_touched_closure() {
11316 let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
11320 let far_leaf = id(5);
11323 tree.nodes.get_mut(&far_leaf).expect("present").parent = None;
11324
11325 let touched = [id(1)];
11326
11327 assert!(
11331 tree.validate_after_operation_with_mode(
11332 PaneOperationKind::SetSplitRatio,
11333 &touched,
11334 PaneValidationMode::Adaptive,
11335 )
11336 .is_ok(),
11337 "local closure over the root split must not see a far leaf corruption"
11338 );
11339
11340 assert!(
11342 tree.validate_after_operation_with_mode(
11343 PaneOperationKind::SetSplitRatio,
11344 &touched,
11345 PaneValidationMode::AlwaysFull,
11346 )
11347 .is_err(),
11348 "forced full validation must detect the far leaf corruption"
11349 );
11350 }
11351
11352 fn neutral_pressure() -> PanePressureSnapProfile {
11353 PanePressureSnapProfile {
11354 strength_bps: 5_000,
11355 hysteresis_bps: 100,
11356 }
11357 }
11358
11359 fn first_share_bps(op: &PaneOperation) -> u32 {
11360 match op {
11361 PaneOperation::SetSplitRatio { ratio, .. } => {
11362 ratio.numerator() * 10_000 / (ratio.numerator() + ratio.denominator())
11363 }
11364 other => panic!("expected SetSplitRatio, got {other:?}"),
11365 }
11366 }
11367
11368 fn split_target(split: PaneId, axis: SplitAxis) -> PaneResizeTarget {
11369 PaneResizeTarget {
11370 split_id: split,
11371 axis,
11372 }
11373 }
11374
11375 fn drag_updated_transition(
11376 target: PaneResizeTarget,
11377 current: PanePointerPosition,
11378 ) -> PaneDragResizeTransition {
11379 PaneDragResizeTransition {
11380 transition_id: 1,
11381 sequence: 1,
11382 from: PaneDragResizeState::Idle,
11383 to: PaneDragResizeState::Idle,
11384 effect: PaneDragResizeEffect::DragUpdated {
11385 target,
11386 pointer_id: 1,
11387 previous: PanePointerPosition::new(current.x - 1, current.y),
11388 current,
11389 delta_x: 1,
11390 delta_y: 0,
11391 total_delta_x: 1,
11392 total_delta_y: 0,
11393 },
11394 }
11395 }
11396
11397 #[test]
11398 fn plan_splitter_resize_tracks_pointer_along_axis() {
11399 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11400 let layout = tree
11401 .solve_layout(Rect::new(0, 0, 60, 16))
11402 .expect("layout solves");
11403 let rect = layout.rect(id(1)).expect("root split rect");
11404 let target = split_target(id(1), SplitAxis::Horizontal);
11405
11406 let left_pointer = PanePointerPosition::new(i32::from(rect.x) + 2, i32::from(rect.y) + 4);
11407 let right_pointer = PanePointerPosition::new(
11408 i32::from(rect.x) + i32::from(rect.width) - 3,
11409 i32::from(rect.y) + 4,
11410 );
11411
11412 let left_op = tree
11413 .plan_splitter_resize(target, &layout, left_pointer, neutral_pressure())
11414 .expect("left plan");
11415 let right_op = tree
11416 .plan_splitter_resize(target, &layout, right_pointer, neutral_pressure())
11417 .expect("right plan");
11418
11419 assert!(matches!(left_op, PaneOperation::SetSplitRatio { split, .. } if split == id(1)));
11420 assert!(matches!(right_op, PaneOperation::SetSplitRatio { split, .. } if split == id(1)));
11421 assert!(
11423 first_share_bps(&right_op) > first_share_bps(&left_op),
11424 "right={} left={}",
11425 first_share_bps(&right_op),
11426 first_share_bps(&left_op)
11427 );
11428 }
11429
11430 #[test]
11431 fn plan_splitter_resize_rejects_non_split_target() {
11432 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11433 let layout = tree
11434 .solve_layout(Rect::new(0, 0, 60, 16))
11435 .expect("layout solves");
11436 let err = tree
11438 .plan_splitter_resize(
11439 split_target(id(2), SplitAxis::Horizontal),
11440 &layout,
11441 PanePointerPosition::new(5, 5),
11442 neutral_pressure(),
11443 )
11444 .expect_err("leaf target must be rejected");
11445 assert_eq!(err, PaneSplitterResizePlanError::NotASplit { node: id(2) });
11446 }
11447
11448 #[test]
11449 fn plan_splitter_resize_rejects_axis_mismatch() {
11450 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11451 let layout = tree
11452 .solve_layout(Rect::new(0, 0, 60, 16))
11453 .expect("layout solves");
11454 let err = tree
11455 .plan_splitter_resize(
11456 split_target(id(1), SplitAxis::Vertical),
11457 &layout,
11458 PanePointerPosition::new(5, 5),
11459 neutral_pressure(),
11460 )
11461 .expect_err("axis mismatch must be rejected");
11462 assert_eq!(
11463 err,
11464 PaneSplitterResizePlanError::AxisMismatch {
11465 split: id(1),
11466 expected: SplitAxis::Vertical,
11467 actual: SplitAxis::Horizontal,
11468 }
11469 );
11470 }
11471
11472 #[test]
11473 fn plan_splitter_resize_rejects_missing_split() {
11474 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11475 let layout = tree
11476 .solve_layout(Rect::new(0, 0, 60, 16))
11477 .expect("layout solves");
11478 let err = tree
11479 .plan_splitter_resize(
11480 split_target(id(99), SplitAxis::Horizontal),
11481 &layout,
11482 PanePointerPosition::new(5, 5),
11483 neutral_pressure(),
11484 )
11485 .expect_err("missing split must be rejected");
11486 assert_eq!(
11487 err,
11488 PaneSplitterResizePlanError::MissingSplit { split: id(99) }
11489 );
11490 }
11491
11492 #[test]
11493 fn plan_splitter_nudge_steps_current_ratio() {
11494 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11495 let target = split_target(id(1), SplitAxis::Horizontal);
11497 let up = tree
11498 .plan_splitter_nudge(target, i32::from(PANE_SNAP_DEFAULT_STEP_BPS))
11499 .expect("nudge up");
11500 let down = tree
11501 .plan_splitter_nudge(target, -i32::from(PANE_SNAP_DEFAULT_STEP_BPS))
11502 .expect("nudge down");
11503 assert_eq!(first_share_bps(&up), 6_500);
11504 assert_eq!(first_share_bps(&down), 5_500);
11505 }
11506
11507 #[test]
11508 fn operations_for_transition_drag_updated_mutates_ratio() {
11509 let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11510 let layout = tree
11511 .solve_layout(Rect::new(0, 0, 60, 16))
11512 .expect("layout solves");
11513 let rect = layout.rect(id(1)).expect("root split rect");
11514 let target = split_target(id(1), SplitAxis::Horizontal);
11515 let pointer = PanePointerPosition::new(
11516 i32::from(rect.x) + i32::from(rect.width) - 3,
11517 i32::from(rect.y) + 4,
11518 );
11519 let transition = drag_updated_transition(target, pointer);
11520
11521 let before = split_ratio(&tree, id(1));
11522 let before_share =
11523 before.numerator() * 10_000 / (before.numerator() + before.denominator());
11524
11525 let ops = tree.operations_for_transition(&transition, &layout, neutral_pressure());
11526 assert_eq!(ops.len(), 1);
11527 for (offset, op) in ops.iter().cloned().enumerate() {
11528 tree.apply_operation(1_000 + offset as u64, op)
11529 .expect("operation applies");
11530 }
11531
11532 let after = split_ratio(&tree, id(1));
11533 let after_share = after.numerator() * 10_000 / (after.numerator() + after.denominator());
11534 assert!(
11535 after_share > before_share,
11536 "after={after_share} before={before_share}"
11537 );
11538 }
11539
11540 #[test]
11541 fn operations_for_transition_keyboard_applied_nudges() {
11542 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11543 let layout = tree
11544 .solve_layout(Rect::new(0, 0, 60, 16))
11545 .expect("layout solves");
11546 let target = split_target(id(1), SplitAxis::Horizontal);
11547 let transition = PaneDragResizeTransition {
11548 transition_id: 2,
11549 sequence: 2,
11550 from: PaneDragResizeState::Idle,
11551 to: PaneDragResizeState::Idle,
11552 effect: PaneDragResizeEffect::KeyboardApplied {
11553 target,
11554 direction: PaneResizeDirection::Increase,
11555 units: 2,
11556 },
11557 };
11558 let ops = tree.operations_for_transition(&transition, &layout, neutral_pressure());
11559 assert_eq!(ops.len(), 1);
11560 assert_eq!(first_share_bps(&ops[0]), 7_000);
11562 }
11563
11564 #[test]
11565 fn operations_for_transition_is_empty_for_non_geometric_and_unresolvable() {
11566 let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11567 let layout = tree
11568 .solve_layout(Rect::new(0, 0, 60, 16))
11569 .expect("layout solves");
11570 let target = split_target(id(1), SplitAxis::Horizontal);
11571
11572 let armed = PaneDragResizeTransition {
11573 transition_id: 3,
11574 sequence: 3,
11575 from: PaneDragResizeState::Idle,
11576 to: PaneDragResizeState::Idle,
11577 effect: PaneDragResizeEffect::Armed {
11578 target,
11579 pointer_id: 1,
11580 origin: PanePointerPosition::new(5, 5),
11581 },
11582 };
11583 assert!(
11584 tree.operations_for_transition(&armed, &layout, neutral_pressure())
11585 .is_empty()
11586 );
11587
11588 let canceled = PaneDragResizeTransition {
11589 transition_id: 4,
11590 sequence: 4,
11591 from: PaneDragResizeState::Idle,
11592 to: PaneDragResizeState::Idle,
11593 effect: PaneDragResizeEffect::Canceled {
11594 target: Some(target),
11595 pointer_id: Some(1),
11596 reason: PaneCancelReason::EscapeKey,
11597 },
11598 };
11599 assert!(
11600 tree.operations_for_transition(&canceled, &layout, neutral_pressure())
11601 .is_empty()
11602 );
11603
11604 let stale = drag_updated_transition(
11607 split_target(id(99), SplitAxis::Horizontal),
11608 PanePointerPosition::new(10, 5),
11609 );
11610 assert!(
11611 tree.operations_for_transition(&stale, &layout, neutral_pressure())
11612 .is_empty()
11613 );
11614 }
11615}