mahbot 0.11.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
//! A [`cosmic_text::Buffer`]-backed widget for rendering diff file content with syntax
//! highlighting, gutter line numbers and per-line background tints.
//!
//! Each diff file gets its own [`DiffBufferWidget`]; file headers, binary placeholders and
//! truncation warnings stay Iced widgets interleaved between them, and the whole panel is wrapped
//! in an Iced scrollable — per-file buffers do NOT manage their own scroll.
//!
//! The buffer text excludes the gutter: each logical line is `"{prefix} {content}\n"` (`+`, `-` or
//! ` ` in the prefix), and hunk headers are inserted as full text lines. The gutter is drawn
//! entirely in `draw()` via `fill_text`, so it is never repeated on wrapped continuation lines.
//!
//! Shaping a large diff is expensive and the UI rebuilds on the modal's auto-refresh tick, so the
//! shaped [`cosmic_text::Buffer`] is cached in widget state keyed on a content fingerprint plus the
//! text-area width (see [`ShapeCacheKey`]); `draw()` processes only layout runs intersecting the
//! visible viewport, so per-frame cost scales with visible content. The key is content-derived, so
//! iced's position-based state reuse can never display stale content.

use std::sync::Arc;

use iced::advanced::graphics::text::cosmic_text;
use iced::advanced::layout::{self, Layout};
use iced::advanced::text;
use iced::advanced::widget::{self, Tree, Widget};
use iced::advanced::{Clipboard, Shell};
use iced::advanced::{mouse, renderer};
use iced::keyboard;
use iced::{Color, Event, Length, Point, Rectangle, Size};

use crate::git::diff_parse::{DiffFileStatus, DiffLineKind};

use super::text_rendering::{
    GUTTER_FONT_SIZE, compute_total_height, cursor_to_buffer_coords, draw_background,
    draw_buffer_text, draw_highlight_background, draw_run_highlights, fill_rich_spans,
    font_metrics, gutter_clip_rect, iced_color_to_cosmic, text_area_rect, with_font_system,
};
use super::theme;

/// Hunk header text color — the syntax-highlight palette entry for types
/// ([`super::highlight::HighlightClass::Type`]).
const HUNK_HEADER_COLOR: Color = super::highlight::HighlightClass::Type.color();

const ADDED_COLOR: Color = theme::STATUS_SUCCESS;

const REMOVED_COLOR: Color = theme::STATUS_ERROR;

const CONTEXT_COLOR: Color = theme::TEXT_SECONDARY;

/// Approximate pixel width of one monospace digit at [`GUTTER_FONT_SIZE`].
const GUTTER_DIGIT_WIDTH: f32 = GUTTER_FONT_SIZE * 0.62;

const SELECTION_COLOR: Color = theme::ACCENT_DIM;

/// Pre-built data for rendering one diff file via [`DiffBufferWidget`]: all string formatting and
/// span computation happens when this is built (on diff load / selection change), not per-frame.
pub struct DiffFileBuffer {
    /// The full buffer text: hunk headers + prefixed diff lines, newline-terminated.
    pub text: String,
    /// Per-span data `(start_byte, end_byte, iced_color)` covering the entire text; gaps use
    /// `theme::TEXT_PRIMARY`.
    pub span_data: Vec<(usize, usize, Color)>,
    /// Per-logical-line kind: `None` for hunk headers, `Some(kind)` for diff lines.
    pub line_kinds: Vec<Option<DiffLineKind>>,
    /// Per-logical-line `(old_num, new_num)`; both `None` for hunk headers and unnumbered lines.
    pub line_numbers: Vec<(Option<usize>, Option<usize>)>,
    /// Digit count for the widest old/new line number (minimum 1).
    pub gutter_digits: usize,
    /// Content fingerprint over every other field, computed once at build time and part of the
    /// shape-cache key: an unchanged diff (a byte-identical rebuild on auto-refresh) reuses the
    /// shaped layout, any change forces a full re-shape.
    pub content_fingerprint: u64,
}

/// Cache key for a shaped [`cosmic_text::Buffer`], covering every input to shaping: the content
/// fingerprint, the content lengths (hash-collision hardening) and the shaping width (wrapping
/// depends on it). Any change invalidates the cache and runs the full re-shape — stale content must
/// never be displayed, including when iced recycles widget state positionally after the file list
/// changes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct ShapeCacheKey {
    content_fingerprint: u64,
    text_len: usize,
    span_count: usize,
    width_bits: u32,
}

