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
use std::io;
use serde::{Serialize, Deserialize};
use unicode_width::UnicodeWidthStr;
use crate::types::*;
use crate::tree::*;
use crate::util::infer_title_from_prompt;
pub fn cycle_top_layout(app: &mut AppState) {
let win = &mut app.windows[app.active_idx];
// toggle parent of active path, else toggle root
if !win.active_path.is_empty() {
let parent_path = &win.active_path[..win.active_path.len()-1].to_vec();
if let Some(Node::Split { kind, sizes, .. }) = get_split_mut(&mut win.root, &parent_path.to_vec()) {
*kind = match *kind { LayoutKind::Horizontal => LayoutKind::Vertical, LayoutKind::Vertical => LayoutKind::Horizontal };
*sizes = vec![50,50];
}
} else {
if let Node::Split { kind, sizes, .. } = &mut win.root { *kind = match *kind { LayoutKind::Horizontal => LayoutKind::Vertical, LayoutKind::Vertical => LayoutKind::Horizontal }; *sizes = vec![50,50]; }
}
}
#[derive(Serialize, Deserialize)]
pub struct CellJson { pub text: String, pub fg: String, pub bg: String, pub bold: bool, pub italic: bool, pub underline: bool, pub inverse: bool, pub dim: bool }
#[derive(Serialize, Deserialize)]
pub struct CellRunJson {
pub text: String,
pub fg: String,
pub bg: String,
pub flags: u8,
pub width: u16,
}
#[derive(Serialize, Deserialize)]
pub struct RowRunsJson {
pub runs: Vec<CellRunJson>,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum LayoutJson {
#[serde(rename = "split")]
Split { kind: String, sizes: Vec<u16>, children: Vec<LayoutJson> },
#[serde(rename = "leaf")]
Leaf {
id: usize,
rows: u16,
cols: u16,
cursor_row: u16,
cursor_col: u16,
#[serde(default)]
alternate_screen: bool,
active: bool,
copy_mode: bool,
scroll_offset: usize,
sel_start_row: Option<u16>,
sel_start_col: Option<u16>,
sel_end_row: Option<u16>,
sel_end_col: Option<u16>,
#[serde(default)]
content: Vec<Vec<CellJson>>,
#[serde(default)]
rows_v2: Vec<RowRunsJson>,
},
}
pub fn dump_layout_json(app: &mut AppState) -> io::Result<String> {
let in_copy_mode = matches!(app.mode, Mode::CopyMode);
let scroll_offset = app.copy_scroll_offset;
fn build(node: &mut Node, cur_path: &mut Vec<usize>, active_path: &[usize], include_full_content: bool) -> LayoutJson {
match node {
Node::Split { kind, sizes, children } => {
let k = match *kind { LayoutKind::Horizontal => "Horizontal".to_string(), LayoutKind::Vertical => "Vertical".to_string() };
let mut ch: Vec<LayoutJson> = Vec::new();
for (i, c) in children.iter_mut().enumerate() {
cur_path.push(i);
ch.push(build(c, cur_path, active_path, include_full_content));
cur_path.pop();
}
LayoutJson::Split { kind: k, sizes: sizes.clone(), children: ch }
}
Node::Leaf(p) => {
const FLAG_DIM: u8 = 1;
const FLAG_BOLD: u8 = 2;
const FLAG_ITALIC: u8 = 4;
const FLAG_UNDERLINE: u8 = 8;
const FLAG_INVERSE: u8 = 16;
let parser = p.term.lock().unwrap();
let screen = parser.screen();
let (cr, cc) = screen.cursor_position();
// ConPTY never passes through ESC[?1049h, so alternate_screen()
// is always false. Use a heuristic instead: if the last row of
// the screen has non-blank content, this is a fullscreen TUI app.
let alternate_screen = screen.alternate_screen() || {
let last_row = p.last_rows.saturating_sub(1);
let mut has_content = false;
for col in 0..p.last_cols {
if let Some(cell) = screen.cell(last_row, col) {
let t = cell.contents();
if !t.is_empty() && t != " " {
has_content = true;
break;
}
}
}
has_content
};
// Throttle infer_title_from_prompt — expensive scan, only needed for display
let now = std::time::Instant::now();
if now.duration_since(p.last_infer_title).as_millis() >= 500 {
if let Some(t) = infer_title_from_prompt(&screen, p.last_rows, p.last_cols) { p.title = t; }
p.last_infer_title = now;
}
let need_full_content = include_full_content && *cur_path == active_path;
let mut lines: Vec<Vec<CellJson>> = if need_full_content {
Vec::with_capacity(p.last_rows as usize)
} else {
Vec::new()
};
let mut rows_v2: Vec<RowRunsJson> = Vec::with_capacity(p.last_rows as usize);
for r in 0..p.last_rows {
let mut row: Vec<CellJson> = if need_full_content {
Vec::with_capacity(p.last_cols as usize)
} else {
Vec::new()
};
let mut runs: Vec<CellRunJson> = Vec::new();
let mut c = 0;
// Track previous cell's raw color enums for run-merging
// without allocating strings on every cell.
let mut prev_fg_raw: Option<vt100::Color> = None;
let mut prev_bg_raw: Option<vt100::Color> = None;
let mut prev_flags: u8 = 0;
while c < p.last_cols {
// Process each cell inline to avoid per-cell String allocation.
// The &str from cell.contents() can only be used inside the
// if-let block (borrows from parser), so run-merging happens
// here too — push_str(&str) avoids allocation for merged cells.
let (width, cell_fg_raw, cell_bg_raw, flags) = if let Some(cell) = screen.cell(r, c) {
let t = cell.contents();
let t = if t.is_empty() { " " } else { t };
let cell_fg = cell.fgcolor();
let cell_bg = cell.bgcolor();
let mut w = UnicodeWidthStr::width(t) as u16;
if w == 0 { w = 1; }
let mut fl = 0u8;
if cell.dim() { fl |= FLAG_DIM; }
if cell.bold() { fl |= FLAG_BOLD; }
if cell.italic() { fl |= FLAG_ITALIC; }
if cell.underline() { fl |= FLAG_UNDERLINE; }
if cell.inverse() { fl |= FLAG_INVERSE; }
// Run merging — push &str directly, no String allocation
let merged = if let Some(last) = runs.last_mut() {
if prev_fg_raw == Some(cell_fg) && prev_bg_raw == Some(cell_bg) && prev_flags == fl {
last.text.push_str(t);
last.width = last.width.saturating_add(w);
true
} else { false }
} else { false };
if !merged {
let fg = crate::util::color_to_name(cell_fg);
let bg = crate::util::color_to_name(cell_bg);
runs.push(CellRunJson { text: t.to_string(), fg: fg.into_owned(), bg: bg.into_owned(), flags: fl, width: w });
}
if need_full_content {
let fg_str = crate::util::color_to_name(cell_fg).into_owned();
let bg_str = crate::util::color_to_name(cell_bg).into_owned();
row.push(CellJson {
text: t.to_string(), fg: fg_str.clone(), bg: bg_str.clone(),
bold: cell.bold(), italic: cell.italic(),
underline: cell.underline(), inverse: cell.inverse(), dim: cell.dim(),
});
for _ in 1..w {
row.push(CellJson {
text: String::new(), fg: fg_str.clone(), bg: bg_str.clone(),
bold: cell.bold(), italic: cell.italic(),
underline: cell.underline(), inverse: cell.inverse(), dim: cell.dim(),
});
}
}
(w, cell_fg, cell_bg, fl)
} else {
// No cell — default space
let merged = if let Some(last) = runs.last_mut() {
if prev_fg_raw == Some(vt100::Color::Default) && prev_bg_raw == Some(vt100::Color::Default) && prev_flags == 0 {
last.text.push(' ');
last.width = last.width.saturating_add(1);
true
} else { false }
} else { false };
if !merged {
runs.push(CellRunJson { text: " ".to_string(), fg: "default".to_string(), bg: "default".to_string(), flags: 0, width: 1 });
}
if need_full_content {
row.push(CellJson {
text: " ".to_string(), fg: "default".to_string(), bg: "default".to_string(),
bold: false, italic: false, underline: false, inverse: false, dim: false,
});
}
(1u16, vt100::Color::Default, vt100::Color::Default, 0u8)
};
prev_fg_raw = Some(cell_fg_raw);
prev_bg_raw = Some(cell_bg_raw);
prev_flags = flags;
c = c.saturating_add(width.max(1));
}
if need_full_content {
while row.len() < p.last_cols as usize {
row.push(CellJson {
text: " ".to_string(),
fg: "default".to_string(),
bg: "default".to_string(),
bold: false,
italic: false,
underline: false,
inverse: false,
dim: false,
});
}
lines.push(row);
}
rows_v2.push(RowRunsJson { runs });
}
LayoutJson::Leaf {
id: p.id,
rows: p.last_rows,
cols: p.last_cols,
cursor_row: cr,
cursor_col: cc,
alternate_screen,
active: false,
copy_mode: false,
scroll_offset: 0,
sel_start_row: None,
sel_start_col: None,
sel_end_row: None,
sel_end_col: None,
content: lines,
rows_v2,
}
}
}
}
let win = &mut app.windows[app.active_idx];
let mut path = Vec::new();
let mut root = build(&mut win.root, &mut path, &win.active_path, in_copy_mode);
// Mark the active pane and set copy mode info
fn mark_active(
node: &mut LayoutJson,
path: &[usize],
idx: usize,
in_copy_mode: bool,
scroll_offset: usize,
copy_anchor: Option<(u16, u16)>,
copy_pos: Option<(u16, u16)>,
) {
match node {
LayoutJson::Leaf {
active,
copy_mode,
scroll_offset: so,
sel_start_row,
sel_start_col,
sel_end_row,
sel_end_col,
..
} => {
let is_active = idx >= path.len();
*active = is_active;
if is_active {
*copy_mode = in_copy_mode;
*so = scroll_offset;
if in_copy_mode {
if let (Some((ar, ac)), Some((pr, pc))) = (copy_anchor, copy_pos) {
*sel_start_row = Some(ar.min(pr));
*sel_start_col = Some(ac.min(pc));
*sel_end_row = Some(ar.max(pr));
*sel_end_col = Some(ac.max(pc));
} else {
*sel_start_row = None;
*sel_start_col = None;
*sel_end_row = None;
*sel_end_col = None;
}
} else {
*sel_start_row = None;
*sel_start_col = None;
*sel_end_row = None;
*sel_end_col = None;
}
}
}
LayoutJson::Split { children, .. } => {
if idx < path.len() {
if let Some(child) = children.get_mut(path[idx]) {
mark_active(child, path, idx + 1, in_copy_mode, scroll_offset, copy_anchor, copy_pos);
}
}
}
}
}
mark_active(
&mut root,
&win.active_path,
0,
in_copy_mode,
scroll_offset,
app.copy_anchor,
app.copy_pos,
);
let s = serde_json::to_string(&root).map_err(|e| io::Error::new(io::ErrorKind::Other, format!("json error: {e}")))?;
Ok(s)
}
/// Direct JSON serialisation of the layout tree – writes JSON straight into
/// a pre-allocated `String`, avoiding the intermediate `LayoutJson` / `CellRunJson`
/// allocations **and** the `serde_json::to_string` traversal. Produces the
/// identical JSON format that the client deserialises into `LayoutJson`.
pub fn dump_layout_json_fast(app: &mut AppState) -> io::Result<String> {
let in_copy = matches!(app.mode, Mode::CopyMode);
let scroll_off = app.copy_scroll_offset;
let anchor = app.copy_anchor;
let cpos = app.copy_pos;
// ── tiny helpers (no captures needed, so plain `fn` items) ───────
/// Append the JSON-escaped form of `s` into `out`.
fn json_esc(s: &str, out: &mut String) {
// Fast path – most cell text needs no escaping.
if !s.bytes().any(|b| b == b'"' || b == b'\\' || b < 0x20) {
out.push_str(s);
return;
}
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => {
let _ = std::fmt::Write::write_fmt(out, format_args!("\\u{:04x}", c as u32));
}
c => out.push(c),
}
}
}
/// Append a `vt100::Color` as its JSON string value (**no** surrounding quotes).
fn push_color(c: vt100::Color, out: &mut String) {
match c {
vt100::Color::Default => out.push_str("default"),
vt100::Color::Idx(i) => {
let _ = std::fmt::Write::write_fmt(out, format_args!("idx:{}", i));
}
vt100::Color::Rgb(r, g, b) => {
let _ = std::fmt::Write::write_fmt(out, format_args!("rgb:{},{},{}", r, g, b));
}
}
}
/// Close the currently-open run: closing `"` for text, then fg/bg/flags/width, then `}`.
fn close_run(fg: vt100::Color, bg: vt100::Color, fl: u8, w: u16, out: &mut String) {
out.push_str("\",\"fg\":\"");
push_color(fg, out);
out.push_str("\",\"bg\":\"");
push_color(bg, out);
let _ = std::fmt::Write::write_fmt(out, format_args!("\",\"flags\":{},\"width\":{}}}", fl, w));
}
// ── recursive tree walker ────────────────────────────────────────
fn write_node(
node: &mut Node,
cur_path: &mut Vec<usize>,
active_path: &[usize],
in_copy: bool,
scroll_off: usize,
anchor: Option<(u16, u16)>,
cpos: Option<(u16, u16)>,
out: &mut String,
) {
match node {
Node::Split { kind, sizes, children } => {
out.push_str("{\"type\":\"split\",\"kind\":\"");
match kind {
LayoutKind::Horizontal => out.push_str("Horizontal"),
LayoutKind::Vertical => out.push_str("Vertical"),
}
out.push_str("\",\"sizes\":[");
for (i, s) in sizes.iter().enumerate() {
if i > 0 { out.push(','); }
let _ = std::fmt::Write::write_fmt(out, format_args!("{}", s));
}
out.push_str("],\"children\":[");
for (i, c) in children.iter_mut().enumerate() {
if i > 0 { out.push(','); }
cur_path.push(i);
write_node(c, cur_path, active_path, in_copy, scroll_off, anchor, cpos, out);
cur_path.pop();
}
out.push_str("]}");
}
Node::Leaf(p) => {
const FLAG_DIM: u8 = 1;
const FLAG_BOLD: u8 = 2;
const FLAG_ITALIC: u8 = 4;
const FLAG_UNDERLINE: u8 = 8;
const FLAG_INVERSE: u8 = 16;
let is_active = cur_path.as_slice() == active_path;
let need_content = in_copy && is_active;
// ── Snapshot cell data under the mutex, then release ──
// This minimises the time we block the reader thread (which
// also holds p.term's mutex while processing ConPTY output).
// Without this, WSL echo gets starved because its output sits
// in the ConPTY pipe while we build the JSON string.
struct Run { text: String, fg: vt100::Color, bg: vt100::Color, flags: u8, width: u16 }
struct RowSnap { runs: Vec<Run> }
struct CopyCell { text: String, fg: vt100::Color, bg: vt100::Color, bold: bool, italic: bool, underline: bool, inverse: bool, dim: bool, width: u16 }
struct LeafSnap {
cr: u16, cc: u16, alt: bool,
rows_v2: Vec<RowSnap>,
content: Vec<Vec<CopyCell>>,
}
let snap = {
let parser = p.term.lock().unwrap();
let screen = parser.screen();
let (cr, cc) = screen.cursor_position();
// Alternate-screen heuristic
let alt = screen.alternate_screen() || {
let lr = p.last_rows.saturating_sub(1);
(0..p.last_cols).any(|col| {
screen.cell(lr, col).map_or(false, |c| {
let t = c.contents();
!t.is_empty() && t != " "
})
})
};
// Throttled title inference (still under lock, but only every 500ms)
let now = std::time::Instant::now();
if now.duration_since(p.last_infer_title).as_millis() >= 500 {
if let Some(t) = infer_title_from_prompt(screen, p.last_rows, p.last_cols) {
p.title = t;
}
p.last_infer_title = now;
}
// Snapshot rows_v2 (run-merged)
let mut snap_rows: Vec<RowSnap> = Vec::with_capacity(p.last_rows as usize);
for r in 0..p.last_rows {
let mut runs: Vec<Run> = Vec::new();
let mut c = 0u16;
let mut prev_fg: Option<vt100::Color> = None;
let mut prev_bg: Option<vt100::Color> = None;
let mut prev_fl: u8 = 0;
while c < p.last_cols {
if let Some(cell) = screen.cell(r, c) {
let t = cell.contents();
let t = if t.is_empty() { " " } else { t };
let cfg = cell.fgcolor();
let cbg = cell.bgcolor();
let mut w = UnicodeWidthStr::width(t) as u16;
if w == 0 { w = 1; }
let mut fl = 0u8;
if cell.dim() { fl |= FLAG_DIM; }
if cell.bold() { fl |= FLAG_BOLD; }
if cell.italic(){ fl |= FLAG_ITALIC; }
if cell.underline() { fl |= FLAG_UNDERLINE; }
if cell.inverse() { fl |= FLAG_INVERSE; }
if prev_fg == Some(cfg) && prev_bg == Some(cbg) && prev_fl == fl {
if let Some(last) = runs.last_mut() {
last.text.push_str(t);
last.width += w;
}
} else {
runs.push(Run { text: t.to_string(), fg: cfg, bg: cbg, flags: fl, width: w });
}
prev_fg = Some(cfg);
prev_bg = Some(cbg);
prev_fl = fl;
c += w.max(1);
} else {
let cfg = vt100::Color::Default;
let cbg = vt100::Color::Default;
let fl = 0u8;
if prev_fg == Some(cfg) && prev_bg == Some(cbg) && prev_fl == fl {
if let Some(last) = runs.last_mut() {
last.text.push(' ');
last.width += 1;
}
} else {
runs.push(Run { text: " ".to_string(), fg: cfg, bg: cbg, flags: fl, width: 1 });
}
prev_fg = Some(cfg);
prev_bg = Some(cbg);
prev_fl = fl;
c += 1;
}
}
snap_rows.push(RowSnap { runs });
}
// Snapshot content (copy-mode only)
let mut snap_content: Vec<Vec<CopyCell>> = Vec::new();
if need_content {
for r in 0..p.last_rows {
let mut row_cells: Vec<CopyCell> = Vec::new();
let mut c = 0u16;
while c < p.last_cols {
if let Some(cell) = screen.cell(r, c) {
let t = cell.contents();
let t = if t.is_empty() { " " } else { t };
let w = UnicodeWidthStr::width(t).max(1) as u16;
row_cells.push(CopyCell {
text: t.to_string(), fg: cell.fgcolor(), bg: cell.bgcolor(),
bold: cell.bold(), italic: cell.italic(), underline: cell.underline(),
inverse: cell.inverse(), dim: cell.dim(), width: w,
});
c += w;
} else {
row_cells.push(CopyCell {
text: " ".to_string(), fg: vt100::Color::Default, bg: vt100::Color::Default,
bold: false, italic: false, underline: false, inverse: false, dim: false, width: 1,
});
c += 1;
}
}
snap_content.push(row_cells);
}
}
LeafSnap { cr, cc, alt, rows_v2: snap_rows, content: snap_content }
};
// ── Parser mutex is now RELEASED ──
// All JSON string building below happens without holding the lock,
// so the reader thread can process ConPTY output concurrently.
// ── leaf header ──────────────────────────────────────
let so = if is_active && in_copy { scroll_off } else { 0 };
let _ = std::fmt::Write::write_fmt(out, format_args!(
concat!(
"{{\"type\":\"leaf\",\"id\":{},",
"\"rows\":{},\"cols\":{},",
"\"cursor_row\":{},\"cursor_col\":{},",
"\"alternate_screen\":{},",
"\"active\":{},\"copy_mode\":{},",
"\"scroll_offset\":{},"),
p.id, p.last_rows, p.last_cols,
snap.cr, snap.cc, snap.alt, is_active, need_content, so,
));
// selection bounds
if is_active && in_copy {
if let (Some((ar, ac)), Some((pr, pc))) = (anchor, cpos) {
let _ = std::fmt::Write::write_fmt(out, format_args!(
"\"sel_start_row\":{},\"sel_start_col\":{},\"sel_end_row\":{},\"sel_end_col\":{},",
ar.min(pr), ac.min(pc), ar.max(pr), ac.max(pc),
));
} else {
out.push_str("\"sel_start_row\":null,\"sel_start_col\":null,\"sel_end_row\":null,\"sel_end_col\":null,");
}
} else {
out.push_str("\"sel_start_row\":null,\"sel_start_col\":null,\"sel_end_row\":null,\"sel_end_col\":null,");
}
// ── content (per-cell, only in copy-mode active pane) ──
if need_content && !snap.content.is_empty() {
out.push_str("\"content\":[");
for (ri, row) in snap.content.iter().enumerate() {
if ri > 0 { out.push(','); }
out.push('[');
for (ci, cell) in row.iter().enumerate() {
if ci > 0 { out.push(','); }
out.push_str("{\"text\":\"");
json_esc(&cell.text, out);
out.push_str("\",\"fg\":\"");
push_color(cell.fg, out);
out.push_str("\",\"bg\":\"");
push_color(cell.bg, out);
let _ = std::fmt::Write::write_fmt(out, format_args!(
"\",\"bold\":{},\"italic\":{},\"underline\":{},\"inverse\":{},\"dim\":{}}}",
cell.bold, cell.italic, cell.underline, cell.inverse, cell.dim,
));
// Emit width-2 filler cells
for _ in 1..cell.width {
out.push_str(",{\"text\":\"\",\"fg\":\"");
push_color(cell.fg, out);
out.push_str("\",\"bg\":\"");
push_color(cell.bg, out);
let _ = std::fmt::Write::write_fmt(out, format_args!(
"\",\"bold\":{},\"italic\":{},\"underline\":{},\"inverse\":{},\"dim\":{}}}",
cell.bold, cell.italic, cell.underline, cell.inverse, cell.dim,
));
}
}
// pad to full column width
let total_w: u16 = row.iter().map(|c| c.width).sum();
for _ in total_w..p.last_cols {
out.push_str(",{\"text\":\" \",\"fg\":\"default\",\"bg\":\"default\",\"bold\":false,\"italic\":false,\"underline\":false,\"inverse\":false,\"dim\":false}");
}
out.push(']');
}
out.push_str("],");
} else {
out.push_str("\"content\":[],");
}
// ── rows_v2 (from snapshot, no mutex held) ───────────
out.push_str("\"rows_v2\":[");
for (ri, row) in snap.rows_v2.iter().enumerate() {
if ri > 0 { out.push(','); }
out.push_str("{\"runs\":[");
for (i, run) in row.runs.iter().enumerate() {
if i > 0 { out.push(','); }
out.push_str("{\"text\":\"");
json_esc(&run.text, out);
close_run(run.fg, run.bg, run.flags, run.width, out);
}
out.push_str("]}");
}
out.push_str("]}");
}
}
}
let win = &mut app.windows[app.active_idx];
let active_path = win.active_path.clone();
let mut path = Vec::new();
let mut out = String::with_capacity(32768);
write_node(
&mut win.root, &mut path, &active_path,
in_copy, scroll_off, anchor, cpos, &mut out,
);
Ok(out)
}
/// Apply a named layout to the current window
pub fn apply_layout(app: &mut AppState, layout: &str) {
let win = &mut app.windows[app.active_idx];
// Count panes
fn count_panes(node: &Node) -> usize {
match node {
Node::Leaf(_) => 1,
Node::Split { children, .. } => children.iter().map(count_panes).sum(),
}
}
let pane_count = count_panes(&win.root);
if pane_count < 2 { return; }
match layout.to_lowercase().as_str() {
"even-horizontal" | "even-h" => {
if let Node::Split { kind, sizes, .. } = &mut win.root {
*kind = LayoutKind::Horizontal;
let size = 100 / sizes.len().max(1) as u16;
for s in sizes.iter_mut() { *s = size; }
}
}
"even-vertical" | "even-v" => {
if let Node::Split { kind, sizes, .. } = &mut win.root {
*kind = LayoutKind::Vertical;
let size = 100 / sizes.len().max(1) as u16;
for s in sizes.iter_mut() { *s = size; }
}
}
"main-horizontal" | "main-h" => {
if let Node::Split { kind, sizes, .. } = &mut win.root {
*kind = LayoutKind::Vertical;
if sizes.len() >= 2 {
sizes[0] = 60;
let remaining = 40 / (sizes.len() - 1).max(1) as u16;
for s in sizes.iter_mut().skip(1) { *s = remaining; }
}
}
}
"main-vertical" | "main-v" => {
if let Node::Split { kind, sizes, .. } = &mut win.root {
*kind = LayoutKind::Horizontal;
if sizes.len() >= 2 {
sizes[0] = 60;
let remaining = 40 / (sizes.len() - 1).max(1) as u16;
for s in sizes.iter_mut().skip(1) { *s = remaining; }
}
}
}
"tiled" => {
if let Node::Split { sizes, .. } = &mut win.root {
let size = 100 / sizes.len().max(1) as u16;
for s in sizes.iter_mut() { *s = size; }
}
}
_ => {}
}
}
/// Cycle through available layouts
pub fn cycle_layout(app: &mut AppState) {
static LAYOUTS: [&str; 5] = ["even-horizontal", "even-vertical", "main-horizontal", "main-vertical", "tiled"];
let win = &app.windows[app.active_idx];
let (kind, sizes) = match &win.root {
Node::Leaf(_) => return,
Node::Split { kind, sizes, .. } => (*kind, sizes.clone()),
};
let current_idx = if sizes.is_empty() {
0
} else if sizes.iter().all(|s| *s == sizes[0]) {
match kind {
LayoutKind::Horizontal => 0,
LayoutKind::Vertical => 1,
}
} else if sizes.len() >= 2 && sizes[0] > sizes[1] {
match kind {
LayoutKind::Vertical => 2,
LayoutKind::Horizontal => 3,
}
} else {
4
};
let next_idx = (current_idx + 1) % LAYOUTS.len();
apply_layout(app, LAYOUTS[next_idx]);
}