1pub mod layout;
16
17use crate::capture::TrackMask;
18use crate::event::Event;
19use crate::junction::{Edge, Junction, JunctionMark, Weight, divider_junction};
20use crate::theme::Role;
21use crate::view::{Context, DrawCtx, Group, GrowMode, Point, Rect, View, ViewId};
22
23pub use layout::{Constraints, Orientation};
24use layout::{Slot, relax_weight, solve};
25
26#[derive(Clone, Copy, PartialEq, Eq, Debug)]
28pub enum DividerStyle {
29 Line,
31 Handle,
33 Hidden,
35 Locked,
37}
38
39impl DividerStyle {
40 pub fn draggable_live(&self) -> bool {
42 matches!(self, DividerStyle::Line | DividerStyle::Handle)
43 }
44 pub fn movable(&self) -> bool {
46 !matches!(self, DividerStyle::Locked)
47 }
48}
49
50fn divider_role(moving: bool, active: bool) -> Role {
53 if moving {
54 Role::FrameDragging
55 } else if active {
56 Role::FrameActive
57 } else {
58 Role::FramePassive
59 }
60}
61
62pub struct Splitter {
69 group: Group,
70 orientation: Orientation,
71 slots: Vec<Slot>,
73 divider_styles: Vec<DividerStyle>,
75 default_style: DividerStyle,
76 active_divider: Option<usize>,
78 saved_weights: Vec<f64>,
80 abs_origin: Point,
82 dragging: Option<usize>,
84 joined: bool,
89}
90
91impl Splitter {
92 fn new(bounds: Rect, orientation: Orientation) -> Self {
93 let mut group = Group::new(bounds);
94 group.state_mut().grow_mode = GrowMode {
101 hi_x: true,
102 hi_y: true,
103 ..Default::default()
104 };
105 Splitter {
106 group,
107 orientation,
108 slots: Vec::new(),
109 divider_styles: Vec::new(),
110 default_style: DividerStyle::Line,
111 active_divider: None,
112 saved_weights: Vec::new(),
113 abs_origin: bounds.a,
114 dragging: None,
115 joined: false,
116 }
117 }
118
119 pub fn joined(mut self) -> Self {
125 self.set_joined(true);
126 self
127 }
128
129 pub fn with_grow_mode(mut self, grow_mode: GrowMode) -> Self {
133 self.group.state_mut().grow_mode = grow_mode;
134 self
135 }
136
137 pub fn set_joined(&mut self, on: bool) {
140 self.joined = on;
141 let ids = self.group.child_ids_in_order();
142 for id in ids {
143 if let Some(sub) = self
144 .group
145 .child_mut(id)
146 .and_then(|v| v.as_any_mut())
147 .and_then(|a| a.downcast_mut::<Splitter>())
148 {
149 sub.set_joined(on);
150 }
151 }
152 }
153
154 pub fn cols() -> Self {
156 Splitter::new(Rect::new(0, 0, 0, 0), Orientation::Cols)
157 }
158
159 pub fn rows() -> Self {
161 Splitter::new(Rect::new(0, 0, 0, 0), Orientation::Rows)
162 }
163
164 fn content_len(&self) -> i32 {
166 let b = self.group.state().get_bounds();
167 let extent = match self.orientation {
168 Orientation::Cols => b.b.x - b.a.x,
169 Orientation::Rows => b.b.y - b.a.y,
170 };
171 let dividers = self.slots.len().saturating_sub(1) as i32;
172 (extent - dividers).max(0)
173 }
174
175 pub fn insert(&mut self, view: Box<dyn View>, c: Constraints) -> ViewId {
177 let id = self.group.insert(view);
178 self.slots.push(Slot::from_constraints(c));
179 if self.joined
182 && let Some(sub) = self
183 .group
184 .child_mut(id)
185 .and_then(|v| v.as_any_mut())
186 .and_then(|a| a.downcast_mut::<Splitter>())
187 {
188 sub.set_joined(true);
189 }
190 self.resolve_layout_local();
191 id
192 }
193
194 fn style_of(&self, i: usize) -> DividerStyle {
196 self.divider_styles
197 .get(i)
198 .copied()
199 .unwrap_or(self.default_style)
200 }
201
202 fn is_moving(&self, i: usize) -> bool {
205 self.dragging == Some(i) || self.active_divider == Some(i)
206 }
207
208 fn draw_dividers(&self, ctx: &mut DrawCtx) {
212 let b = self.group.state().get_bounds();
213 let sizes = solve(&self.slots, self.content_len());
214 let (frame_v, frame_h) = {
216 let g = ctx.glyphs();
217 (g.frame_v, g.frame_h)
218 };
219 let run = match self.orientation {
221 Orientation::Cols => b.b.y - b.a.y,
222 Orientation::Rows => b.b.x - b.a.x,
223 };
224 let mut cursor = 0i32; for i in 0..self.slots.len().saturating_sub(1) {
226 cursor += sizes.get(i).copied().unwrap_or(0);
227 let style = self.style_of(i);
228 let moving = self.is_moving(i);
229 let role = divider_role(moving, self.state().state.active);
230 let st = ctx.style(role);
231 let (line_glyph, nub_glyph) = match self.orientation {
233 Orientation::Cols => (frame_v, frame_v),
234 Orientation::Rows => (frame_h, frame_h),
235 };
236 let draw_full = matches!(style, DividerStyle::Line) || moving;
237 let draw_handle = matches!(style, DividerStyle::Handle) && !moving;
238 for k in 0..run {
239 let (x, y) = match self.orientation {
240 Orientation::Cols => (cursor, k),
241 Orientation::Rows => (k, cursor),
242 };
243 if draw_full {
244 ctx.put_char(x, y, line_glyph, st);
245 } else if draw_handle && k == run / 2 {
246 ctx.put_char(x, y, nub_glyph, st);
247 }
248 }
250 cursor += 1; }
252 }
253
254 pub fn pane(mut self, view: Box<dyn View>, c: Constraints) -> Self {
256 self.insert(view, c);
257 self
258 }
259
260 pub fn default_divider(mut self, style: DividerStyle) -> Self {
262 self.default_style = style;
263 self.resolve_layout_local();
264 self
265 }
266
267 pub fn divider(mut self, i: usize, style: DividerStyle) -> Self {
269 self.ensure_divider_len();
270 if i < self.divider_styles.len() {
271 self.divider_styles[i] = style;
272 }
273 self
274 }
275
276 fn ensure_divider_len(&mut self) {
278 let want = self.slots.len().saturating_sub(1);
279 while self.divider_styles.len() < want {
280 self.divider_styles.push(self.default_style);
281 }
282 }
283
284 fn resolve_layout_local(&mut self) {
287 let sizes = solve(&self.slots, self.content_len());
288 let ext = self.group.state().get_extent();
294 let mut cursor = match self.orientation {
295 Orientation::Cols => ext.a.x,
296 Orientation::Rows => ext.a.y,
297 };
298 let ids = self.group.child_ids_in_order();
299 let mut resized = false;
300 for (i, id) in ids.iter().enumerate() {
301 let size = sizes.get(i).copied().unwrap_or(0);
302 let rect = match self.orientation {
303 Orientation::Cols => Rect::new(cursor, ext.a.y, cursor + size, ext.b.y),
304 Orientation::Rows => Rect::new(ext.a.x, cursor, ext.b.x, cursor + size),
305 };
306 if let Some(child) = self.group.find_mut(*id) {
307 resized |= child.state().size != rect.b - rect.a;
308 child.change_bounds(rect);
309 }
310 cursor += size + 1; }
312 if resized {
315 self.group.mark_bounds_dirty();
316 }
317 }
318
319 fn divider_axis_pos(&self, i: usize) -> Option<i32> {
322 if i + 1 >= self.slots.len() {
323 return None;
324 }
325 let sizes = solve(&self.slots, self.content_len());
326 let mut pos = 0;
327 for k in 0..=i {
328 pos += sizes.get(k).copied().unwrap_or(0);
329 if k < i {
330 pos += 1; }
332 }
333 Some(pos)
334 }
335
336 pub(crate) fn frame_junction_marks(&mut self, frame_bounds: Rect) -> Vec<JunctionMark> {
343 if !self.joined {
344 return Vec::new();
345 }
346 let mut out = Vec::new();
347 let origin = self.group.state().get_bounds().a; self.collect_frame_marks(frame_bounds, origin, &mut out);
349 out
350 }
351
352 fn collect_frame_marks(&mut self, fb: Rect, origin: Point, out: &mut Vec<JunctionMark>) {
356 let ext = self.group.state().get_extent();
357 let w = ext.b.x - ext.a.x;
358 let h = ext.b.y - ext.a.y;
359 let sizes = solve(&self.slots, self.content_len());
360 let stem = Weight::Single; let fw = fb.b.x - fb.a.x; let fh = fb.b.y - fb.a.y; let mut cursor = 0i32; for i in 0..self.slots.len().saturating_sub(1) {
366 cursor += sizes.get(i).copied().unwrap_or(0);
367 let local = cursor; let draws_full = matches!(self.style_of(i), DividerStyle::Line) || self.is_moving(i);
369 if draws_full {
370 match self.orientation {
371 Orientation::Cols => {
372 let off = (origin.x - fb.a.x) + local;
373 let interior = off > 0 && off < fw - 1;
374 if interior && origin.y == fb.a.y + 1 {
375 out.push(JunctionMark {
376 edge: Edge::Top,
377 offset: off,
378 stem,
379 });
380 }
381 if interior && origin.y + h == fb.b.y - 1 {
382 out.push(JunctionMark {
383 edge: Edge::Bottom,
384 offset: off,
385 stem,
386 });
387 }
388 }
389 Orientation::Rows => {
390 let off = (origin.y - fb.a.y) + local;
391 let interior = off > 0 && off < fh - 1;
392 if interior && origin.x == fb.a.x + 1 {
393 out.push(JunctionMark {
394 edge: Edge::Left,
395 offset: off,
396 stem,
397 });
398 }
399 if interior && origin.x + w == fb.b.x - 1 {
400 out.push(JunctionMark {
401 edge: Edge::Right,
402 offset: off,
403 stem,
404 });
405 }
406 }
407 }
408 }
409 cursor += 1; }
411
412 let ids = self.group.child_ids_in_order();
415 for id in ids {
416 if let Some(sp) = self
417 .group
418 .child_mut(id)
419 .and_then(|v| v.as_any_mut())
420 .and_then(|a| a.downcast_mut::<Splitter>())
421 {
422 let ca = sp.group.state().get_bounds().a; let child_origin = Point::new(origin.x + ca.x, origin.y + ca.y);
424 sp.collect_frame_marks(fb, child_origin, out);
425 }
426 }
427 }
428
429 fn divider_at(&self, local: Point) -> Option<usize> {
431 let along = match self.orientation {
432 Orientation::Cols => local.x,
433 Orientation::Rows => local.y,
434 };
435 (0..self.slots.len().saturating_sub(1)).find(|&i| self.divider_axis_pos(i) == Some(along))
436 }
437
438 fn drag_divider_to(&mut self, i: usize, target: i32) {
443 if i + 1 >= self.slots.len() {
444 return;
445 }
446 let sizes = solve(&self.slots, self.content_len());
447 let (a, b) = (i, i + 1);
448 let cur_boundary = self.divider_axis_pos(i).unwrap_or(0);
449 let mut delta = target - cur_boundary; let (size_a, size_b) = (sizes[a], sizes[b]);
451 let max_grow_a = (self.slots[a].max - size_a).max(0);
452 let max_shrink_b = (size_b - self.slots[b].min).max(0);
453 let max_pos = max_grow_a.min(max_shrink_b);
454 let max_shrink_a = (size_a - self.slots[a].min).max(0);
455 let max_grow_b = (self.slots[b].max - size_b).max(0);
456 let max_neg = max_shrink_a.min(max_grow_b);
457 delta = delta.clamp(-max_neg, max_pos);
458 if delta == 0 {
459 return;
460 }
461 let new_a = size_a + delta;
462 let new_b = size_b - delta;
463 let free_a = (new_a - self.slots[a].min).max(0) as f64;
464 let free_b = (new_b - self.slots[b].min).max(0) as f64;
465 let pair_w = self.slots[a].weight + self.slots[b].weight;
466 let free_sum = free_a + free_b;
467 if pair_w > 0.0 && free_sum > 0.0 {
468 self.slots[a].weight = pair_w * free_a / free_sum;
469 self.slots[b].weight = pair_w * free_b / free_sum;
470 }
471 }
472
473 fn request_relayout(&mut self, ctx: &mut Context) {
475 let sizes = solve(&self.slots, self.content_len());
476 let ext = self.group.state().get_extent();
477 let mut cursor = match self.orientation {
478 Orientation::Cols => ext.a.x,
479 Orientation::Rows => ext.a.y,
480 };
481 let ids = self.group.child_ids_in_order();
482 for (i, id) in ids.iter().enumerate() {
483 let size = sizes.get(i).copied().unwrap_or(0);
484 let rect = match self.orientation {
485 Orientation::Cols => Rect::new(cursor, ext.a.y, cursor + size, ext.b.y),
486 Orientation::Rows => Rect::new(ext.a.x, cursor, ext.b.x, cursor + size),
487 };
488 ctx.request_bounds(*id, rect);
489 cursor += size + 1;
490 }
491 }
492
493 fn pane_index(&self, id: ViewId) -> Option<usize> {
497 self.group
498 .child_ids_in_order()
499 .iter()
500 .position(|&c| c == id)
501 }
502
503 pub fn set_constraints(&mut self, id: ViewId, c: Constraints) {
505 if let Some(i) = self.pane_index(id) {
506 self.slots[i] = Slot::from_constraints(c);
507 self.resolve_layout_local();
508 }
509 }
510
511 pub fn set_divider_style(&mut self, i: usize, style: DividerStyle) {
513 self.ensure_divider_len();
514 if i < self.divider_styles.len() {
515 self.divider_styles[i] = style;
516 }
517 }
518
519 pub fn set_default_divider_style(&mut self, style: DividerStyle) {
521 self.default_style = style;
522 }
523
524 pub fn remove(&mut self, id: ViewId) -> bool {
526 if let Some(i) = self.pane_index(id) {
527 self.group.remove_child_by_id(id);
528 self.slots.remove(i);
529 if i < self.divider_styles.len() {
530 self.divider_styles.remove(i);
531 }
532 self.resolve_layout_local();
533 true
534 } else {
535 false
536 }
537 }
538
539 pub fn relax(&mut self, id: ViewId) {
543 let Some(i) = self.pane_index(id) else {
544 return;
545 };
546 let sizes = solve(&self.slots, self.content_len());
547 let cur = sizes.get(i).copied().unwrap_or(0);
548 let others: f64 = self
549 .slots
550 .iter()
551 .enumerate()
552 .filter(|(k, s)| *k != i && s.weight > 0.0)
553 .map(|(_, s)| s.weight)
554 .sum();
555 let free = self.content_len() - self.slots.iter().map(|s| s.min).sum::<i32>();
556 let w = relax_weight(others, cur, free);
557 self.slots[i].min = 0;
558 self.slots[i].max = i32::MAX;
559 self.slots[i].weight = w;
560 self.resolve_layout_local();
561 }
562
563 pub(crate) fn begin_resize_session(&mut self) -> Vec<(ViewId, usize, Orientation)> {
578 self.saved_weights = if self.has_movable_divider() {
583 self.slots.iter().map(|s| s.weight).collect()
584 } else {
585 Vec::new()
586 };
587 self.active_divider = None;
588 let mut out = Vec::new();
589 if let Some(id) = self.state().id() {
590 for i in 0..self.slots.len().saturating_sub(1) {
591 if self.style_of(i).movable() {
592 out.push((id, i, self.orientation));
593 }
594 }
595 }
596 let ids = self.group.child_ids_in_order();
597 for cid in ids {
598 if let Some(sub) = self
599 .group
600 .child_mut(cid)
601 .and_then(|v| v.as_any_mut())
602 .and_then(|a| a.downcast_mut::<Splitter>())
603 {
604 out.extend(sub.begin_resize_session());
605 }
606 }
607 out
608 }
609
610 pub(crate) fn set_active_divider(&mut self, sel: Option<usize>) {
614 self.active_divider = sel;
615 }
616
617 pub(crate) fn nudge_divider(&mut self, index: usize, delta: i32) {
622 if let Some(p) = self.divider_axis_pos(index) {
623 self.drag_divider_to(index, p + delta);
624 }
625 self.resolve_layout_local();
626 }
627
628 pub(crate) fn end_resize_session(&mut self, commit: bool) {
631 if !commit && self.saved_weights.len() == self.slots.len() {
632 for (s, w) in self.slots.iter_mut().zip(&self.saved_weights) {
633 s.weight = *w;
634 }
635 }
636 self.active_divider = None;
637 self.saved_weights.clear();
638 self.resolve_layout_local();
639 }
640
641 pub(crate) fn has_movable_divider(&self) -> bool {
644 (0..self.slots.len().saturating_sub(1)).any(|i| self.style_of(i).movable())
645 }
646
647 fn draw_interior_crossings(&mut self, ctx: &mut DrawCtx) {
664 if self.slots.len() < 2 {
665 return; }
667 let weight = Weight::Single;
668 let ids = self.group.child_ids_in_order();
669 for (p, id) in ids.iter().enumerate() {
670 let info = self.group.child_mut(*id).and_then(|v| {
672 v.as_any_mut()
673 .and_then(|a| a.downcast_mut::<Splitter>())
674 .filter(|sub| sub.orientation != self.orientation)
675 .map(|sub| {
676 let cb = sub.group.state().get_bounds();
677 let csizes = solve(&sub.slots, sub.content_len());
678 let mut pos = Vec::new();
679 let mut c = 0i32;
680 for i in 0..sub.slots.len().saturating_sub(1) {
681 c += csizes.get(i).copied().unwrap_or(0);
682 let full =
683 matches!(sub.style_of(i), DividerStyle::Line) || sub.is_moving(i);
684 if full {
685 pos.push(c);
686 }
687 c += 1;
688 }
689 (cb, pos)
690 })
691 });
692 let Some((cb, perp)) = info else { continue };
693
694 let low = if p > 0 {
695 self.divider_axis_pos(p - 1)
696 } else {
697 None
698 };
699 let high = if p < self.slots.len() - 1 {
700 self.divider_axis_pos(p)
701 } else {
702 None
703 };
704
705 for d in &perp {
706 let (cross_local, branch_low, branch_high) = match self.orientation {
707 Orientation::Cols => {
710 let row = cb.a.y + d;
711 (row, Junction::TeeLeft, Junction::TeeRight)
712 }
713 Orientation::Rows => {
716 let col = cb.a.x + d;
717 (col, Junction::TeeUp, Junction::TeeDown)
718 }
719 };
720 if let Some(ld) = low {
722 let glyph = divider_junction(branch_high, weight, ctx.glyphs());
723 self.put_crossing(ctx, ld, cross_local, glyph);
724 }
725 if let Some(hd) = high {
727 let glyph = divider_junction(branch_low, weight, ctx.glyphs());
728 self.put_crossing(ctx, hd, cross_local, glyph);
729 }
730 }
731 }
732 }
733
734 fn put_crossing(&self, ctx: &mut DrawCtx, axis: i32, cross: i32, glyph: char) {
737 let role = divider_role(false, self.state().state.active);
739 let st = ctx.style(role);
740 let (x, y) = match self.orientation {
741 Orientation::Cols => (axis, cross), Orientation::Rows => (cross, axis), };
744 ctx.put_char(x, y, glyph, st);
745 }
746}
747
748#[crate::delegate(to = group)]
749impl View for Splitter {
750 fn draw(&mut self, ctx: &mut DrawCtx) {
751 self.abs_origin = ctx.origin();
752 self.group.draw(ctx);
753 self.draw_dividers(ctx);
754 if self.joined {
755 self.draw_interior_crossings(ctx);
756 }
757 }
758
759 fn change_bounds(&mut self, bounds: Rect) {
760 self.group.state_mut().set_bounds(bounds);
761 self.resolve_layout_local();
762 }
763
764 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
771 Some(self)
772 }
773
774 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
775 match ev {
776 Event::KeyDown(_) => {
777 self.group.handle_event(ev, ctx);
783 }
784 Event::MouseDown(me) => {
785 let local = me.position; if let Some(i) = self.divider_at(local) {
787 let style = self.style_of(i);
788 let allowed = style.movable();
791 if let (true, Some(id)) = (allowed, self.state().id()) {
792 self.dragging = Some(i);
793 ctx.start_mouse_track(
794 id,
795 self.abs_origin,
796 TrackMask {
797 mouse_move: true,
798 ..Default::default()
799 },
800 );
801 ev.clear();
802 return;
803 }
804 }
805 self.group.handle_event(ev, ctx);
806 }
807 Event::MouseMove(me) if self.dragging.is_some() => {
808 let i = self.dragging.unwrap();
809 let target = match self.orientation {
810 Orientation::Cols => me.position.x,
811 Orientation::Rows => me.position.y,
812 };
813 self.drag_divider_to(i, target);
814 self.request_relayout(ctx);
815 ev.clear();
816 }
817 Event::MouseUp(_) if self.dragging.is_some() => {
818 self.dragging = None;
819 ev.clear();
820 }
821 _ => self.group.handle_event(ev, ctx),
822 }
823 }
824}
825
826#[cfg(test)]
827mod divider_tests {
828 use super::*;
829 use crate::backend::{HeadlessBackend, Renderer};
830 use crate::screen::Buffer;
831 use crate::theme::{Role, Theme};
832 use crate::view::ViewState;
833
834 struct Fill(char, ViewState);
836 impl Fill {
837 fn boxed(ch: char) -> Box<dyn View> {
838 Box::new(Fill(ch, ViewState::new(Rect::new(0, 0, 1, 1))))
839 }
840 }
841 impl View for Fill {
842 fn state(&self) -> &ViewState {
843 &self.1
844 }
845 fn state_mut(&mut self) -> &mut ViewState {
846 &mut self.1
847 }
848 fn draw(&mut self, ctx: &mut DrawCtx) {
849 let b = self.1.get_bounds();
850 let (w, h) = (b.b.x - b.a.x, b.b.y - b.a.y);
851 ctx.fill(Rect::new(0, 0, w, h), self.0, ctx.style(Role::Normal));
852 }
853 }
854
855 fn render_splitter(sp: &mut Splitter, w: u16, h: u16) -> String {
856 let theme = Theme::classic_blue();
857 let (backend, screen) = HeadlessBackend::new(w, h);
858 let mut r = Renderer::new(Box::new(backend));
859 r.render(|buf: &mut Buffer| {
860 let bounds = sp.state().get_bounds();
861 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
862 sp.draw(&mut dc);
863 });
864 screen.snapshot()
865 }
866
867 #[test]
868 fn splitter_grows_with_owner_by_default() {
869 let sp = Splitter::cols();
870 let gm = sp.state().grow_mode;
871 assert!(gm.hi_x && gm.hi_y, "splitter fills/grows by default");
872 assert!(!gm.lo_x && !gm.lo_y, "top-left stays (keeps any inset)");
873 let sp2 = Splitter::rows();
875 assert!(sp2.state().grow_mode.hi_x && sp2.state().grow_mode.hi_y);
876 }
877
878 #[test]
879 fn with_grow_mode_can_disable_growth() {
880 let sp = Splitter::cols().with_grow_mode(GrowMode::default());
881 let gm = sp.state().grow_mode;
882 assert!(
883 !gm.hi_x && !gm.hi_y && !gm.lo_x && !gm.lo_y,
884 "fixed-size opt-out"
885 );
886 }
887
888 #[test]
889 fn draggability_matrix() {
890 assert!(DividerStyle::Line.draggable_live());
891 assert!(DividerStyle::Handle.draggable_live());
892 assert!(!DividerStyle::Hidden.draggable_live());
893 assert!(!DividerStyle::Locked.draggable_live());
894
895 assert!(DividerStyle::Hidden.movable());
896 assert!(!DividerStyle::Locked.movable());
897 }
898
899 struct Leaf(ViewState);
901 impl Leaf {
902 fn boxed() -> Box<dyn View> {
903 Box::new(Leaf(ViewState::new(Rect::new(0, 0, 1, 1))))
904 }
905 }
906 impl View for Leaf {
907 fn state(&self) -> &ViewState {
908 &self.0
909 }
910 fn state_mut(&mut self) -> &mut ViewState {
911 &mut self.0
912 }
913 fn draw(&mut self, _ctx: &mut DrawCtx) {}
914 }
915
916 fn three_pane_cols() -> Splitter {
920 let mut sp = Splitter::cols();
921 sp.change_bounds(Rect::new(0, 0, 30, 5));
922 sp.insert(Fill::boxed('A'), Constraints::flex());
923 sp.insert(Fill::boxed('B'), Constraints::flex());
924 sp.insert(Fill::boxed('C'), Constraints::flex());
925 sp.state_mut().id = Some(ViewId::next());
927 sp
928 }
929
930 #[test]
931 fn begin_resize_session_lists_movable_dividers_and_snapshots() {
932 let mut sp = three_pane_cols(); let targets = sp.begin_resize_session();
935 let id = sp.state().id().unwrap();
936 assert_eq!(
937 targets,
938 vec![(id, 0, Orientation::Cols), (id, 1, Orientation::Cols)],
939 "movable dividers enumerated in axis order with this splitter's id"
940 );
941 assert_eq!(
942 sp.active_divider, None,
943 "begin does NOT auto-select a divider"
944 );
945 assert_eq!(
946 sp.saved_weights.len(),
947 sp.slots.len(),
948 "weights snapshotted"
949 );
950 }
951
952 #[test]
953 fn nudge_divider_moves_then_end_commit_keeps_position() {
954 let mut sp = three_pane_cols();
955 sp.begin_resize_session();
956 let before = sp.divider_axis_pos(0).unwrap();
957 sp.nudge_divider(0, 1);
958 let after = sp.divider_axis_pos(0).unwrap();
959 assert_eq!(
960 after,
961 before + 1,
962 "nudge moves the divider one cell along the axis"
963 );
964 sp.end_resize_session(true); assert_eq!(
966 sp.divider_axis_pos(0).unwrap(),
967 after,
968 "commit keeps the new position"
969 );
970 assert!(sp.saved_weights.is_empty(), "session ended");
971 assert_eq!(sp.active_divider, None);
972 }
973
974 #[test]
975 fn end_resize_session_cancel_restores_weights() {
976 let mut sp = three_pane_cols();
977 sp.begin_resize_session();
978 let before = sp.divider_axis_pos(0).unwrap();
979 sp.nudge_divider(0, 2);
980 assert_ne!(sp.divider_axis_pos(0).unwrap(), before);
981 sp.end_resize_session(false); assert_eq!(
983 sp.divider_axis_pos(0).unwrap(),
984 before,
985 "cancel restores pre-session position"
986 );
987 }
988
989 #[test]
990 fn set_active_divider_drives_active_field() {
991 let mut sp = three_pane_cols();
992 sp.begin_resize_session();
993 sp.set_active_divider(Some(1));
994 assert_eq!(sp.active_divider, Some(1));
995 sp.set_active_divider(None);
996 assert_eq!(sp.active_divider, None);
997 }
998
999 #[test]
1000 fn divider_role_rule() {
1001 use crate::theme::Role;
1002 assert_eq!(divider_role(true, true), Role::FrameDragging);
1004 assert_eq!(divider_role(true, false), Role::FrameDragging);
1005 assert_eq!(divider_role(false, true), Role::FrameActive);
1007 assert_eq!(divider_role(false, false), Role::FramePassive);
1008 }
1009
1010 #[test]
1011 fn divider_inactive_is_single_line_passive() {
1012 let mut sp = three_pane_cols(); let snap = render_splitter(&mut sp, 30, 5);
1014 insta::assert_snapshot!("divider_inactive", snap);
1015 }
1016
1017 #[test]
1018 fn divider_dragging_highlight_on_mouse() {
1019 let mut sp = three_pane_cols();
1020 sp.dragging = Some(0); let snap = render_splitter(&mut sp, 30, 5);
1022 insta::assert_snapshot!("divider_dragging_highlight_on_mouse", snap);
1023 }
1024
1025 #[test]
1026 fn divider_active_is_single_line_active() {
1027 let mut sp = three_pane_cols();
1028 sp.state_mut().state.active = true; let snap = render_splitter(&mut sp, 30, 5);
1030 insta::assert_snapshot!("divider_active", snap);
1031 }
1032
1033 #[test]
1034 fn begin_resize_session_recurses_into_sub_splitter() {
1035 let sub = Splitter::rows()
1039 .pane(Leaf::boxed(), Constraints::flex())
1040 .pane(Leaf::boxed(), Constraints::flex());
1041 let mut outer = Splitter::cols();
1042 outer.change_bounds(Rect::new(0, 0, 30, 10));
1043 outer.insert(Leaf::boxed(), Constraints::flex());
1044 let sub_id = outer.insert(Box::new(sub), Constraints::flex());
1046 outer.state_mut().id = Some(ViewId::next());
1048 let outer_id = outer.state().id().unwrap();
1049
1050 let targets = outer.begin_resize_session();
1051 assert_eq!(
1052 targets,
1053 vec![
1054 (outer_id, 0, Orientation::Cols), (sub_id, 0, Orientation::Rows), ],
1057 "depth-first: outer's dividers (outer id/orientation) then the sub's (sub id/orientation)"
1058 );
1059
1060 let sub = outer
1062 .group
1063 .child_mut(sub_id)
1064 .and_then(|v| v.as_any_mut())
1065 .and_then(|a| a.downcast_mut::<Splitter>())
1066 .expect("sub pane is a Splitter");
1067 assert_eq!(
1068 sub.saved_weights.len(),
1069 sub.slots.len(),
1070 "sub-splitter's weights snapshotted by the recursive begin"
1071 );
1072 }
1073}
1074
1075#[cfg(test)]
1076mod view_tests {
1077 use super::*;
1078 use crate::backend::{HeadlessBackend, Renderer};
1079 use crate::screen::Buffer;
1080 use crate::theme::{Role, Theme};
1081 use crate::view::ViewState;
1082
1083 struct Fill(char, ViewState);
1084 impl Fill {
1085 fn boxed(ch: char) -> Box<dyn View> {
1086 Box::new(Fill(ch, ViewState::new(Rect::new(0, 0, 1, 1))))
1087 }
1088 }
1089 impl View for Fill {
1090 fn state(&self) -> &ViewState {
1091 &self.1
1092 }
1093 fn state_mut(&mut self) -> &mut ViewState {
1094 &mut self.1
1095 }
1096 fn draw(&mut self, ctx: &mut DrawCtx) {
1097 let b = self.1.get_bounds();
1100 let (w, h) = (b.b.x - b.a.x, b.b.y - b.a.y);
1101 ctx.fill(Rect::new(0, 0, w, h), self.0, ctx.style(Role::Normal));
1102 }
1103 }
1104
1105 fn render_buf(sp: &mut Splitter, w: u16, h: u16) -> crate::screen::Buffer {
1106 let theme = crate::theme::Theme::classic_blue();
1107 let mut buf = crate::screen::Buffer::new(w, h);
1108 let bounds = sp.state().get_bounds();
1109 let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
1110 sp.draw(&mut dc);
1111 buf
1112 }
1113
1114 fn render(sp: &mut Splitter, w: u16, h: u16) -> String {
1115 let theme = Theme::classic_blue();
1116 let (backend, screen) = HeadlessBackend::new(w, h);
1117 let mut r = Renderer::new(Box::new(backend));
1118 r.render(|buf: &mut Buffer| {
1119 let bounds = sp.state().get_bounds();
1120 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1121 sp.draw(&mut dc);
1122 });
1123 screen.snapshot()
1124 }
1125
1126 #[test]
1127 fn three_equal_columns_render() {
1128 let mut sp = Splitter::cols();
1129 sp.change_bounds(Rect::new(0, 0, 32, 4)); sp.insert(Fill::boxed('A'), Constraints::flex());
1131 sp.insert(Fill::boxed('B'), Constraints::flex());
1132 sp.insert(Fill::boxed('C'), Constraints::flex());
1133 insta::assert_snapshot!(render(&mut sp, 32, 4));
1134 }
1135
1136 #[test]
1137 fn dividers_line_style() {
1138 let mut sp = Splitter::cols(); sp.change_bounds(Rect::new(0, 0, 13, 3)); sp.insert(Fill::boxed('A'), Constraints::flex());
1141 sp.insert(Fill::boxed('B'), Constraints::flex());
1142 insta::assert_snapshot!(render(&mut sp, 13, 3)); }
1144
1145 #[test]
1146 fn dividers_hidden_style_is_seamless() {
1147 let mut sp = Splitter::cols();
1148 sp.default_style = DividerStyle::Hidden;
1149 sp.change_bounds(Rect::new(0, 0, 13, 3));
1150 sp.insert(Fill::boxed('A'), Constraints::flex());
1151 sp.insert(Fill::boxed('B'), Constraints::flex());
1152 insta::assert_snapshot!(render(&mut sp, 13, 3)); }
1154
1155 #[test]
1156 fn dividers_rows_orientation() {
1157 let mut sp = Splitter::rows();
1158 sp.change_bounds(Rect::new(0, 0, 6, 7)); sp.insert(Fill::boxed('A'), Constraints::flex());
1160 sp.insert(Fill::boxed('B'), Constraints::flex());
1161 insta::assert_snapshot!(render(&mut sp, 6, 7)); }
1163
1164 #[test]
1165 fn builder_builds_same_layout_as_imperative() {
1166 let mut imperative = Splitter::cols();
1167 imperative.change_bounds(Rect::new(0, 0, 13, 2));
1168 imperative.insert(Fill::boxed('A'), Constraints::flex());
1169 imperative.insert(Fill::boxed('B'), Constraints::flex());
1170
1171 let mut built = Splitter::cols()
1172 .pane(Fill::boxed('A'), Constraints::flex())
1173 .pane(Fill::boxed('B'), Constraints::flex());
1174 built.change_bounds(Rect::new(0, 0, 13, 2));
1175
1176 assert_eq!(render(&mut imperative, 13, 2), render(&mut built, 13, 2));
1177 }
1178
1179 #[test]
1180 fn per_divider_override_renders() {
1181 let mut sp = Splitter::cols()
1182 .default_divider(DividerStyle::Hidden)
1183 .pane(Fill::boxed('A'), Constraints::flex())
1184 .pane(Fill::boxed('B'), Constraints::flex())
1185 .pane(Fill::boxed('C'), Constraints::flex())
1186 .divider(1, DividerStyle::Line); sp.change_bounds(Rect::new(0, 0, 14, 1)); insta::assert_snapshot!(render(&mut sp, 14, 1)); }
1190
1191 #[test]
1192 fn drag_repartitions_two_neighbors_sum_preserved() {
1193 let mut sp = Splitter::cols();
1194 sp.change_bounds(Rect::new(0, 0, 31, 1)); sp.insert(Fill::boxed('A'), Constraints::flex());
1196 sp.insert(Fill::boxed('B'), Constraints::flex());
1197 sp.insert(Fill::boxed('C'), Constraints::flex());
1198 let w_before_c = sp.slots[2].weight;
1199 let pair_before = sp.slots[0].weight + sp.slots[1].weight;
1200 let d0 = sp.divider_axis_pos(0).unwrap();
1201 sp.drag_divider_to(0, d0 + 3);
1202 assert!(
1203 (sp.slots[2].weight - w_before_c).abs() < 1e-9,
1204 "pane C weight untouched (locality)"
1205 );
1206 assert!(
1207 (sp.slots[0].weight + sp.slots[1].weight - pair_before).abs() < 1e-9,
1208 "pair sum preserved"
1209 );
1210 let sizes = super::layout::solve(&sp.slots, sp.content_len());
1211 assert!(sizes[0] > sizes[1], "pane 0 grew, pane 1 shrank");
1212 }
1213
1214 #[test]
1215 fn drag_against_fixed_neighbor_is_a_wall() {
1216 let mut sp = Splitter::cols();
1217 sp.change_bounds(Rect::new(0, 0, 31, 1));
1218 sp.insert(Fill::boxed('A'), Constraints::fixed(10)); sp.insert(Fill::boxed('B'), Constraints::flex());
1220 let before = super::layout::solve(&sp.slots, sp.content_len());
1221 let d0 = sp.divider_axis_pos(0).unwrap();
1222 sp.drag_divider_to(0, d0 + 5); let after = super::layout::solve(&sp.slots, sp.content_len());
1224 assert_eq!(
1225 before, after,
1226 "fixed pane is immovable — divider does not move"
1227 );
1228 }
1229
1230 #[test]
1231 fn relax_does_not_move_dividers() {
1232 let mut sp = Splitter::cols();
1233 sp.change_bounds(Rect::new(0, 0, 41, 1)); let a = sp.insert(Fill::boxed('A'), Constraints::fixed(12));
1235 sp.insert(Fill::boxed('B'), Constraints::flex());
1236 sp.insert(Fill::boxed('C'), Constraints::flex());
1237 let before = solve(&sp.slots, sp.content_len());
1238 sp.relax(a);
1239 let after = solve(&sp.slots, sp.content_len());
1240 assert_eq!(before, after, "relax keeps every pane the same size");
1241 assert!(
1242 sp.slots[0].min != sp.slots[0].max,
1243 "pane A is now draggable (not fixed)"
1244 );
1245 }
1246
1247 #[test]
1248 fn remove_pane_resolves_remaining() {
1249 let mut sp = Splitter::cols();
1250 sp.change_bounds(Rect::new(0, 0, 21, 1)); let a = sp.insert(Fill::boxed('A'), Constraints::flex());
1252 sp.insert(Fill::boxed('B'), Constraints::flex());
1253 sp.insert(Fill::boxed('C'), Constraints::flex());
1254 assert!(sp.remove(a));
1255 let sizes = solve(&sp.slots, sp.content_len());
1256 assert_eq!(sizes.len(), 2);
1257 assert_eq!(sizes.iter().sum::<i32>(), sp.content_len());
1258 }
1259
1260 #[test]
1261 fn frame_marks_two_pane_cols_abut_top_and_bottom() {
1262 use crate::junction::{Edge, Weight};
1263 let frame_bounds = Rect::new(0, 0, 13, 5);
1264 let mut sp = Splitter::cols();
1265 sp.set_joined(true);
1266 sp.change_bounds(Rect::new(1, 1, 12, 4));
1267 sp.insert(Fill::boxed('A'), Constraints::flex());
1268 sp.insert(Fill::boxed('B'), Constraints::flex());
1269 let marks = sp.frame_junction_marks(frame_bounds);
1270 assert_eq!(marks.len(), 2, "one top + one bottom mark");
1271 assert!(marks.contains(&crate::junction::JunctionMark {
1272 edge: Edge::Top,
1273 offset: 6,
1274 stem: Weight::Single
1275 }));
1276 assert!(marks.contains(&crate::junction::JunctionMark {
1277 edge: Edge::Bottom,
1278 offset: 6,
1279 stem: Weight::Single
1280 }));
1281 }
1282
1283 #[test]
1284 fn frame_marks_handle_divider_emits_nothing() {
1285 let frame_bounds = Rect::new(0, 0, 13, 5);
1286 let mut sp = Splitter::cols()
1287 .default_divider(DividerStyle::Handle)
1288 .joined();
1289 sp.change_bounds(Rect::new(1, 1, 12, 4));
1290 sp.insert(Fill::boxed('A'), Constraints::flex());
1291 sp.insert(Fill::boxed('B'), Constraints::flex());
1292 assert!(sp.frame_junction_marks(frame_bounds).is_empty());
1294 }
1295
1296 #[test]
1297 fn frame_marks_inset_splitter_emits_nothing() {
1298 let frame_bounds = Rect::new(0, 0, 13, 7);
1299 let mut sp = Splitter::cols().joined();
1300 sp.change_bounds(Rect::new(2, 2, 11, 5)); sp.insert(Fill::boxed('A'), Constraints::flex());
1302 sp.insert(Fill::boxed('B'), Constraints::flex());
1303 assert!(sp.frame_junction_marks(frame_bounds).is_empty());
1305 }
1306
1307 #[test]
1308 fn frame_marks_empty_when_not_joined() {
1309 let frame_bounds = Rect::new(0, 0, 13, 5);
1310 let mut sp = Splitter::cols(); sp.change_bounds(Rect::new(1, 1, 12, 4));
1312 sp.insert(Fill::boxed('A'), Constraints::flex());
1313 sp.insert(Fill::boxed('B'), Constraints::flex());
1314 assert!(
1315 sp.frame_junction_marks(frame_bounds).is_empty(),
1316 "no marks unless joined"
1317 );
1318 }
1319
1320 #[test]
1321 fn frame_marks_nested_grid_inner_divider_hits_right_frame() {
1322 use crate::junction::Edge;
1323 let frame_bounds = Rect::new(0, 0, 22, 7);
1324 let inner = Splitter::rows()
1325 .pane(Fill::boxed('L'), Constraints::flex())
1326 .pane(Fill::boxed('F'), Constraints::flex());
1327 let mut outer = Splitter::cols();
1328 outer.set_joined(true); outer.change_bounds(Rect::new(1, 1, 21, 6));
1330 outer.insert(Fill::boxed('T'), Constraints::fixed(8));
1331 outer.insert(Box::new(inner), Constraints::flex());
1332 let marks = outer.frame_junction_marks(frame_bounds);
1333 assert_eq!(
1334 marks.len(),
1335 3,
1336 "outer top+bottom + inner right, got {marks:?}"
1337 );
1338 assert!(
1339 marks.iter().any(|m| m.edge == Edge::Right && m.offset == 3),
1340 "inner horizontal divider abuts the right frame edge at offset 3, got {marks:?}"
1341 );
1342 assert_eq!(
1343 marks.iter().filter(|m| m.edge == Edge::Top).count(),
1344 1,
1345 "outer vertical divider abuts the top edge once"
1346 );
1347 assert!(
1348 !marks.iter().any(|m| m.edge == Edge::Left),
1349 "no spurious left mark, got {marks:?}"
1350 );
1351 }
1352
1353 #[test]
1354 fn interior_crossing_grid_renders_left_tee() {
1355 let inner = Splitter::rows()
1362 .pane(Fill::boxed('L'), Constraints::flex())
1363 .pane(Fill::boxed('F'), Constraints::flex());
1364 let mut outer = Splitter::cols();
1365 outer.set_joined(true); outer.change_bounds(Rect::new(0, 0, 20, 7));
1367 outer.insert(Fill::boxed('T'), Constraints::fixed(6));
1368 outer.insert(Box::new(inner), Constraints::flex());
1369 insta::assert_snapshot!(render(&mut outer, 20, 7));
1370 }
1371
1372 #[test]
1373 fn interior_crossings_absent_when_not_joined() {
1374 let inner = Splitter::rows()
1377 .pane(Fill::boxed('L'), Constraints::flex())
1378 .pane(Fill::boxed('F'), Constraints::flex());
1379 let mut outer = Splitter::cols(); outer.change_bounds(Rect::new(0, 0, 20, 7));
1381 outer.insert(Fill::boxed('T'), Constraints::fixed(6));
1382 outer.insert(Box::new(inner), Constraints::flex());
1383 let out = render(&mut outer, 20, 7);
1384 assert!(!out.contains('├'), "no interior tee unless joined:\n{out}");
1385 }
1386
1387 #[test]
1388 fn inset_splitter_panes_fill_from_origin() {
1389 let mut sp = Splitter::cols();
1394 sp.change_bounds(Rect::new(3, 2, 16, 5)); sp.insert(Fill::boxed('A'), Constraints::flex());
1396 sp.insert(Fill::boxed('B'), Constraints::flex());
1397 let buf = render_buf(&mut sp, 16, 5);
1398 assert_eq!(
1401 buf.get(3, 3).symbol(),
1402 "A",
1403 "pane A must start at the splitter origin column, not be shifted by it"
1404 );
1405 assert_ne!(
1407 buf.get(3, 3).symbol(),
1408 " ",
1409 "no blank column at the splitter origin"
1410 );
1411 }
1412
1413 #[test]
1414 fn splitter_downcasts_through_as_any_mut() {
1415 let mut sp = Splitter::cols();
1416 sp.change_bounds(Rect::new(0, 0, 13, 3));
1417 sp.insert(Fill::boxed('A'), Constraints::flex());
1418 sp.insert(Fill::boxed('B'), Constraints::flex());
1419 let resolved = (&mut sp as &mut dyn View)
1420 .as_any_mut()
1421 .and_then(|a| a.downcast_mut::<Splitter>())
1422 .is_some();
1423 assert!(resolved, "Splitter must override as_any_mut → Some(self)");
1424 }
1425}