impl ShapeCacheKey {
    fn new(data: &DiffFileBuffer, text_area_width: f32) -> Self {
        Self {
            content_fingerprint: data.content_fingerprint,
            text_len: data.text.len(),
            span_count: data.span_data.len(),
            width_bits: text_area_width.to_bits(),
        }
    }
}

/// A shaped buffer cached in widget state across UI rebuilds, together with
/// its total content height (kept consistent with the buffer so the
/// scrollable content height never drifts from the drawn content).
struct ShapeCacheEntry {
    key: ShapeCacheKey,
    buffer: Arc<cosmic_text::Buffer>,
    total_height: f32,
}

/// Persistent state stored in `widget::Tree::State`.
#[derive(Default)]
struct DiffBufferState {
    /// Cached shaped buffer + total height, reused while the cache key is
    /// unchanged. The `Arc<Buffer>` must live across frames for `fill_raw`
    /// to work.
    shape_cache: Option<ShapeCacheEntry>,
    /// Cached gutter width in pixels (computed per frame in layout).
    gutter_width: f32,
    /// Selection anchor byte offset in buffer text (`None` = no selection).
    sel_anchor: Option<usize>,
    sel_cursor: Option<usize>,
    mouse_held: bool,
}

/// A custom Iced widget that renders a single diff file's content via
/// [`cosmic_text::Buffer`], with gutter line numbers and per-line background
/// tints. Designed to be used inside a parent `scrollable` — it reports
/// its full content height.
pub struct DiffBufferWidget<'a> {
    data: &'a DiffFileBuffer,
    /// Horizontal inset. The shared scrollable wrapper (`widgets::SCROLL_H_PAD`)
    /// provides the 8px/side inset, so the widget's own horizontal padding is 0.
    h_padding: f32,
    v_padding: f32,
}

impl<'a> DiffBufferWidget<'a> {
    #[must_use]
    pub const fn new(data: &'a DiffFileBuffer) -> Self {
        Self {
            data,
            h_padding: 0.0,
            v_padding: 8.0,
        }
    }
}

#[must_use]
fn compute_gutter_digits(line_numbers: &[(Option<usize>, Option<usize>)]) -> usize {
    line_numbers
        .iter()
        .flat_map(|(old, new)| [*old, *new])
        .flatten()
        .map(|n| n.to_string().len())
        .max()
        .unwrap_or(1)
}

#[must_use]
#[expect(clippy::cast_precision_loss)]
const fn gutter_width_from_digits(digits: usize) -> f32 {
    digits as f32 * GUTTER_DIGIT_WIDTH * 2.0 + 14.0
}

/// Right-edge anchors for the old/new gutter columns.
///
/// `fill_text` uses the point as the right edge when `align_x` is `Right`.
/// This mirrors the main editor gutter; passing each column's left edge clips
/// or shifts line numbers into the gutter padding.
fn gutter_column_right_edges(bounds_x: f32, h_padding: f32, gutter_width: f32) -> (f32, f32) {
    let half_gutter = gutter_width / 2.0;
    (
        bounds_x + h_padding + half_gutter,
        bounds_x + h_padding + gutter_width,
    )
}

/// Compute a content fingerprint for a [`DiffFileBuffer`]'s shaping inputs.
///
/// The fingerprint covers every field that can influence the shaped buffer
/// (text bytes, span positions/colors, line kinds, line numbers, gutter
/// digits). It is computed once at buffer-build time and forms the core of
/// the shape-cache key, so that unchanged diff content — e.g. after a
/// 5-second auto-refresh that rebuilt byte-identical buffers — reuses the
/// existing shaped layout, while any content change forces a full re-shape.
#[must_use]
fn compute_content_fingerprint(
    text: &str,
    span_data: &[(usize, usize, Color)],
    line_kinds: &[Option<DiffLineKind>],
    line_numbers: &[(Option<usize>, Option<usize>)],
    gutter_digits: usize,
) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    text.hash(&mut hasher);
    for &(start, end, color) in span_data {
        start.hash(&mut hasher);
        end.hash(&mut hasher);
        color.r.to_bits().hash(&mut hasher);
        color.g.to_bits().hash(&mut hasher);
        color.b.to_bits().hash(&mut hasher);
        color.a.to_bits().hash(&mut hasher);
    }
    for kind in line_kinds {
        match kind {
            Some(k) => {
                1u8.hash(&mut hasher);
                (*k as u8).hash(&mut hasher);
            }
            None => 0u8.hash(&mut hasher),
        }
    }
    for (old, new) in line_numbers {
        match old {
            Some(n) => {
                1u8.hash(&mut hasher);
                n.hash(&mut hasher);
            }
            None => 0u8.hash(&mut hasher),
        }
        match new {
            Some(n) => {
                1u8.hash(&mut hasher);
                n.hash(&mut hasher);
            }
            None => 0u8.hash(&mut hasher),
        }
    }
    gutter_digits.hash(&mut hasher);
    hasher.finish()
}

