1pub mod widgets;
26
27use ab_glyph::{Font, ScaleFont};
28use serde::{Deserialize, Serialize};
29
30pub type Rgba = [f32; 4];
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
37pub struct Rect {
38 pub x: f32,
39 pub y: f32,
40 pub w: f32,
41 pub h: f32,
42}
43
44impl Rect {
45 pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
46 Self { x, y, w, h }
47 }
48 pub fn right(&self) -> f32 {
49 self.x + self.w
50 }
51 pub fn bottom(&self) -> f32 {
52 self.y + self.h
53 }
54 pub fn contains(&self, px: f32, py: f32) -> bool {
55 px >= self.x && px < self.right() && py >= self.y && py < self.bottom()
56 }
57 pub fn intersect(&self, o: &Rect) -> Rect {
59 let x = self.x.max(o.x);
60 let y = self.y.max(o.y);
61 let r = self.right().min(o.right());
62 let b = self.bottom().min(o.bottom());
63 if r <= x || b <= y {
64 Rect::new(x, y, 0.0, 0.0)
65 } else {
66 Rect::new(x, y, r - x, b - y)
67 }
68 }
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
77pub struct ThemeColors {
78 pub background: Rgba,
79 pub panel: Rgba,
80 pub header: Rgba,
81 pub border: Rgba,
82 pub text: Rgba,
83 pub text_dim: Rgba,
84 pub accent: Rgba,
85 pub accent_hover: Rgba,
86 pub hover: Rgba,
87 pub select: Rgba,
88 pub input: Rgba,
89 pub viewport_bg: Rgba,
90}
91
92impl Default for ThemeColors {
93 fn default() -> Self {
96 Self {
97 background: [0.086, 0.080, 0.074, 1.0],
98 panel: [0.117, 0.110, 0.102, 1.0],
99 header: [0.145, 0.137, 0.127, 1.0],
100 border: [0.200, 0.190, 0.175, 1.0],
101 text: [0.870, 0.850, 0.820, 1.0],
102 text_dim: [0.550, 0.530, 0.500, 1.0],
103 accent: [0.900, 0.350, 0.150, 1.0],
104 accent_hover: [1.000, 0.450, 0.220, 1.0],
105 hover: [0.160, 0.150, 0.140, 1.0],
106 select: [0.320, 0.160, 0.090, 1.0],
107 input: [0.070, 0.065, 0.060, 1.0],
108 viewport_bg: [0.020, 0.020, 0.025, 1.0],
109 }
110 }
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
116pub struct ThemeMetrics {
117 pub row_h: f32,
118 pub tab_h: f32,
119 pub pad: f32,
120 pub corner: f32,
121 pub splitter: f32,
122 pub font_px: f32,
123 pub font_px_small: f32,
124 pub icon_px: f32,
125}
126
127impl Default for ThemeMetrics {
128 fn default() -> Self {
129 Self {
130 row_h: 24.0,
131 tab_h: 26.0,
132 pad: 6.0,
133 corner: 3.0,
134 splitter: 4.0,
135 font_px: 15.0,
136 font_px_small: 12.0,
137 icon_px: 16.0,
138 }
139 }
140}
141
142#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
146pub struct Theme {
147 pub name: String,
148 pub colors: ThemeColors,
149 pub metrics: ThemeMetrics,
150 #[serde(default)]
151 pub labels: std::collections::BTreeMap<String, String>,
152}
153
154impl Default for Theme {
155 fn default() -> Self {
156 Self {
157 name: "default".into(),
158 colors: ThemeColors::default(),
159 metrics: ThemeMetrics::default(),
160 labels: std::collections::BTreeMap::new(),
161 }
162 }
163}
164
165impl Theme {
166 pub fn label<'a>(&'a self, id: &'a str) -> &'a str {
169 self.labels.get(id).map(String::as_str).unwrap_or(id)
170 }
171}
172
173#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180pub enum DockNode {
181 Split {
184 vertical: bool,
185 ratio: f32,
186 first: Box<DockNode>,
187 second: Box<DockNode>,
188 },
189 Tabs { active: usize, panels: Vec<String> },
191 Leaf { panel: String },
193}
194
195#[derive(Clone, Debug, PartialEq)]
198pub struct PanelPlacement {
199 pub panel: String,
200 pub rect: Rect,
201 pub tabs: Vec<(String, Rect)>,
202}
203
204pub fn dock_layout(node: &DockNode, area: Rect, tab_h: f32, splitter: f32) -> Vec<PanelPlacement> {
208 let mut out = Vec::new();
209 place(node, area, tab_h, splitter, &mut out);
210 out
211}
212
213fn place(node: &DockNode, area: Rect, tab_h: f32, sp: f32, out: &mut Vec<PanelPlacement>) {
214 match node {
215 DockNode::Leaf { panel } => out.push(PanelPlacement {
216 panel: panel.clone(),
217 rect: area,
218 tabs: Vec::new(),
219 }),
220 DockNode::Tabs { active, panels } => {
221 if panels.is_empty() {
222 return;
223 }
224 let tw = area.w / panels.len() as f32;
225 let tabs: Vec<(String, Rect)> = panels
226 .iter()
227 .enumerate()
228 .map(|(i, p)| {
229 (
230 p.clone(),
231 Rect::new(area.x + i as f32 * tw, area.y, tw, tab_h),
232 )
233 })
234 .collect();
235 let body = Rect::new(area.x, area.y + tab_h, area.w, (area.h - tab_h).max(0.0));
236 let idx = (*active).min(panels.len() - 1);
238 out.push(PanelPlacement {
239 panel: panels[idx].clone(),
240 rect: body,
241 tabs,
242 });
243 }
244 DockNode::Split {
245 vertical,
246 ratio,
247 first,
248 second,
249 } => {
250 let r = ratio.clamp(0.05, 0.95);
251 let (fa, sa) = if *vertical {
252 let h1 = (area.h * r - sp * 0.5).max(0.0);
253 let y2 = area.y + h1 + sp;
254 (
255 Rect::new(area.x, area.y, area.w, h1),
256 Rect::new(area.x, y2, area.w, (area.bottom() - y2).max(0.0)),
257 )
258 } else {
259 let w1 = (area.w * r - sp * 0.5).max(0.0);
260 let x2 = area.x + w1 + sp;
261 (
262 Rect::new(area.x, area.y, w1, area.h),
263 Rect::new(x2, area.y, (area.right() - x2).max(0.0), area.h),
264 )
265 };
266 place(first, fa, tab_h, sp, out);
267 place(second, sa, tab_h, sp, out);
268 }
269 }
270}
271
272#[derive(Clone, Debug, PartialEq)]
280pub struct SplitHit {
281 pub path: Vec<usize>,
282 pub grab: Rect,
283 pub track: Rect,
284 pub vertical: bool,
285}
286
287pub fn dock_splitters(node: &DockNode, area: Rect, tab_h: f32, sp: f32) -> Vec<SplitHit> {
291 let mut out = Vec::new();
292 splitters(node, area, tab_h, sp, &mut Vec::new(), &mut out);
293 out
294}
295
296#[allow(clippy::only_used_in_recursion)]
300fn splitters(
301 node: &DockNode,
302 area: Rect,
303 tab_h: f32,
304 sp: f32,
305 path: &mut Vec<usize>,
306 out: &mut Vec<SplitHit>,
307) {
308 if let DockNode::Split {
309 vertical,
310 ratio,
311 first,
312 second,
313 } = node
314 {
315 let r = ratio.clamp(0.05, 0.95);
316 let (fa, sa, band) = if *vertical {
317 let h1 = (area.h * r - sp * 0.5).max(0.0);
318 let y2 = area.y + h1 + sp;
319 (
320 Rect::new(area.x, area.y, area.w, h1),
321 Rect::new(area.x, y2, area.w, (area.bottom() - y2).max(0.0)),
322 Rect::new(area.x, area.y + h1, area.w, sp),
323 )
324 } else {
325 let w1 = (area.w * r - sp * 0.5).max(0.0);
326 let x2 = area.x + w1 + sp;
327 (
328 Rect::new(area.x, area.y, w1, area.h),
329 Rect::new(x2, area.y, (area.right() - x2).max(0.0), area.h),
330 Rect::new(area.x + w1, area.y, sp, area.h),
331 )
332 };
333 let mut grab = band;
334 if *vertical && grab.h < 6.0 {
335 grab.y -= (6.0 - grab.h) * 0.5;
336 grab.h = 6.0;
337 }
338 if !*vertical && grab.w < 6.0 {
339 grab.x -= (6.0 - grab.w) * 0.5;
340 grab.w = 6.0;
341 }
342 out.push(SplitHit {
343 path: path.clone(),
344 grab,
345 track: area,
346 vertical: *vertical,
347 });
348 path.push(0);
349 splitters(first, fa, tab_h, sp, path, out);
350 path.pop();
351 path.push(1);
352 splitters(second, sa, tab_h, sp, path, out);
353 path.pop();
354 }
355}
356
357pub fn dock_set_ratio(node: &mut DockNode, path: &[usize], ratio: f32) -> bool {
361 let mut cur = node;
362 for &step in path {
363 cur = match cur {
364 DockNode::Split { first, second, .. } => {
365 if step == 0 {
366 &mut **first
367 } else {
368 &mut **second
369 }
370 }
371 _ => return false,
372 };
373 }
374 match cur {
375 DockNode::Split { ratio: rr, .. } => {
376 *rr = ratio.clamp(0.05, 0.95);
377 true
378 }
379 _ => false,
380 }
381}
382
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum DockEdge {
387 Center,
388 Left,
389 Right,
390 Top,
391 Bottom,
392}
393
394pub fn dock_contains(node: &DockNode, panel: &str) -> bool {
396 match node {
397 DockNode::Leaf { panel: p } => p == panel,
398 DockNode::Tabs { panels, .. } => panels.iter().any(|p| p == panel),
399 DockNode::Split { first, second, .. } => {
400 dock_contains(first, panel) || dock_contains(second, panel)
401 }
402 }
403}
404
405pub fn dock_panel_count(node: &DockNode) -> usize {
407 match node {
408 DockNode::Leaf { .. } => 1,
409 DockNode::Tabs { panels, .. } => panels.len(),
410 DockNode::Split { first, second, .. } => dock_panel_count(first) + dock_panel_count(second),
411 }
412}
413
414pub fn dock_take(node: &mut DockNode, panel: &str) -> bool {
420 if !dock_contains(node, panel) || dock_panel_count(node) <= 1 {
421 return false;
422 }
423 match take_rec(node, panel) {
424 Cut::Miss => false,
425 Cut::Found => true,
426 Cut::Replace(None) => false, Cut::Replace(Some(rep)) => {
428 *node = rep;
429 true
430 }
431 }
432}
433
434enum Cut {
435 Miss,
437 Found,
439 Replace(Option<DockNode>),
441}
442
443fn take_rec(node: &mut DockNode, panel: &str) -> Cut {
444 match node {
445 DockNode::Leaf { panel: p } if p == panel => Cut::Replace(None),
446 DockNode::Tabs { active, panels } => match panels.iter().position(|x| x == panel) {
447 None => Cut::Miss,
448 Some(i) => {
449 panels.remove(i);
450 if panels.is_empty() {
451 Cut::Replace(None)
452 } else if panels.len() == 1 {
453 Cut::Replace(Some(DockNode::Leaf {
454 panel: panels.remove(0),
455 }))
456 } else {
457 *active = (*active).min(panels.len() - 1);
458 Cut::Found
459 }
460 }
461 },
462 DockNode::Split { first, second, .. } => {
463 match take_rec(first, panel) {
464 Cut::Miss => {}
465 Cut::Found => return Cut::Found,
466 Cut::Replace(Some(n)) => {
467 **first = n;
468 return Cut::Found;
469 }
470 Cut::Replace(None) => return Cut::Replace(Some(*second.clone())),
472 }
473 match take_rec(second, panel) {
474 Cut::Miss => Cut::Miss,
475 Cut::Found => Cut::Found,
476 Cut::Replace(Some(n)) => {
477 **second = n;
478 Cut::Found
479 }
480 Cut::Replace(None) => Cut::Replace(Some(*first.clone())),
481 }
482 }
483 _ => Cut::Miss,
484 }
485}
486
487pub fn dock_put(node: &mut DockNode, panel: &str, target: &str, edge: DockEdge) -> bool {
493 if panel == target || dock_contains(node, panel) || !dock_contains(node, target) {
494 return false;
495 }
496 put_rec(node, panel, target, edge)
497}
498
499fn split_around(sub: DockNode, panel: &str, edge: DockEdge) -> DockNode {
500 let leaf = DockNode::Leaf {
501 panel: panel.to_string(),
502 };
503 let (vertical, first, second) = match edge {
504 DockEdge::Left => (false, leaf, sub),
505 DockEdge::Right => (false, sub, leaf),
506 DockEdge::Top => (true, leaf, sub),
507 DockEdge::Bottom => (true, sub, leaf),
508 DockEdge::Center => unreachable!("Center hat keinen Split-Zweig"),
509 };
510 DockNode::Split {
511 vertical,
512 ratio: 0.5,
513 first: Box::new(first),
514 second: Box::new(second),
515 }
516}
517
518impl DockNode {
519 fn tabs_group(&mut self) -> Option<&mut Vec<String>> {
521 match self {
522 DockNode::Tabs { panels, .. } => Some(panels),
523 _ => None,
524 }
525 }
526
527 fn leaf_panel(&self) -> Option<&str> {
529 match self {
530 DockNode::Leaf { panel } => Some(panel),
531 _ => None,
532 }
533 }
534}
535
536fn put_rec(node: &mut DockNode, panel: &str, target: &str, edge: DockEdge) -> bool {
537 if let Some(panels) = node.tabs_group() {
539 if let Some(at) = panels.iter().position(|p| p == target) {
540 match edge {
541 DockEdge::Center => {
542 panels.insert(at + 1, panel.to_string());
543 if let DockNode::Tabs { active, .. } = node {
544 *active = at + 1;
545 }
546 return true;
547 }
548 e => {
549 let sub = std::mem::replace(
550 node,
551 DockNode::Leaf {
552 panel: String::new(),
553 },
554 );
555 *node = split_around(sub, panel, e);
556 return true;
557 }
558 }
559 }
560 }
561 if node.leaf_panel() == Some(target) {
563 let sub = std::mem::replace(
564 node,
565 DockNode::Leaf {
566 panel: String::new(),
567 },
568 );
569 *node = match edge {
570 DockEdge::Center => DockNode::Tabs {
571 active: 1,
572 panels: vec![target.to_string(), panel.to_string()],
573 },
574 e => split_around(sub, panel, e),
575 };
576 return true;
577 }
578 if let DockNode::Split { first, second, .. } = node {
579 if dock_contains(first, target) {
580 return put_rec(first, panel, target, edge);
581 }
582 return put_rec(second, panel, target, edge);
583 }
584 false
585}
586
587#[derive(Clone, Copy, Debug, PartialEq)]
600pub struct UiVertex {
601 pub pos: [f32; 2],
602 pub uv: [f32; 2],
603 pub color: Rgba,
604 pub rect: [f32; 4],
606 pub span: [f32; 4],
608}
609
610fn uv_span(uv: Rect) -> [f32; 4] {
615 [uv.x, uv.y, uv.right() - uv.x, uv.bottom() - uv.y]
616}
617
618#[derive(Clone, Debug, PartialEq)]
621pub struct DrawCmd {
622 pub clip: Rect,
623 pub textured: bool,
624 pub vertices: Vec<UiVertex>,
625}
626
627#[derive(Clone, Debug, Default)]
631pub struct DrawList {
632 cmds: Vec<DrawCmd>,
633 clips: Vec<Rect>,
634}
635
636impl DrawList {
637 pub fn new(clip: Rect) -> Self {
638 Self {
639 cmds: Vec::new(),
640 clips: vec![clip],
641 }
642 }
643
644 pub fn cmds(&self) -> &[DrawCmd] {
645 &self.cmds
646 }
647
648 pub fn push_clip(&mut self, r: Rect) {
649 let parent = *self.clips.last().unwrap_or(&Rect::default());
650 let c = parent.intersect(&r);
651 self.clips.push(c);
652 }
653
654 pub fn pop_clip(&mut self) {
655 if self.clips.len() > 1 {
656 self.clips.pop();
657 }
658 }
659
660 fn open_batch(&mut self, textured: bool) {
663 let clip = *self.clips.last().unwrap_or(&Rect::default());
664 let reuse = self
665 .cmds
666 .last()
667 .is_some_and(|c| c.textured == textured && c.clip == clip);
668 if !reuse {
669 self.cmds.push(DrawCmd {
670 clip,
671 textured,
672 vertices: Vec::new(),
673 });
674 }
675 }
676
677 fn quad(&mut self, r: Rect, uv: Rect, color: Rgba, textured: bool) {
678 let rect = [r.x, r.y, r.right(), r.bottom()];
679 let span = uv_span(uv);
680 let v = |x: f32, y: f32, u: f32, vv: f32| UiVertex {
681 pos: [x, y],
682 uv: [u, vv],
683 color,
684 rect,
685 span,
686 };
687 let a = v(r.x, r.y, uv.x, uv.y);
688 let b = v(r.right(), r.y, uv.right(), uv.y);
689 let c = v(r.right(), r.bottom(), uv.right(), uv.bottom());
690 let d = v(r.x, r.bottom(), uv.x, uv.bottom());
691 self.open_batch(textured);
692 self.cmds
693 .last_mut()
694 .expect("Batch geöffnet")
695 .vertices
696 .extend_from_slice(&[a, b, c, a, c, d]);
697 }
698
699 pub fn rect(&mut self, r: Rect, color: Rgba) {
701 self.quad(r, Rect::default(), color, false);
702 }
703
704 pub fn stroke(&mut self, r: Rect, w: f32, color: Rgba) {
706 self.rect(Rect::new(r.x, r.y, r.w, w), color);
707 self.rect(Rect::new(r.x, r.bottom() - w, r.w, w), color);
708 self.rect(Rect::new(r.x, r.y, w, r.h), color);
709 self.rect(Rect::new(r.right() - w, r.y, w, r.h), color);
710 }
711
712 pub fn line(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, w: f32, color: Rgba) {
717 if (y0 - y1).abs() <= w {
718 let top = (y0 - w * 0.5).round();
719 self.rect(
720 Rect::new(x0.min(x1), top, (x1 - x0).abs(), w.max(1.0)),
721 color,
722 );
723 } else {
724 let left = (x0 - w * 0.5).round();
725 self.rect(
726 Rect::new(left, y0.min(y1), w.max(1.0), (y1 - y0).abs()),
727 color,
728 );
729 }
730 }
731
732 pub fn image(&mut self, r: Rect, uv: Rect, color: Rgba) {
734 self.quad(r, uv, color, true);
735 }
736
737 #[allow(clippy::too_many_arguments)]
739 pub fn text(
740 &mut self,
741 atlas: &FontAtlas,
742 font: usize,
743 text: &str,
744 x: f32,
745 y: f32,
746 line_h: f32,
747 color: Rgba,
748 ) -> [f32; 2] {
749 let (verts, size) = atlas.text(font, text, x, y, line_h, color);
750 if !verts.is_empty() {
751 self.open_batch(true);
752 self.cmds
753 .last_mut()
754 .expect("Batch geöffnet")
755 .vertices
756 .extend_from_slice(&verts);
757 }
758 size
759 }
760}
761
762pub fn scissor_rect(clip: &Rect) -> (u32, u32, u32, u32) {
770 let x0 = clip.x.max(0.0).floor() as u32;
771 let y0 = clip.y.max(0.0).floor() as u32;
772 let x1 = clip.right().max(0.0).ceil() as u32;
773 let y1 = clip.bottom().max(0.0).ceil() as u32;
774 (x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
775}
776
777pub fn rasterize(dl: &DrawList, atlas: Option<&FontAtlas>, w: u32, h: u32, clear: Rgba) -> Vec<u8> {
785 let n = (w * h) as usize;
786 let mut buf: Vec<Rgba> = vec![clear; n];
787 for cmd in dl.cmds() {
788 let (sx, sy, sw, sh) = scissor_rect(&cmd.clip);
789 if sw == 0 || sh == 0 {
790 continue;
791 }
792 for quad in cmd.vertices.as_chunks::<6>().0 {
793 let (x0, y0) = (quad[0].pos[0], quad[0].pos[1]);
795 let (x1, y1) = (quad[2].pos[0], quad[2].pos[1]);
796 let (rx0, rx1) = (x0.min(x1), x0.max(x1));
797 let (ry0, ry1) = (y0.min(y1), y0.max(y1));
798 if rx1 <= rx0 || ry1 <= ry0 {
799 continue;
800 }
801 let (u0, v0) = (quad[0].uv[0], quad[0].uv[1]);
802 let (u1, v1) = (quad[2].uv[0], quad[2].uv[1]);
803 let color = quad[0].color;
804 debug_assert!(
808 quad[0].rect == [rx0, ry0, rx1, ry1] && quad[0].span == [u0, v0, u1 - u0, v1 - v0],
809 "rect/span-Felder weichen von der Eckpunkt-Ableitung ab"
810 );
811 let px0 = (rx0.floor().max(sx as f32)) as u32;
812 let py0 = (ry0.floor().max(sy as f32)) as u32;
813 let px1 = (rx1.ceil().min((sx + sw) as f32).min(w as f32) as u32).max(px0);
814 let py1 = (ry1.ceil().min((sy + sh) as f32).min(h as f32) as u32).max(py0);
815 for py in py0..py1 {
816 for px in px0..px1 {
817 let pcx = px as f32 + 0.5;
818 let pcy = py as f32 + 0.5;
819 if pcx < rx0 || pcx >= rx1 || pcy < ry0 || pcy >= ry1 {
820 continue;
821 }
822 let cov = if cmd.textured {
823 match atlas {
824 Some(a) => {
825 let tu = (pcx - rx0) / (rx1 - rx0);
826 let tv = (pcy - ry0) / (ry1 - ry0);
827 a.sample(u0 + (u1 - u0) * tu, v0 + (v1 - v0) * tv)
828 }
829 None => 1.0,
830 }
831 } else {
832 1.0
833 };
834 let sa = color[3] * cov;
835 if sa <= 0.0 {
836 continue;
837 }
838 let dst = &mut buf[(py * w + px) as usize];
839 let inv = 1.0 - sa;
840 for k in 0..3 {
841 dst[k] = color[k] * sa + dst[k] * inv;
842 }
843 dst[3] = sa + dst[3] * inv;
844 }
845 }
846 }
847 }
848 let mut out = vec![0u8; n * 4];
849 for (i, rgba) in buf.iter().enumerate() {
850 for k in 0..4 {
851 out[i * 4 + k] = (rgba[k].clamp(0.0, 1.0) * 255.0).round() as u8;
852 }
853 }
854 out
855}
856
857#[derive(Debug, thiserror::Error)]
860pub enum UiError {
861 #[error("Font konnte nicht gelesen werden: {0}")]
862 Font(String),
863 #[error("Atlas reicht nicht — {0} Glyphen passen nicht in {1}x{2}")]
864 AtlasFull(usize, u32, u32),
865}
866
867#[derive(Clone, Copy, Debug, PartialEq)]
871pub struct Glyph {
872 pub uv: Rect,
873 pub offset: [f32; 2],
874 pub size: [f32; 2],
875 pub advance: f32,
876}
877
878#[derive(Clone, Debug)]
882pub struct FontAtlas {
883 pub width: u32,
884 pub height: u32,
885 pub pixels: Vec<u8>,
886 ascents: Vec<f32>,
887 descents: Vec<f32>,
888 entries: std::collections::BTreeMap<(usize, char), Glyph>,
889}
890
891pub const ASCII_CHARS: &str =
894 " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
895
896impl FontAtlas {
897 pub fn build(
900 ttf_fonts: &[&[u8]],
901 px: f32,
902 extra: &str,
903 width: u32,
904 height: u32,
905 ) -> Result<Self, UiError> {
906 let mut fonts = Vec::with_capacity(ttf_fonts.len());
907 for bytes in ttf_fonts {
908 fonts.push(
909 ab_glyph::FontVec::try_from_vec(bytes.to_vec())
910 .map_err(|e| UiError::Font(e.to_string()))?,
911 );
912 }
913 let mut chars: Vec<char> = ASCII_CHARS.chars().collect();
914 chars.extend(extra.chars());
915 chars.sort_unstable();
916 chars.dedup();
917
918 let mut pixels = vec![0u8; (width * height) as usize];
919 let mut entries: std::collections::BTreeMap<(usize, char), Glyph> =
920 std::collections::BTreeMap::new();
921 let mut ascents = Vec::with_capacity(fonts.len());
922 let mut descents = Vec::with_capacity(fonts.len());
923
924 let mut shelf_x = 1u32;
925 let mut shelf_y = 1u32;
926 let mut shelf_h = 0u32;
927 for (fi, font) in fonts.iter().enumerate() {
928 let scaled = font.as_scaled(px);
929 ascents.push(scaled.ascent());
930 descents.push(scaled.descent());
931 for &ch in &chars {
932 let id = scaled.glyph_id(ch);
933 let adv = scaled.h_advance(id);
934 let og = font.outline_glyph(id.with_scale(px));
937 let bounds = og.as_ref().map(|o| o.px_bounds());
938 let gw = bounds.map_or(0, |b| b.width().ceil().max(0.0) as u32);
939 let gh = bounds.map_or(0, |b| b.height().ceil().max(0.0) as u32);
940 if og.is_none() || gw == 0 || gh == 0 {
941 entries.insert(
943 (fi, ch),
944 Glyph {
945 uv: Rect::default(),
946 offset: [0.0, 0.0],
947 size: [0.0, 0.0],
948 advance: adv,
949 },
950 );
951 continue;
952 }
953 if shelf_x + gw + 1 > width {
954 shelf_x = 1;
955 shelf_y += shelf_h + 1;
956 shelf_h = 0;
957 }
958 if shelf_y + gh + 1 > height {
959 return Err(UiError::AtlasFull(entries.len(), width, height));
960 }
961 let og = og.expect("geprüft");
962 og.draw(|x, y, alpha| {
963 let a = (alpha * 255.0).round().clamp(0.0, 255.0) as u8;
964 let ix = shelf_x + 1 + x;
965 let iy = shelf_y + 1 + y;
966 if ix < width && iy < height {
967 let idx = (iy * width + ix) as usize;
968 pixels[idx] = pixels[idx].max(a);
969 }
970 });
971 let b = bounds.expect("geprüft");
972 entries.insert(
973 (fi, ch),
974 Glyph {
975 uv: Rect::new(
976 (shelf_x + 1) as f32 / width as f32,
977 (shelf_y + 1) as f32 / height as f32,
978 gw as f32 / width as f32,
979 gh as f32 / height as f32,
980 ),
981 offset: [b.min.x, b.min.y],
982 size: [gw as f32, gh as f32],
983 advance: adv,
984 },
985 );
986 shelf_x += gw + 2;
987 shelf_h = shelf_h.max(gh);
988 }
989 }
990 Ok(Self {
991 width,
992 height,
993 pixels,
994 ascents,
995 descents,
996 entries,
997 })
998 }
999
1000 pub fn glyph(&self, font: usize, ch: char) -> Option<Glyph> {
1001 self.entries.get(&(font, ch)).copied()
1002 }
1003
1004 pub fn font_count(&self) -> usize {
1007 self.ascents.len()
1008 }
1009
1010 pub fn measure(&self, font: usize, text: &str, line_h: f32) -> [f32; 2] {
1014 let ascent = self.ascents[font];
1015 let descent = self.descents[font];
1016 let mut pen_x = 0.0f32;
1017 let mut pen_y = 0.0f32;
1018 let mut max_w = 0.0f32;
1019 for ch in text.chars() {
1020 if ch == '\n' {
1021 max_w = max_w.max(pen_x);
1022 pen_x = 0.0;
1023 pen_y += line_h;
1024 continue;
1025 }
1026 let Some(g) = self.glyph(font, ch) else {
1027 continue;
1028 };
1029 pen_x += g.advance;
1030 }
1031 max_w = max_w.max(pen_x);
1032 [max_w, pen_y + ascent - descent]
1034 }
1035
1036 pub fn sample(&self, u: f32, v: f32) -> f32 {
1039 let fx = (u * self.width as f32 - 0.5).clamp(0.0, self.width as f32 - 1.0);
1040 let fy = (v * self.height as f32 - 0.5).clamp(0.0, self.height as f32 - 1.0);
1041 let x0 = fx.floor() as u32;
1042 let y0 = fy.floor() as u32;
1043 let x1 = (x0 + 1).min(self.width - 1);
1044 let y1 = (y0 + 1).min(self.height - 1);
1045 let tx = fx - x0 as f32;
1046 let ty = fy - y0 as f32;
1047 let at = |x: u32, y: u32| self.pixels[(y * self.width + x) as usize] as f32 / 255.0;
1048 let top = at(x0, y0) * (1.0 - tx) + at(x1, y0) * tx;
1049 let bot = at(x0, y1) * (1.0 - tx) + at(x1, y1) * tx;
1050 top * (1.0 - ty) + bot * ty
1051 }
1052
1053 pub fn text(
1059 &self,
1060 font: usize,
1061 text: &str,
1062 x: f32,
1063 y: f32,
1064 line_h: f32,
1065 color: Rgba,
1066 ) -> (Vec<UiVertex>, [f32; 2]) {
1067 let ascent = self.ascents[font];
1068 let descent = self.descents[font];
1069 let mut verts = Vec::new();
1070 let mut pen_x = x;
1071 let mut pen_y = y;
1072 let mut max_w = 0.0f32;
1073 for ch in text.chars() {
1074 if ch == '\n' {
1075 max_w = max_w.max(pen_x - x);
1076 pen_x = x;
1077 pen_y += line_h;
1078 continue;
1079 }
1080 let Some(g) = self.glyph(font, ch) else {
1081 continue;
1082 };
1083 if g.size[0] > 0.0 && g.size[1] > 0.0 {
1084 let baseline = pen_y + ascent;
1085 let gx = (pen_x + g.offset[0]).round();
1094 let gy = (baseline + g.offset[1]).round();
1095 let r = Rect::new(gx, gy, g.size[0], g.size[1]);
1096 let uv = g.uv;
1099 let rect = [r.x, r.y, r.right(), r.bottom()];
1100 let span = uv_span(uv);
1101 let v = |px: f32, py: f32, u: f32, vv: f32| UiVertex {
1102 pos: [px, py],
1103 uv: [u, vv],
1104 color,
1105 rect,
1106 span,
1107 };
1108 verts.extend_from_slice(&[
1109 v(r.x, r.y, uv.x, uv.y),
1110 v(r.right(), r.y, uv.right(), uv.y),
1111 v(r.right(), r.bottom(), uv.right(), uv.bottom()),
1112 v(r.x, r.y, uv.x, uv.y),
1113 v(r.right(), r.bottom(), uv.right(), uv.bottom()),
1114 v(r.x, r.bottom(), uv.x, uv.bottom()),
1115 ]);
1116 }
1117 pen_x += g.advance;
1118 }
1119 max_w = max_w.max(pen_x - x);
1120 (verts, [max_w, pen_y - y + ascent - descent])
1122 }
1123}
1124
1125#[cfg(test)]
1128mod tests {
1129 use super::*;
1130
1131 const FONT_REGULAR: &[u8] = include_bytes!("../../../assets/fonts/inter/Inter-Regular.ttf");
1132
1133 fn r(x: f32, y: f32, w: f32, h: f32) -> Rect {
1134 Rect::new(x, y, w, h)
1135 }
1136
1137 #[test]
1138 fn rechteck_schnitt_und_enthalt() {
1139 let a = r(0.0, 0.0, 100.0, 50.0);
1140 assert_eq!(
1141 a.intersect(&r(50.0, 25.0, 100.0, 100.0)),
1142 r(50.0, 25.0, 50.0, 25.0)
1143 );
1144 assert_eq!(
1145 a.intersect(&r(200.0, 0.0, 10.0, 10.0)),
1146 r(200.0, 0.0, 0.0, 0.0)
1147 );
1148 assert!(a.contains(0.0, 0.0) && a.contains(99.9, 49.9) && !a.contains(100.0, 25.0));
1149 }
1150
1151 #[test]
1152 fn theme_serde_roundtrip_und_default_identitaet() {
1153 let t = Theme::default();
1154 let [rr, gg, bb, _] = t.colors.accent;
1156 assert!(
1157 rr > 0.7 && gg < rr && bb < gg,
1158 "Akzent muss warm-orange sein"
1159 );
1160 let json = serde_json::to_string(&t).expect("serialisiert");
1161 let back: Theme = serde_json::from_str(&json).expect("deserialisiert");
1162 assert_eq!(back, t);
1163 assert_eq!(t.label("unbekannt.panel"), "unbekannt.panel");
1164 }
1165
1166 #[test]
1167 fn dock_split_füllt_fläche_mit_splittern() {
1168 let tree = DockNode::Split {
1169 vertical: false,
1170 ratio: 0.25,
1171 first: Box::new(DockNode::Leaf {
1172 panel: "outliner".into(),
1173 }),
1174 second: Box::new(DockNode::Leaf {
1175 panel: "viewport".into(),
1176 }),
1177 };
1178 let p = dock_layout(&tree, r(0.0, 0.0, 1000.0, 600.0), 26.0, 4.0);
1179 assert_eq!(p.len(), 2);
1180 assert_eq!(p[0].rect, r(0.0, 0.0, 248.0, 600.0)); assert_eq!(p[1].rect, r(252.0, 0.0, 748.0, 600.0));
1182 }
1183
1184 #[test]
1185 fn dock_tabs_reservieren_streifen_und_zeigen_aktives() {
1186 let tree = DockNode::Tabs {
1187 active: 1,
1188 panels: vec!["a".into(), "b".into()],
1189 };
1190 let p = dock_layout(&tree, r(10.0, 20.0, 200.0, 180.0), 26.0, 4.0);
1191 assert_eq!(p.len(), 1, "nur das aktive Panel bekommt Inhalt");
1192 assert_eq!(p[0].panel, "b");
1193 assert_eq!(p[0].rect, r(10.0, 46.0, 200.0, 154.0));
1194 assert_eq!(p[0].tabs.len(), 2);
1195 assert_eq!(p[0].tabs[0].1, r(10.0, 20.0, 100.0, 26.0));
1196 }
1197
1198 #[test]
1199 fn dock_verschachtelt_ohne_luecken() {
1200 let tree = DockNode::Split {
1201 vertical: true,
1202 ratio: 0.7,
1203 first: Box::new(DockNode::Split {
1204 vertical: false,
1205 ratio: 0.5,
1206 first: Box::new(DockNode::Leaf { panel: "a".into() }),
1207 second: Box::new(DockNode::Leaf { panel: "b".into() }),
1208 }),
1209 second: Box::new(DockNode::Leaf { panel: "c".into() }),
1210 };
1211 let area = r(0.0, 0.0, 400.0, 400.0);
1212 let p = dock_layout(&tree, area, 26.0, 4.0);
1213 assert_eq!(p.len(), 3);
1214 for x in &p {
1216 assert!(x.rect.x >= 0.0 && x.rect.right() <= 400.0);
1217 assert!(x.rect.y >= 0.0 && x.rect.bottom() <= 400.0);
1218 }
1219 for i in 0..p.len() {
1220 for j in i + 1..p.len() {
1221 assert_eq!(
1222 p[i].rect.intersect(&p[j].rect).w * p[i].rect.intersect(&p[j].rect).h,
1223 0.0,
1224 "Überlappung {} vs {}",
1225 p[i].panel,
1226 p[j].panel
1227 );
1228 }
1229 }
1230 }
1231
1232 #[test]
1233 fn drawlist_batcht_nach_clip_und_textur() {
1234 let mut dl = DrawList::new(r(0.0, 0.0, 100.0, 100.0));
1235 dl.rect(r(0.0, 0.0, 10.0, 10.0), [1.0, 0.0, 0.0, 1.0]);
1236 dl.rect(r(20.0, 0.0, 10.0, 10.0), [0.0, 1.0, 0.0, 1.0]);
1237 assert_eq!(
1238 dl.cmds().len(),
1239 1,
1240 "gleicher Clip + untexturiert => ein Batch"
1241 );
1242 assert_eq!(dl.cmds()[0].vertices.len(), 12);
1243 dl.push_clip(r(50.0, 0.0, 50.0, 100.0));
1244 dl.rect(r(60.0, 0.0, 10.0, 10.0), [0.0, 0.0, 1.0, 1.0]);
1245 assert_eq!(dl.cmds().len(), 2, "anderer Clip => neuer Batch");
1246 assert_eq!(dl.cmds()[1].clip, r(50.0, 0.0, 50.0, 100.0));
1247 dl.pop_clip();
1248 dl.rect(r(0.0, 0.0, 5.0, 5.0), [1.0, 1.0, 1.0, 1.0]);
1249 assert_eq!(
1250 dl.cmds().len(),
1251 3,
1252 "zurück: eigener Batch (Batch-Reihenfolge zählt)"
1253 );
1254 }
1255
1256 #[test]
1257 fn scissor_stapel_verschachtelt_klemmend() {
1258 let mut dl = DrawList::new(r(0.0, 0.0, 100.0, 100.0));
1259 dl.push_clip(r(10.0, 10.0, 80.0, 80.0));
1260 dl.push_clip(r(50.0, 50.0, 80.0, 80.0));
1261 dl.rect(r(60.0, 60.0, 5.0, 5.0), [1.0, 1.0, 1.0, 1.0]);
1262 assert_eq!(
1263 dl.cmds()[0].clip,
1264 r(50.0, 50.0, 40.0, 40.0),
1265 "Kind-Clip = Schnitt"
1266 );
1267 dl.pop_clip();
1268 dl.rect(r(20.0, 20.0, 5.0, 5.0), [1.0, 1.0, 1.0, 1.0]);
1269 assert_eq!(dl.cmds()[1].clip, r(10.0, 10.0, 80.0, 80.0));
1270 }
1271
1272 #[test]
1273 fn stroke_sind_vier_rechtecke() {
1274 let mut dl = DrawList::new(r(0.0, 0.0, 100.0, 100.0));
1275 dl.stroke(r(0.0, 0.0, 20.0, 20.0), 2.0, [1.0, 1.0, 1.0, 1.0]);
1276 assert_eq!(dl.cmds()[0].vertices.len(), 4 * 6);
1277 }
1278
1279 #[test]
1280 fn atlas_rastert_inter_und_legt_text_aus() {
1281 let atlas = FontAtlas::build(&[FONT_REGULAR], 15.0, "äöüÄÖÜß", 512, 512).expect("Atlas");
1282 assert!(
1283 atlas.pixels.iter().any(|&p| p > 0),
1284 "Atlas muss Abdeckungen haben"
1285 );
1286 let a = atlas.glyph(0, 'A').expect("A im Atlas");
1287 let sp = atlas.glyph(0, ' ').expect("Leerzeichen im Atlas");
1288 assert!(a.size[0] > 0.0 && a.advance > 0.0);
1289 assert_eq!(sp.size[0], 0.0, "Leerzeichen hat keine Fläche");
1290 assert!(sp.advance > 0.0, "aber Vorschub");
1291 let uml = atlas.glyph(0, 'ö').expect("ö im Atlas");
1292 assert!(uml.size[0] > 0.0, "extra-Zeichen im Atlas");
1293 let mut rects: Vec<(usize, char, Rect)> = atlas
1295 .entries
1296 .iter()
1297 .map(|((f, c), g)| (*f, *c, g.uv))
1298 .filter(|(_, _, uv)| uv.w > 0.0)
1299 .collect();
1300 rects.sort_by_key(|(f, c, _)| (*f, *c as u32));
1301 for w in rects.windows(2) {
1302 let (a, b) = (w[0].2, w[1].2);
1303 let ix = a.intersect(&b);
1304 assert!(
1305 ix.w <= 0.0 || ix.h <= 0.0,
1306 "UV-Überlappung {:?} vs {:?}",
1307 w[0],
1308 w[1]
1309 );
1310 }
1311 let (verts, size) = atlas.text(0, "Aö", 10.0, 20.0, 18.0, [1.0, 1.0, 1.0, 1.0]);
1313 assert_eq!(verts.len(), 12);
1314 assert!(size[0] > 0.0 && size[1] >= 15.0);
1315 assert!(verts
1316 .iter()
1317 .all(|v| v.uv[0] >= 0.0 && v.uv[0] <= 1.0 && v.uv[1] >= 0.0 && v.uv[1] <= 1.0));
1318 let (_, size2) = atlas.text(0, "A\nA", 0.0, 0.0, 18.0, [1.0, 1.0, 1.0, 1.0]);
1320 assert!(size2[1] > size[1]);
1321 }
1322
1323 #[test]
1324 fn atlas_bau_ist_deterministisch() {
1325 let a = FontAtlas::build(&[FONT_REGULAR], 15.0, "", 512, 512).expect("a");
1326 let b = FontAtlas::build(&[FONT_REGULAR], 15.0, "", 512, 512).expect("b");
1327 assert_eq!(a.pixels, b.pixels);
1328 assert_eq!(a.entries.keys().count(), b.entries.keys().count());
1329 for (k, ga) in &a.entries {
1330 assert_eq!(*ga, b.entries[k], "Glyph {k:?} instabil");
1331 }
1332 }
1333
1334 #[test]
1335 fn rasterizer_blendet_und_scissort() {
1336 let mut dl = DrawList::new(r(0.0, 0.0, 20.0, 20.0));
1337 dl.rect(r(2.0, 2.0, 8.0, 8.0), [1.0, 0.0, 0.0, 1.0]);
1338 dl.push_clip(r(12.0, 0.0, 8.0, 20.0));
1339 dl.rect(r(10.0, 4.0, 8.0, 8.0), [0.0, 1.0, 0.0, 0.5]);
1340 dl.pop_clip();
1341 let img = rasterize(&dl, None, 20, 20, [0.0, 0.0, 0.0, 0.0]);
1342 let at = |x: u32, y: u32, k: usize| img[((y * 20 + x) as usize) * 4 + k];
1343 assert_eq!((at(5, 5, 0), at(5, 5, 3)), (255, 255), "ndeckendes Rot");
1344 assert_eq!((at(0, 0, 0), at(0, 0, 3)), (0, 0), "Clear bleibt leer");
1345 assert_eq!((at(14, 8, 1), at(14, 8, 3)), (128, 128), "50% gemischt");
1346 assert_eq!(at(10, 8, 1), 0, "Scissor schneidet links ab");
1347 assert_eq!(at(14, 2, 1), 0, "oberhalb des Rechtecks nichts");
1348 }
1349
1350 #[test]
1351 fn rasterizer_malt_text_lesbar() {
1352 let atlas = FontAtlas::build(&[FONT_REGULAR], 24.0, "", 512, 512).expect("Atlas");
1353 let mut dl = DrawList::new(r(0.0, 0.0, 160.0, 48.0));
1354 let size = dl.text(&atlas, 0, "Hallo", 8.0, 8.0, 28.0, [1.0, 1.0, 1.0, 1.0]);
1355 assert!(size[0] > 20.0 && size[1] > 20.0, "bbox plausibel: {size:?}");
1356 let img = rasterize(&dl, Some(&atlas), 160, 48, [0.0, 0.0, 0.0, 1.0]);
1357 let lit = |x: u32, y: u32| img[((y * 160 + x) as usize) * 4] > 40;
1358 let inside = (8..8 + size[0] as u32 + 2).flat_map(|x| (6..40).map(move |y| (x, y)));
1359 assert!(
1360 inside.filter(|&(x, y)| lit(x, y)).count() > 100,
1361 "Glyphenfläche"
1362 );
1363 let outside = (0..160u32)
1365 .flat_map(|x| (0..48u32).map(move |y| (x, y)))
1366 .filter(|(x, y)| *x < 6 || *x > 8 + size[0] as u32 + 2 || *y < 4 || *y > 42);
1367 assert!(
1368 outside.filter(|&(x, y)| lit(x, y)).count() == 0,
1369 "kein Ausbluten"
1370 );
1371 }
1372
1373 #[test]
1374 fn rasterizer_png_beweis() {
1375 let Ok(path) = std::env::var("RE_UI_PNG") else {
1378 return;
1379 };
1380 const FONT_BOLD: &[u8] = include_bytes!("../../../assets/fonts/inter/Inter-Bold.ttf");
1381 let theme = Theme::default();
1382 let atlas = FontAtlas::build(&[FONT_REGULAR, FONT_BOLD], 15.0, "äöüÄÖÜß—", 1024, 512)
1383 .expect("Atlas");
1384 let (w, h) = (480u32, 280u32);
1385 let (wf, hf) = (w as f32, h as f32);
1386 let mut dl = DrawList::new(r(0.0, 0.0, wf, hf));
1387 dl.rect(r(0.0, 0.0, wf, hf), theme.colors.background);
1388 dl.rect(r(0.0, 0.0, wf, 28.0), theme.colors.header);
1390 dl.line(0.0, 28.0, wf, 28.0, 1.0, theme.colors.border);
1391 dl.text(
1392 &atlas,
1393 1,
1394 "re-editor — P1",
1395 10.0,
1396 6.0,
1397 20.0,
1398 theme.colors.text,
1399 );
1400 dl.rect(r(6.0, 36.0, 170.0, hf - 42.0), theme.colors.panel);
1402 dl.stroke(r(6.0, 36.0, 170.0, hf - 42.0), 1.0, theme.colors.border);
1403 dl.text(
1404 &atlas,
1405 1,
1406 "Outliner",
1407 14.0,
1408 42.0,
1409 18.0,
1410 theme.colors.text_dim,
1411 );
1412 for i in 0..6u32 {
1413 let y = 66.0 + i as f32 * 22.0;
1414 if i == 1 {
1415 dl.rect(r(8.0, y - 2.0, 166.0, 20.0), theme.colors.select);
1416 } else if i == 3 {
1417 dl.rect(r(8.0, y - 2.0, 166.0, 20.0), theme.colors.hover);
1418 }
1419 dl.text(
1420 &atlas,
1421 0,
1422 &format!("Entity {i} — Würfel äöü"),
1423 16.0,
1424 y,
1425 18.0,
1426 theme.colors.text,
1427 );
1428 }
1429 let vx = 182.0;
1431 dl.rect(
1432 r(vx, 36.0, wf - vx - 6.0, hf - 42.0),
1433 theme.colors.viewport_bg,
1434 );
1435 dl.stroke(
1436 r(vx, 36.0, wf - vx - 6.0, hf - 42.0),
1437 1.0,
1438 theme.colors.border,
1439 );
1440 dl.text(
1441 &atlas,
1442 0,
1443 "Perspektive",
1444 vx + 10.0,
1445 44.0,
1446 18.0,
1447 theme.colors.text_dim,
1448 );
1449 let btn = r(vx + 12.0, hf - 46.0, 120.0, 26.0);
1451 dl.rect(btn, theme.colors.accent);
1452 dl.text(
1453 &atlas,
1454 1,
1455 "Anwenden",
1456 btn.x + 22.0,
1457 btn.y + 5.0,
1458 18.0,
1459 [1.0, 1.0, 1.0, 1.0],
1460 );
1461 let img = rasterize(&dl, Some(&atlas), w, h, theme.colors.background);
1462 image::RgbaImage::from_raw(w, h, img)
1463 .expect("bild")
1464 .save(&path)
1465 .expect("png");
1466 }
1467
1468 #[test]
1469 fn splitter_spiegelt_die_layout_geometrie() {
1470 let root = DockNode::Split {
1471 vertical: false,
1472 ratio: 0.25,
1473 first: Box::new(DockNode::Leaf { panel: "a".into() }),
1474 second: Box::new(DockNode::Leaf { panel: "b".into() }),
1475 };
1476 let area = Rect::new(0.0, 0.0, 1000.0, 500.0);
1477 let hits = dock_splitters(&root, area, 20.0, 4.0);
1478 assert_eq!(hits.len(), 1);
1479 let g = &hits[0];
1480 assert!(!g.vertical);
1481 assert_eq!(g.track, area);
1482 assert!(g.grab.contains(249.0, 100.0) && g.grab.contains(251.0, 100.0));
1486 let ps = dock_layout(&root, area, 20.0, 4.0);
1487 assert_eq!(ps.len(), 2);
1488 for pl in &ps {
1489 assert!(
1490 !g.grab.contains(pl.rect.x + 1.0, pl.rect.y + 1.0),
1491 "Greifband über Panel"
1492 );
1493 }
1494 }
1495
1496 #[test]
1497 fn ratio_pfad_suche_und_klemmen() {
1498 let inner = DockNode::Split {
1499 vertical: true,
1500 ratio: 0.5,
1501 first: Box::new(DockNode::Leaf { panel: "x".into() }),
1502 second: Box::new(DockNode::Leaf { panel: "y".into() }),
1503 };
1504 let mut root = DockNode::Split {
1505 vertical: false,
1506 ratio: 0.5,
1507 first: Box::new(inner),
1508 second: Box::new(DockNode::Leaf { panel: "z".into() }),
1509 };
1510 assert!(dock_set_ratio(&mut root, &[0], 1.7), "klemmt auf 0.95");
1511 if let DockNode::Split { ratio: rr, .. } = &root {
1512 assert!((*rr - 0.5).abs() < 1e-6, "root bleibt ruhig");
1513 }
1514 if let DockNode::Split { first, .. } = &root {
1515 if let DockNode::Split { ratio, .. } = &**first {
1516 assert!((*ratio - 0.95).abs() < 1e-6, "innerer Split geklemmt");
1517 } else {
1518 panic!("first ist kein Split");
1519 }
1520 }
1521 assert!(
1522 dock_set_ratio(&mut root, &[0], 0.3),
1523 "innerer Split erneut gesetzt"
1524 );
1525 if let DockNode::Split { first, .. } = &root {
1526 if let DockNode::Split { ratio, .. } = &**first {
1527 assert!((*ratio - 0.3).abs() < 1e-6);
1528 }
1529 }
1530 assert!(
1531 !dock_set_ratio(&mut root, &[1, 0], 0.5),
1532 "Blatt am Pfadende — abweg"
1533 );
1534 assert!(
1535 !dock_set_ratio(&mut root, &[0, 0], 0.5),
1536 "Blatt im Inneren — abweg"
1537 );
1538 }
1539
1540 #[test]
1541 fn take_und_put_erhalten_jedes_panel() {
1542 let mut root = DockNode::Split {
1544 vertical: false,
1545 ratio: 0.7,
1546 first: Box::new(DockNode::Tabs {
1547 active: 0,
1548 panels: vec!["console".into(), "assistant".into()],
1549 }),
1550 second: Box::new(DockNode::Leaf {
1551 panel: "viewport".into(),
1552 }),
1553 };
1554 assert_eq!(dock_panel_count(&root), 3);
1555 assert!(dock_take(&mut root, "assistant"));
1557 assert_eq!(
1558 dock_panel_count(&root),
1559 2,
1560 "Rest-Tabs mit einem Kind kollabiert zu Leaf"
1561 );
1562 assert!(dock_put(
1563 &mut root,
1564 "assistant",
1565 "console",
1566 DockEdge::Center
1567 ));
1568 assert_eq!(dock_panel_count(&root), 3);
1569 let ps = dock_layout(&root, Rect::new(0.0, 0.0, 1000.0, 600.0), 20.0, 4.0);
1570 assert!(
1571 ps.iter()
1572 .any(|p| p.panel == "assistant" && !p.tabs.is_empty()),
1573 "assistant aktiv in der Gruppe"
1574 );
1575 assert!(dock_take(&mut root, "assistant"));
1577 assert!(dock_put(
1578 &mut root,
1579 "assistant",
1580 "viewport",
1581 DockEdge::Right
1582 ));
1583 if let DockNode::Split { second, .. } = &root {
1584 assert!(
1585 matches!(&**second, DockNode::Split { vertical: false, ratio, .. } if (*ratio - 0.5).abs() < 1e-6),
1586 "Rechts-Split mit 0.5"
1587 );
1588 } else {
1589 panic!("root bleibt Split");
1590 }
1591 assert_eq!(dock_panel_count(&root), 3);
1592 assert!(dock_contains(&root, "assistant"));
1593 }
1594
1595 #[test]
1596 fn take_schuetzt_letztes_panel_put_prueft_bindungen() {
1597 let mut single = DockNode::Leaf {
1598 panel: "solo".into(),
1599 };
1600 assert!(!dock_take(&mut single, "solo"), "das letzte Panel bleibt");
1601
1602 let mut root = DockNode::Split {
1603 vertical: false,
1604 ratio: 0.5,
1605 first: Box::new(DockNode::Leaf { panel: "a".into() }),
1606 second: Box::new(DockNode::Leaf { panel: "b".into() }),
1607 };
1608 assert!(
1609 !dock_put(&mut root, "c", "wo.nichts.ist", DockEdge::Center),
1610 "Ziel fehlt"
1611 );
1612 assert!(
1613 !dock_put(&mut root, "a", "b", DockEdge::Center),
1614 "Panel sitzt schon im Baum"
1615 );
1616 assert!(dock_take(&mut root, "a"));
1617 assert!(
1618 !dock_put(&mut root, "a", "a", DockEdge::Center),
1619 "nicht auf sich selbst"
1620 );
1621 assert!(dock_put(&mut root, "a", "b", DockEdge::Center));
1622 if let DockNode::Tabs { active, panels } = &root {
1623 assert_eq!(panels, &vec!["b".to_string(), "a".to_string()]);
1624 assert_eq!(*active, 1, "frischangedocktes Tab wird aktiv");
1625 } else {
1626 panic!("Gruppe entstanden");
1627 }
1628 }
1629}