fn hit_to_global_byte(buffer: &cosmic_text::Buffer, line: usize, index: usize) -> usize {
    let mut global = 0usize;
    for i in 0..line {
        if let Some(l) = buffer.lines.get(i) {
            global += l.text().len() + 1;
        }
    }
    global + index
}

fn global_byte_to_cursor(buffer: &cosmic_text::Buffer, global: usize) -> cosmic_text::Cursor {
    let mut pos = 0usize;
    for (i, line) in buffer.lines.iter().enumerate() {
        let text = line.text();
        let line_len = text.len();
        let next = pos.saturating_add(line_len);
        if global <= next || i + 1 == buffer.lines.len() {
            return cosmic_text::Cursor {
                line: i,
                index: global.saturating_sub(pos).min(line_len),
                ..cosmic_text::Cursor::default()
            };
        }
        pos = next + 1;
    }
    cosmic_text::Cursor::default()
}

/// The preamble (cursor → buffer-relative coordinates) is delegated to [`cursor_to_buffer_coords`];
/// **do not subtract `bounds.x` / `bounds.y` again** after calling it — see its docstring for the
/// coordinate convention and the rationale.
fn hit_test(
    buffer: &cosmic_text::Buffer,
    layout: Layout<'_>,
    cursor: mouse::Cursor,
    gutter_width: f32,
    h_padding: f32,
    v_padding: f32,
) -> Option<usize> {
    let (buf_x, buf_y) =
        cursor_to_buffer_coords(layout, cursor, gutter_width, h_padding, v_padding)?;
    let hit = buffer.hit(buf_x, buf_y)?;
    Some(hit_to_global_byte(buffer, hit.line, hit.index))
}

/// Extract selected text from global byte offsets (excluding gutter numbers).
fn selection_text(text: &str, anchor: usize, cursor: usize) -> Option<String> {
    if anchor == cursor {
        return None;
    }
    let (start, end) = if anchor < cursor {
        (anchor, cursor)
    } else {
        (cursor, anchor)
    };
    if !text.is_char_boundary(start) || !text.is_char_boundary(end) {
        return None;
    }
    Some(text[start..end].to_string())
}

fn has_selection(anchor: Option<usize>, cursor: Option<usize>) -> bool {
    match (anchor, cursor) {
        (Some(a), Some(c)) => a != c,
        _ => false,
    }
}

impl<Theme, Renderer> Widget<super::diff::DiffMessage, Theme, Renderer> for DiffBufferWidget<'_>
where
    Renderer: iced::advanced::Renderer
        + iced::advanced::graphics::text::Renderer
        + iced::advanced::text::Renderer<Font = iced::Font>,
{
    fn size(&self) -> Size<Length> {
        Size::new(Length::Fill, Length::Shrink)
    }

    fn state(&self) -> widget::tree::State {
        widget::tree::State::Some(Box::<DiffBufferState>::default())
    }

    fn tag(&self) -> widget::tree::Tag {
        widget::tree::Tag::of::<DiffBufferState>()
    }

    fn layout(
        &mut self,
        tree: &mut Tree,
        _renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        let bounds = limits.max();
        let state = tree.state.downcast_mut::<DiffBufferState>();

        let gutter_width = gutter_width_from_digits(self.data.gutter_digits);
        state.gutter_width = gutter_width;

        let text_area_width = text_area_rect(
            Rectangle::new(Point::ORIGIN, bounds),
            self.h_padding,
            self.v_padding,
            gutter_width,
        )
        .width;

        // No content: collapse to zero height and drop any cached buffer so a recycled
        // state slot can never draw stale content.
        if self.data.text.is_empty() {
            state.shape_cache = None;
            return layout::Node::new(Size::new(bounds.width, 0.0));
        }

        let cache_key = ShapeCacheKey::new(self.data, text_area_width);

        // Reuse the previously shaped buffer and its total height instead of re-shaping:
        // the key covers fingerprint, lengths and width, so any change (diff data, wrapping
        // width, a reshuffle that recycles this slot) falls through to the full re-shape
        // below.
        if let Some(entry) = &state.shape_cache
            && entry.key == cache_key
        {
            return layout::Node::new(Size::new(
                bounds.width,
                entry.total_height + self.v_padding * 2.0,
            ));
        }

        let metrics = font_metrics();

        let (buffer, total_height) = with_font_system(|font_sys| {
            let mut buffer = cosmic_text::Buffer::new(font_sys, font_metrics());

            let text = &self.data.text;
            let base_attrs = cosmic_text::Attrs::new()
                .family(cosmic_text::Family::Name("JetBrains Mono"))
                .color(iced_color_to_cosmic(theme::TEXT_PRIMARY));

            let spans = self.data.span_data.iter().map(|&(start, end, color)| {
                (
                    start,
                    end,
                    base_attrs.clone().color(iced_color_to_cosmic(color)),
                )
            });
            let rich_spans = fill_rich_spans(text, spans, &base_attrs);

            buffer.set_rich_text(
                font_sys,
                rich_spans,
                &base_attrs,
                cosmic_text::Shaping::Advanced,
                None,
            );
            buffer.set_scroll(cosmic_text::Scroll {
                line: 0,
                vertical: 0.0,
                horizontal: 0.0,
            });
            buffer.set_size(font_sys, Some(text_area_width), None);
            buffer.shape_until_scroll(font_sys, false);

            // Cap each source line at MAX_VISUAL_LINES_PER_SOURCE visual lines.
            let total_height: f32 = compute_total_height(&mut buffer, font_sys, metrics);

            (buffer, total_height)
        });

        // Store the shaped buffer with its cache key and total height for reuse on later
        // layouts.
        let arc = Arc::new(buffer);
        state.shape_cache = Some(ShapeCacheEntry {
            key: cache_key,
            buffer: arc,
            total_height,
        });

        layout::Node::new(Size::new(bounds.width, total_height + self.v_padding * 2.0))
    }

    #[expect(clippy::too_many_lines)]
    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        _theme: &Theme,
        _style: &renderer::Style,
        layout: Layout<'_>,
        _cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        let state = tree.state.downcast_ref::<DiffBufferState>();
        let bounds = layout.bounds();
        let gutter_width = state.gutter_width;

        // The scrollable passes its visible region in the same coordinate space as `bounds`
        // (see its draw: the renderer is translated, the viewport is not). Only runs
        // intersecting it are processed, so per-frame cost scales with visible content;
        // fully off-screen → nothing.
        let Some(visible) = bounds.intersection(viewport) else {
            return;
        };
        let viewport_top = visible.y;
        let viewport_bottom = visible.y + visible.height;

        draw_background(renderer, bounds, theme::BG_BASE);

        let text_rect = text_area_rect(bounds, self.h_padding, self.v_padding, gutter_width);
        let text_x = text_rect.x;
        let text_y = text_rect.y;
        let text_area_width = text_rect.width;
        let text_area_height = text_rect.height;

        let text_clip = text_rect;

        let buffer_for_draw = match &state.shape_cache {
            Some(entry) => entry.buffer.clone(),
            None => return,
        };

        // A background rectangle for every visual line, wrapped continuations included
        // (unlike the gutter below, backgrounds cover the full visible span).
        for run in buffer_for_draw.layout_runs() {
            // Cull off-screen runs: layout_runs yields in ascending y order.
            let run_top = text_y + run.line_top;
            let run_bottom = run_top + run.line_height;
            if run_bottom <= viewport_top {
                continue;
            }
            if run_top >= viewport_bottom {
                break;
            }

            if run.line_i >= self.data.line_kinds.len() {
                continue;
            }

            let bg_color = match self.data.line_kinds[run.line_i] {
                Some(DiffLineKind::Added) => Some(theme::DIFF_ADDED_TINT),
                Some(DiffLineKind::Removed) => Some(theme::DIFF_REMOVED_TINT),
                _ => None, // context or hunk header — no tint
            };

            if let Some(color) = bg_color {
                draw_highlight_background(
                    renderer,
                    text_clip,
                    text_x,
                    text_y,
                    &run,
                    0.0,
                    text_area_width,
                    color,
                );
            }
        }

        let number_color = theme::TEXT_MUTED;
        let gutter_clip = gutter_clip_rect(
            bounds,
            self.h_padding,
            self.v_padding,
            gutter_width,
            text_area_height,
        );

        // Only the first visual run of each logical line gets its numbers.
        // `last_drawn_line` updates for every run, including off-screen ones above the
        // viewport, so a wrapped line whose first run is scrolled out never draws its
        // number on a visible continuation.
        let mut last_drawn_line = usize::MAX;
        for run in buffer_for_draw.layout_runs() {
            if run.line_i == last_drawn_line {
                continue;
            }
            last_drawn_line = run.line_i;

            // Cull off-screen runs (ascending y order).
            let run_top = text_y + run.line_top;
            let run_bottom = run_top + run.line_height;
            if run_bottom <= viewport_top {
                continue;
            }
            if run_top >= viewport_bottom {
                break;
            }

            if run.line_i >= self.data.line_numbers.len() {
                continue;
            }

            let (old_num, new_num) = self.data.line_numbers[run.line_i];

            let half_gutter = gutter_width / 2.0;
            let (old_right_x, new_right_x) =
                gutter_column_right_edges(bounds.x, self.h_padding, gutter_width);

            let old_str = old_num.map_or_else(String::new, |n| n.to_string());
            if !old_str.is_empty() {
                let num_text = text::Text {
                    content: old_str,
                    bounds: Size::new(half_gutter, run.line_height),
                    size: iced::Pixels(GUTTER_FONT_SIZE),
                    line_height: text::LineHeight::Relative(1.3),
                    font: theme::FONT_REGULAR,
                    align_x: iced::alignment::Horizontal::Right.into(),
                    align_y: iced::alignment::Vertical::Center,
                    shaping: text::Shaping::Advanced,
                    wrapping: text::Wrapping::None,
                };
                renderer.fill_text(
                    num_text,
                    Point::new(old_right_x, text_y + run.line_top + run.line_height / 2.0),
                    number_color,
                    gutter_clip,
                );
            }

            let new_str = new_num.map_or_else(String::new, |n| n.to_string());
            if !new_str.is_empty() {
                let num_text = text::Text {
                    content: new_str,
                    bounds: Size::new(half_gutter, run.line_height),
                    size: iced::Pixels(GUTTER_FONT_SIZE),
                    line_height: text::LineHeight::Relative(1.3),
                    font: theme::FONT_REGULAR,
                    align_x: iced::alignment::Horizontal::Right.into(),
                    align_y: iced::alignment::Vertical::Center,
                    shaping: text::Shaping::Advanced,
                    wrapping: text::Wrapping::None,
                };
                renderer.fill_text(
                    num_text,
                    Point::new(new_right_x, text_y + run.line_top + run.line_height / 2.0),
                    number_color,
                    gutter_clip,
                );
            }
        }

        if has_selection(state.sel_anchor, state.sel_cursor) {
            let (anchor, cursor) = (state.sel_anchor.unwrap(), state.sel_cursor.unwrap());
            let (start, end) = if anchor < cursor {
                (anchor, cursor)
            } else {
                (cursor, anchor)
            };
            let start_cur = global_byte_to_cursor(&buffer_for_draw, start);
            let end_cur = global_byte_to_cursor(&buffer_for_draw, end);
            let filter = move |_run: &cosmic_text::LayoutRun| {
                Some((
                    (start_cur.line, start_cur.index),
                    (end_cur.line, end_cur.index),
                ))
            };
            draw_run_highlights(
                renderer,
                &buffer_for_draw,
                text_clip,
                text_x,
                text_y,
                SELECTION_COLOR,
                false,
                Some((viewport_top, viewport_bottom)),
                filter,
            );
        }

        draw_buffer_text(
            renderer,
            &buffer_for_draw,
            Point::new(text_x, text_y),
            text_clip,
        );
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, super::diff::DiffMessage>,
        _viewport: &Rectangle,
    ) {
        let state = tree.state.downcast_mut::<DiffBufferState>();
        let buffer = match &state.shape_cache {
            Some(entry) => entry.buffer.clone(),
            None => return,
        };

        match event {
            Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Left)) => {
                if let Some(byte) = hit_test(
                    &buffer,
                    layout,
                    cursor,
                    state.gutter_width,
                    self.h_padding,
                    self.v_padding,
                ) {
                    state.mouse_held = true;
                    state.sel_anchor = Some(byte);
                    state.sel_cursor = Some(byte);
                } else {
                    state.mouse_held = false;
                    state.sel_anchor = None;
                    state.sel_cursor = None;
                }
                shell.request_redraw();
            }

            Event::Mouse(iced::mouse::Event::ButtonReleased(iced::mouse::Button::Left)) => {
                state.mouse_held = false;
                if let (Some(a), Some(c)) = (state.sel_anchor, state.sel_cursor) {
                    if a == c {
                        state.sel_anchor = None;
                        state.sel_cursor = None;
                    }
                }
                shell.request_redraw();
            }

            Event::Mouse(iced::mouse::Event::CursorMoved { .. }) if state.mouse_held => {
                if let Some(byte) = hit_test(
                    &buffer,
                    layout,
                    cursor,
                    state.gutter_width,
                    self.h_padding,
                    self.v_padding,
                ) {
                    state.sel_cursor = Some(byte);
                    shell.request_redraw();
                }
            }

            Event::Keyboard(keyboard::Event::KeyPressed {
                key: key_press,
                modifiers,
                physical_key,
                ..
            }) => {
                let is_clipboard_mod =
                    super::detect_keyboard_mods(*modifiers).is_text_platform_mod();

                if is_clipboard_mod
                    && key_press.to_latin(*physical_key) == Some('c')
                    && let (Some(anchor), Some(cursor_byte)) = (state.sel_anchor, state.sel_cursor)
                    && let Some(text) = selection_text(&self.data.text, anchor, cursor_byte)
                {
                    clipboard.write(iced::advanced::clipboard::Kind::Standard, text);
                }
            }

            _ => {}
        }
    }

    fn mouse_interaction(
        &self,
        _tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _viewport: &Rectangle,
        _renderer: &Renderer,
    ) -> mouse::Interaction {
        let bounds = layout.bounds();
        if cursor.position_over(bounds).is_some() {
            mouse::Interaction::Text
        } else {
            mouse::Interaction::default()
        }
    }
}

/// Build per-file [`DiffFileBuffer`] data from [`super::diff::DiffFile`]s, called in `update()`
/// when diff data or file selection changes and consumed by [`DiffBufferWidget`] in `view()`.
///
/// With `limits` as `Some((max_hunks, max_lines))`, building stops once cumulative hunk/line counts
/// would exceed the caps (matching view truncation).
#[must_use]
pub fn build_file_buffers(
    diff_files: &[super::diff::DiffFile],
    selected_file: Option<&str>,
    limits: Option<(usize, usize)>,
) -> Vec<DiffFileBuffer> {
    // Single source of truth for truncation — shared with build_diff_content.
    // compute_truncation_index already handles `None` limits internally.
    let truncate_at = super::diff::compute_truncation_index(diff_files, selected_file, limits);
    let mut buffers: Vec<DiffFileBuffer> = Vec::new();

    for (idx, file) in diff_files.iter().enumerate() {
        if !super::diff::file_matches_selection(file, selected_file) {
            continue;
        }

        // Truncation check — use the pre-computed index from the shared helper.
        if let Some(limit) = truncate_at {
            if idx >= limit {
                break;
            }
        }

        // File headers, binary, too-large — these are rendered as Iced
        // widgets interleaved with DiffBufferWidgets. We skip buffer
        // construction for binary and too-large files.
        if !file.has_parseable_content() {
            continue;
        }

        buffers.push(build_single_file_buffer(file));
    }

    buffers
}

fn build_single_file_buffer(file: &super::diff::DiffFile) -> DiffFileBuffer {
    let mut text = String::new();
    // Pre-allocate: rough estimate of 80 bytes per line
    let estimated_lines: usize = file
        .hunks
        .iter()
        .map(|h| h.lines.len() + 1) // +1 for hunk header
        .sum();
    text.reserve(estimated_lines * 80);

    let mut span_data: Vec<(usize, usize, Color)> = Vec::new();
    let mut line_kinds: Vec<Option<DiffLineKind>> = Vec::new();
    let mut line_numbers: Vec<(Option<usize>, Option<usize>)> = Vec::new();

    for hunk in &file.hunks {
        {
            let start = text.len();
            text.push_str(&hunk.header);
            text.push('\n');
            let end = text.len();
            span_data.push((start, end, HUNK_HEADER_COLOR));
            line_kinds.push(None);
            line_numbers.push((None, None));
        }

        for line in &hunk.lines {
            let start = text.len();
            let line_start = start;

            text.push(line.kind.prefix());
            text.push(' ');
            let content_start = text.len();

            text.push_str(&line.content);
            text.push('\n');
            let end = text.len();

            let fg_color = match line.kind {
                DiffLineKind::Added => ADDED_COLOR,
                DiffLineKind::Removed => REMOVED_COLOR,
                DiffLineKind::Context => CONTEXT_COLOR,
            };
            let kind = line.kind;

            let content_len = end - content_start;

            // Select highlight source based on line kind and file status
            let (highlights, hl_line_number) = match (line.kind, file.status) {
                (DiffLineKind::Removed, _) | (DiffLineKind::Context, DiffFileStatus::Deleted) => {
                    (file.old_highlights.as_ref(), line.old_line_number)
                }
                (DiffLineKind::Added | DiffLineKind::Context, _) => {
                    (file.new_highlights.as_ref(), line.new_line_number)
                }
            };

            let line_hl_spans = hl_line_number
                .and_then(|n| highlights.and_then(|h| h.spans.get(n.saturating_sub(1))));

            match line_hl_spans {
                Some(hl_spans) if !hl_spans.is_empty() => {
                    let mut cursor = content_start;
                    for s in hl_spans {
                        // s.start and s.end are relative to content start (0-based)
                        if s.start >= s.end || s.start >= content_len {
                            continue;
                        }
                        let abs_start = content_start + s.start.min(content_len);
                        let abs_end = content_start + s.end.min(content_len);
                        if abs_start > cursor {
                            span_data.push((cursor, abs_start, fg_color));
                        }
                        if abs_end > abs_start {
                            span_data.push((abs_start, abs_end, s.highlight_class.color()));
                            cursor = abs_end;
                        }
                    }
                    if cursor < end {
                        span_data.push((cursor, end, fg_color));
                    }
                    span_data.push((line_start, content_start, fg_color));
                }
                _ => {
                    span_data.push((line_start, end, fg_color));
                }
            }

            line_kinds.push(Some(kind));
            line_numbers.push((line.old_line_number, line.new_line_number));
        }
    }

    // Sort span_data by start byte (they may be out of order due to
    // prefix being pushed last in the highlighted case)
    span_data.sort_by_key(|(start, _, _)| *start);

    let gutter_digits = compute_gutter_digits(&line_numbers);
    let content_fingerprint =
        compute_content_fingerprint(&text, &span_data, &line_kinds, &line_numbers, gutter_digits);

    DiffFileBuffer {
        text,
        span_data,
        line_kinds,
        line_numbers,
        gutter_digits,
        content_fingerprint,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::diff_parse::DiffFileStatus::Modified;
    use crate::git::diff_parse::DiffLineKind::{Added, Context, Removed};
    use crate::git::diff_parse::{DiffContent, DiffFileStatus, DiffLine, DiffLineKind};

    fn make_test_diff_file(
        path: &str,
        hunks: Vec<crate::git::diff_parse::DiffHunk>,
        status: DiffFileStatus,
    ) -> super::super::diff::DiffFile {
        super::super::diff::DiffFile::from_parsed(
            crate::git::diff_parse::DiffFile::new(path.to_string(), hunks, status),
            None,
            None,
        )
    }

    fn file_with_content(path: &str, content: DiffContent) -> super::super::diff::DiffFile {
        super::super::diff::DiffFile::from_parsed(
            crate::git::diff_parse::DiffFile {
                path: path.to_string(),
                old_path: None,
                hunks: Vec::new(),
                status: Modified,
                content,
            },
            None,
            None,
        )
    }

    fn make_line(
        kind: DiffLineKind,
        content: &str,
        old: Option<usize>,
        new: Option<usize>,
    ) -> DiffLine {
        DiffLine {
            kind,
            old_line_number: old,
            new_line_number: new,
            content: content.to_string(),
        }
    }

    fn make_hunk(header: &str, lines: Vec<DiffLine>) -> crate::git::diff_parse::DiffHunk {
        crate::git::diff_parse::DiffHunk {
            header: header.to_string(),
            lines,
        }
    }

    fn single_hunk_file(path: &str, header: &str, line: DiffLine) -> super::super::diff::DiffFile {
        make_test_diff_file(path, vec![make_hunk(header, vec![line])], Modified)
    }

    fn hunk_file(path: &str, header: &str, lines: Vec<DiffLine>) -> super::super::diff::DiffFile {
        make_test_diff_file(path, vec![make_hunk(header, lines)], Modified)
    }

    /// Every buffer's spans cover the whole text, stay inside it, and are sorted.
    fn assert_span_invariants(name: &str, buffers: &[DiffFileBuffer]) {
        for buf in buffers {
            for &(start, end, _) in &buf.span_data {
                assert!(start <= end, "case {name}: span start {start} > end {end}");
            }
            let total: usize = buf.span_data.iter().map(|(s, e, _)| e - s).sum();
            assert_eq!(total, buf.text.len(), "case {name}: span coverage");
            let starts: Vec<usize> = buf.span_data.iter().map(|(s, _, _)| *s).collect();
            assert!(
                starts.windows(2).all(|w| w[0] <= w[1]),
                "case {name}: spans sorted"
            );
            for &(start, end, _) in &buf.span_data {
                assert!(end <= buf.text.len(), "case {name}: span end {end}");
                assert!(
                    buf.text.is_char_boundary(start) && buf.text.is_char_boundary(end),
                    "case {name}: span boundaries"
                );
            }
        }
    }

    fn run_buffer_cases(cases: &[Case]) {
        for case in cases {
            let name = case.name;
            let buffers = build_file_buffers(&case.files, case.selected, None);
            assert_eq!(buffers.len(), case.buffers, "case {name}: buffers");
            let first = || {
                buffers
                    .first()
                    .unwrap_or_else(|| panic!("case {name}: no buffers built"))
            };
            if let Some(kinds) = case.kinds {
                assert_eq!(first().line_kinds, kinds, "case {name}: kinds");
            }
            if let Some(numbers) = case.numbers {
                assert_eq!(first().line_numbers, numbers, "case {name}: numbers");
            }
            if let Some(prefix) = case.starts_with {
                assert!(
                    first().text.starts_with(prefix),
                    "case {name}: prefix {prefix:?}"
                );
            }
            for text in case.contains {
                assert!(first().text.contains(text), "case {name}: {text:?}");
            }
            assert_span_invariants(name, &buffers);
        }
    }

    // One row shape for both buffer tables; absent columns fall back to Default.
    #[derive(Default)]
    struct Case {
        name: &'static str,
        files: Vec<super::super::diff::DiffFile>,
        selected: Option<&'static str>,
        buffers: usize,
        kinds: Option<&'static [Option<DiffLineKind>]>,
        numbers: Option<&'static [(Option<usize>, Option<usize>)]>,
        starts_with: Option<&'static str>,
        contains: &'static [&'static str],
    }

    #[test]
    fn test_build_file_buffers() {
        let cases: &[Case] = &[
            Case {
                name: "empty file has no buffers",
                ..Case::default()
            },
            Case {
                name: "binary file skipped",
                files: vec![file_with_content("binary.bin", DiffContent::Binary)],
                ..Case::default()
            },
            Case {
                name: "too large file skipped",
                files: vec![file_with_content(
                    "large.bin",
                    DiffContent::TooLarge(5_000_000),
                )],
                ..Case::default()
            },
            Case {
                name: "selected file filter",
                files: vec![
                    single_hunk_file(
                        "a.rs",
                        "@@ -1,3 +1,3 @@",
                        make_line(Context, "line1", Some(1), Some(1)),
                    ),
                    single_hunk_file(
                        "b.rs",
                        "@@ -1,2 +1,2 @@",
                        make_line(Added, "new", None, Some(1)),
                    ),
                ],
                selected: Some("b.rs"),
                buffers: 1,
                kinds: Some(&[None, Some(Added)]),
                numbers: Some(&[(None, None), (None, Some(1))]),
                contains: &["new"],
                ..Case::default()
            },
        ];

        run_buffer_cases(cases);
    }

    #[test]
    fn test_build_file_buffer_text() {
        let cases: &[Case] = &[
            Case {
                name: "buffer text prefixes and line values",
                files: vec![hunk_file(
                    "test.rs",
                    "@@ -1,3 +1,4 @@ fn main() {",
                    vec![
                        make_line(Context, "let x = 1;", Some(1), Some(1)),
                        make_line(Removed, "let y = 2;", Some(2), None),
                        make_line(Added, "let z = 3;", None, Some(2)),
                    ],
                )],
                buffers: 1,
                kinds: Some(&[None, Some(Context), Some(Removed), Some(Added)]),
                numbers: Some(&[
                    (None, None),
                    (Some(1), Some(1)),
                    (Some(2), None),
                    (None, Some(2)),
                ]),
                starts_with: Some("@@ -1,3 +1,4 @@ fn main() {\n"),
                contains: &["  let x = 1;\n", "- let y = 2;\n", "+ let z = 3;\n"],
                ..Case::default()
            },
            Case {
                name: "multiple hunks produce correct line count",
                files: vec![make_test_diff_file(
                    "multi.rs",
                    vec![
                        make_hunk(
                            "@@ -1,2 +1,2 @@",
                            vec![
                                make_line(Context, "a", Some(1), Some(1)),
                                make_line(Context, "b", Some(2), Some(2)),
                            ],
                        ),
                        make_hunk(
                            "@@ -10,1 +10,1 @@",
                            vec![make_line(Removed, "old", Some(10), None)],
                        ),
                    ],
                    Modified,
                )],
                buffers: 1,
                kinds: Some(&[None, Some(Context), Some(Context), None, Some(Removed)]),
                numbers: Some(&[
                    (None, None),
                    (Some(1), Some(1)),
                    (Some(2), Some(2)),
                    (None, None),
                    (Some(10), None),
                ]),
                ..Case::default()
            },
        ];

        run_buffer_cases(cases);
    }
}