Module: TUITD::ANSIParser

Defined in:
lib/tui_td/ansi_parser.rb

Overview

Parses raw terminal output (ANSI escape sequences + text) into a structured state representation.

Handles:

  • SGR (Select Graphic Rendition) — colors, bold, italic, underline

  • Cursor movement (CUU, CUD, CUF, CUB, CUP)

  • Erase (ED, EL)

  • Line feed, carriage return, backspace, tab

Output: [[{char, fg, bg, bold, italic, underline]], cursor: col, size: cols}

Constant Summary collapse

SGR_COLORS =
{
  0  => :reset,
  1  => :bold,
  3  => :italic,
  4  => :underline,
  5  => :blink,
  7  => :reverse,
  22 => :normal,
  23 => :no_italic,
  24 => :no_underline,
  30 => :black,
  31 => :red,
  32 => :green,
  33 => :yellow,
  34 => :blue,
  35 => :magenta,
  36 => :cyan,
  37 => :white,
  38 => :xterm_fg,  # 38;5;N or 38;2;R;G;B
  39 => :default_fg,
  40 => :bg_black,
  41 => :bg_red,
  42 => :bg_green,
  43 => :bg_yellow,
  44 => :bg_blue,
  45 => :bg_magenta,
  46 => :bg_cyan,
  47 => :bg_white,
  48 => :xterm_bg,  # 48;5;N or 48;2;R;G;B
  49 => :default_bg,
  90 => :bright_black,
  91 => :bright_red,
  92 => :bright_green,
  93 => :bright_yellow,
  94 => :bright_blue,
  95 => :bright_magenta,
  96 => :bright_cyan,
  97 => :bright_white,
  100 => :bg_bright_black,
  101 => :bg_bright_red,
  102 => :bg_bright_green,
  103 => :bg_bright_yellow,
  104 => :bg_bright_blue,
  105 => :bg_bright_magenta,
  106 => :bg_bright_cyan,
  107 => :bg_bright_white,
}.freeze
SGR_16_TO_NAME =
{
  0  => "black",
  1  => "red",
  2  => "green",
  3  => "yellow",
  4  => "blue",
  5  => "magenta",
  6  => "cyan",
  7  => "white",
  8  => "bright_black",
  9  => "bright_red",
  10 => "bright_green",
  11 => "bright_yellow",
  12 => "bright_blue",
  13 => "bright_magenta",
  14 => "bright_cyan",
  15 => "bright_white",
}.freeze
DEC_MAP =
{
  '`' => '',
  'a' => '',
  'b' => "\u2409",
  'c' => "\u240C",
  'd' => "\u240D",
  'e' => "\u240A",
  'f' => '°',
  'g' => '±',
  'h' => "\u2424",
  'i' => "\u240B",
  'j' => '',
  'k' => '',
  'l' => '',
  'm' => '',
  'n' => '',
  'o' => '',
  'p' => '',
  'q' => '',
  'r' => '',
  's' => '',
  't' => '',
  'u' => '',
  'v' => '',
  'w' => '',
  'x' => '',
  'y' => '',
  'z' => '',
  '{' => 'π',
  '|' => '',
  '}' => '£',
  '~' => '·'
}.freeze

Class Method Summary collapse

Class Method Details

._apply_csi(seq, cursor, attrs, grid, rows, cols, saved_cursor, scroll_region) ⇒ Object



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
# File 'lib/tui_td/ansi_parser.rb', line 415

def self._apply_csi(seq, cursor, attrs, grid, rows, cols, saved_cursor, scroll_region)
  # Strip leading escape char if present
  cleaned = seq.sub(/^\e/, "")
  match = cleaned.match(/^\[(\??)([\d;]*)( ?)([A-HJ-KP-SX@\`fhlmnRrsuq])$/)
  return [false, nil, {}] unless match

  is_private = (match[1] == "?")
  params = match[2].split(";").map(&:to_i)
  space = match[3]
  command = match[4]

  new_saved = nil
  action = {}

  case command
  when "m"
    _apply_sgr(params, attrs)
  when "A" # CUU — Cursor Up
    n = params[0] || 1
    n = 1 if n == 0
    cursor[:row] = [cursor[:row] - n, 0].max
  when "B" # CUD — Cursor Down
    n = params[0] || 1
    n = 1 if n == 0
    cursor[:row] = [cursor[:row] + n, rows - 1].min
  when "C" # CUF — Cursor Forward
    n = params[0] || 1
    n = 1 if n == 0
    cursor[:col] = [cursor[:col] + n, cols - 1].min
  when "D" # CUB — Cursor Back
    n = params[0] || 1
    n = 1 if n == 0
    cursor[:col] = [cursor[:col] - n, 0].max
  when "H", "f" # CUP — Cursor Position
    r = (params[0] || 1) - 1
    c = (params[1] || 1) - 1
    cursor[:row] = r.clamp(0, rows - 1)
    cursor[:col] = c.clamp(0, cols - 1)
  when "J" # ED — Erase in Display
    case params[0]
    when nil, 0
      _erase_down(cursor, grid, rows, cols)
    when 1
      _erase_up(cursor, grid, cols)
    when 2, 3
      _erase_all(grid, rows, cols)
      cursor[:row] = 0
      cursor[:col] = 0
    end
  when "K" # EL — Erase in Line
    case params[0]
    when nil, 0
      _erase_line_right(cursor, grid, cols)
    when 1
      _erase_line_left(cursor, grid, cols)
    when 2
      _erase_line(cursor, grid, cols)
    end
  when "X" # Erase Characters
    n = params[0] || 1
    n.times do |i|
      next unless cursor[:row] < rows && cursor[:col] + i < cols
      grid[cursor[:row]][cursor[:col] + i][:char] = " "
    end
  when "s" # DECSC — Save Cursor (CSI variant)
    new_saved = { row: cursor[:row], col: cursor[:col] }
  when "u" # DECRC — Restore Cursor (CSI variant)
    if saved_cursor
      cursor[:row] = saved_cursor[:row]
      cursor[:col] = saved_cursor[:col]
    end
  when "r" # DECSTBM — Set Scroll Region
    top = (params[0] || 1) - 1
    bottom = (params[1] || rows) - 1
    top = top.clamp(0, rows - 1)
    bottom = bottom.clamp(0, rows - 1)
    if top < bottom
      scroll_region[:top] = top
      scroll_region[:bottom] = bottom
    else
      scroll_region[:top] = 0
      scroll_region[:bottom] = rows - 1
    end
    cursor[:row] = 0
    cursor[:col] = 0
  when "h"
    if is_private
      params.each do |p|
        case p
        when 47, 1047, 1049
          action[:alt_screen] = true
          action[:alt_screen_code] = p
        when 25
          action[:cursor_visible] = true
        when 1000
          action[:mouse_mode] = :normal
        when 1002
          action[:mouse_mode] = :drag
        when 1003
          action[:mouse_mode] = :all
        when 1006
          action[:mouse_format] = :sgr
        end
      end
    end
  when "l"
    if is_private
      params.each do |p|
        case p
        when 47, 1047, 1049
          action[:alt_screen] = false
          action[:alt_screen_code] = p
        when 25
          action[:cursor_visible] = false
        when 1000, 1002, 1003
          action[:mouse_mode] = :none
        when 1006
          action[:mouse_format] = :normal
        end
      end
    end
  when "q"
    if space == " "
      style_val = params[0] || 0
      action[:cursor_style] = style_val
    end
  when "n" # DSR — Device Status Report request
    return [params[0] == 6, nil, {}]
  when "R" # DSR response (from terminal side) or CPR — ignore
    nil
  end

  [false, new_saved, action]
end

._apply_sgr(params, attrs) ⇒ Object



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
# File 'lib/tui_td/ansi_parser.rb', line 550

def self._apply_sgr(params, attrs)
  return attrs.merge!(fg: "default", bg: "default", bold: false, italic: false, underline: false, blink: false) if params.empty? || params == [0]

  i = 0
  while i < params.length
    p = params[i]
    case p
    when 0
      attrs.merge!(fg: "default", bg: "default", bold: false, italic: false, underline: false, blink: false)
    when 1
      attrs[:bold] = true
    when 3
      attrs[:italic] = true
    when 4
      attrs[:underline] = true
    when 5, 6
      attrs[:blink] = true
    when 22
      attrs[:bold] = false
    when 23
      attrs[:italic] = false
    when 24
      attrs[:underline] = false
    when 25
      attrs[:blink] = false
    when 7
      # Reverse — swap fg and bg
      attrs[:fg], attrs[:bg] = attrs[:bg], attrs[:fg]
    when 27
      attrs[:fg], attrs[:bg] = attrs[:bg], attrs[:fg]
    when 30..37
      attrs[:fg] = SGR_16_TO_NAME[p - 30] || "color#{p - 30}"
    when 38
      # Extended foreground
      if params[i + 1] == 5
        color = params[i + 2]
        attrs[:fg] = "color#{color}"
        i += 2
      elsif params[i + 1] == 2
        r, g, b = params[i + 2], params[i + 3], params[i + 4]
        attrs[:fg] = format("#%02x%02x%02x", r, g, b)
        i += 4
      end
    when 39
      attrs[:fg] = "default"
    when 40..47
      attrs[:bg] = SGR_16_TO_NAME[p - 40] || "bg_color#{p - 40}"
    when 48
      # Extended background
      if params[i + 1] == 5
        color = params[i + 2]
        attrs[:bg] = "color#{color}"
        i += 2
      elsif params[i + 1] == 2
        r, g, b = params[i + 2], params[i + 3], params[i + 4]
        attrs[:bg] = format("#%02x%02x%02x", r, g, b)
        i += 4
      end
    when 49
      attrs[:bg] = "default"
    when 90..97
      attrs[:fg] = "bright_#{SGR_16_TO_NAME[p - 90] || "color#{p - 90 + 8}"}"
    when 100..107
      attrs[:bg] = "bright_#{SGR_16_TO_NAME[p - 100] || "color#{p - 100 + 8}"}"
    end
    i += 1
  end
end

._color_code(name, prefix) ⇒ Object



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'lib/tui_td/ansi_parser.rb', line 668

def self._color_code(name, prefix)
  case name
  when "default" then nil
  when /^#([0-9a-fA-F]{6})$/
    r = $1[0..1].to_i(16)
    g = $1[2..3].to_i(16)
    b = $1[4..5].to_i(16)
    "#{prefix};2;#{r};#{g};#{b}"
  when /^(bright_)?(.+)$/
    base_name = $2
    index = SGR_16_TO_NAME.key(base_name)
    index += 8 if $1 && index && index < 8
    index ? "#{prefix};5;#{index}" : nil
  else
    nil
  end
end

._erase_all(grid, rows, cols) ⇒ Object



645
646
647
648
649
# File 'lib/tui_td/ansi_parser.rb', line 645

def self._erase_all(grid, rows, cols)
  rows.times do |ri|
    cols.times { |ci| grid[ri][ci][:char] = " " }
  end
end

._erase_down(cursor, grid, rows, cols) ⇒ Object



619
620
621
622
623
624
625
626
627
628
629
630
# File 'lib/tui_td/ansi_parser.rb', line 619

def self._erase_down(cursor, grid, rows, cols)
  r = cursor[:row]
  c = cursor[:col]

  # Erase from cursor to end of line
  (c...cols).each { |ci| grid[r][ci][:char] = " " if r < rows }

  # Erase remaining lines
  ((r + 1)...rows).each do |ri|
    cols.times { |ci| grid[ri][ci][:char] = " " }
  end
end

._erase_line(cursor, grid, cols) ⇒ Object



663
664
665
666
# File 'lib/tui_td/ansi_parser.rb', line 663

def self._erase_line(cursor, grid, cols)
  r = cursor[:row]
  cols.times { |ci| grid[r][ci][:char] = " " if r < grid.length }
end

._erase_line_left(cursor, grid, cols) ⇒ Object



657
658
659
660
661
# File 'lib/tui_td/ansi_parser.rb', line 657

def self._erase_line_left(cursor, grid, cols)
  r = cursor[:row]
  c = cursor[:col]
  (0..c).each { |ci| grid[r][ci][:char] = " " if r < grid.length }
end

._erase_line_right(cursor, grid, cols) ⇒ Object



651
652
653
654
655
# File 'lib/tui_td/ansi_parser.rb', line 651

def self._erase_line_right(cursor, grid, cols)
  r = cursor[:row]
  c = cursor[:col]
  (c...cols).each { |ci| grid[r][ci][:char] = " " if r < grid.length }
end

._erase_up(cursor, grid, cols) ⇒ Object



632
633
634
635
636
637
638
639
640
641
642
643
# File 'lib/tui_td/ansi_parser.rb', line 632

def self._erase_up(cursor, grid, cols)
  r = cursor[:row]
  c = cursor[:col]

  # Erase lines above cursor
  (0...r).each do |ri|
    cols.times { |ci| grid[ri][ci][:char] = " " }
  end

  # Erase from start of line to cursor
  (0..c).each { |ci| grid[r][ci][:char] = " " }
end

._utf8_char_at(str, i) ⇒ Object

Extract a single UTF-8 character at position i in a binary string. Returns [char_string, byte_length] or nil if the byte is not printable/valid.



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
# File 'lib/tui_td/ansi_parser.rb', line 692

def self._utf8_char_at(str, i)
  byte = str.getbyte(i)
  return nil unless byte

  if byte < 0x80
    # Single-byte ASCII
    return nil unless byte >= 0x20  # only printable, skip control chars
    return [byte.chr, 1]
  end

  # Multi-byte UTF-8
  len = if byte & 0xE0 == 0xC0
          2
  elsif byte & 0xF0 == 0xE0
          3
  elsif byte & 0xF8 == 0xF0
          4
  else
          return nil  # continuation byte or invalid — let main loop advance
  end
  return nil if i + len > str.bytesize

  bytes = str.byteslice(i, len)
  char = bytes.dup.force_encoding("UTF-8")
  return nil unless char.valid_encoding?

  [char, len]
rescue StandardError
  nil
end

.build_frame(state) ⇒ Object

Rebuild ANSI output from a state hash (for rendering/screenshot)



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
# File 'lib/tui_td/ansi_parser.rb', line 341

def self.build_frame(state)
  rows = state.dig(:size, :rows) || state["size"]["rows"]
  cols = state.dig(:size, :cols) || state["size"]["cols"]
  grid = state[:rows] || state["rows"]
  cursor = state[:cursor] || state["cursor"]
  mouse_mode = state[:mouse_mode] || state["mouse_mode"] || :none
  mouse_format = state[:mouse_format] || state["mouse_format"] || :normal

  out = +""
  out << "\e[0m"
  out << "\e[2J\e[H"

  grid.each_with_index do |row, ri|
    row.each_with_index do |cell, ci|
      char = cell[:char] || cell["char"] || " "
      fg = cell[:fg] || cell["fg"] || "default"
      bg = cell[:bg] || cell["bg"] || "default"
      bold = cell[:bold] || cell["bold"] || false
      italic = cell[:italic] || cell["italic"] || false
      underline = cell[:underline] || cell["underline"] || false
      blink = cell[:blink] || cell["blink"] || false

      codes = []
      codes << "1" if bold
      codes << "3" if italic
      codes << "4" if underline
      codes << "5" if blink

      fg_code = _color_code(fg, "38")
      bg_code = _color_code(bg, "48")

      codes << fg_code if fg_code
      codes << bg_code if bg_code

      out << "\e[#{codes.join(";")}m" unless codes.empty?
      out << char
    end
    out << "\n" if ri < rows - 1
  end

  # Reconstruct cursor visibility
  cursor_vis = true
  if cursor.is_a?(Hash)
    cursor_vis = cursor[:visible] != false && cursor["visible"] != false
  end
  out << (cursor_vis ? "\e[?25h" : "\e[?25l")

  # Reconstruct cursor style
  if cursor.is_a?(Hash)
    style = cursor[:style] || cursor["style"]
    out << "\e[#{style} q" if style
  end

  # Reconstruct mouse mode and format
  if mouse_mode == :normal
    out << "\e[?1000h"
  elsif mouse_mode == :drag
    out << "\e[?1002h"
  elsif mouse_mode == :all
    out << "\e[?1003h"
  else
    out << "\e[?1000l\e[?1002l\e[?1003l"
  end

  if mouse_format == :sgr
    out << "\e[?1006h"
  else
    out << "\e[?1006l"
  end

  out << "\e[0m"
  out
end

.default_cellObject



686
687
688
# File 'lib/tui_td/ansi_parser.rb', line 686

def self.default_cell
  { char: " ", fg: "default", bg: "default", bold: false, italic: false, underline: false, blink: false }
end

.parse(raw, rows = 40, cols = 120) ⇒ Object

Parse raw terminal output into a structured state Hash



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
# File 'lib/tui_td/ansi_parser.rb', line 118

def self.parse(raw, rows = 40, cols = 120)
  grid = Array.new(rows) do
    Array.new(cols) { default_cell.dup }
  end

  cursor = { row: 0, col: 0 }
  attrs = { fg: "default", bg: "default", bold: false, italic: false, underline: false, blink: false }
  saved_cursor = nil
  scroll_region = { top: 0, bottom: rows - 1 }
  pending_dsr = false

  normal_grid = grid
  alt_grid = nil

  normal_cursor = cursor
  alt_cursor = { row: 0, col: 0 }

  normal_saved_cursor = nil
  alt_saved_cursor = nil

  use_alt_screen = false

  cursor_visible = true
  cursor_style = 1 # 1 = blinking block (default)

  g0_charset = :ascii
  g1_charset = :dec
  active_charset = :g0

  mouse_mode = :none
  mouse_format = :normal

  # Strip everything before the last full clear (if any)
  # to avoid accumulated garbage
  processed = raw

  i = 0
  while i < processed.length
    if processed[i] == "\e" && processed[i + 1] == "["
      # Find end of CSI sequence
      j = i + 2
      j += 1 while j < processed.length && !processed[j].match?(/[A-HJ-KP-SX@\`fhlmnRrsuq]/)
      seq = processed[i..j]

      dsr, new_saved, action = _apply_csi(seq, cursor, attrs, grid, rows, cols, saved_cursor, scroll_region)
      pending_dsr ||= dsr

      if new_saved
        if use_alt_screen
          alt_saved_cursor = new_saved
          saved_cursor = alt_saved_cursor
        else
          normal_saved_cursor = new_saved
          saved_cursor = normal_saved_cursor
        end
      end

      if action.key?(:alt_screen)
        new_alt = action[:alt_screen]
        code = action[:alt_screen_code]
        if new_alt != use_alt_screen
          if new_alt
            # Switch to Alternate Screen
            # Save normal cursor
            normal_cursor = { row: cursor[:row], col: cursor[:col] }

            # Lazy initialize alt grid
            alt_grid ||= Array.new(rows) do
              Array.new(cols) { default_cell.dup }
            end

            # For \e[?1049h, clear alternate screen and reset cursor to 0,0
            if code == 1049
              alt_grid = Array.new(rows) do
                Array.new(cols) { default_cell.dup }
              end
              alt_cursor = { row: 0, col: 0 }
            end

            grid = alt_grid
            cursor = alt_cursor
            saved_cursor = alt_saved_cursor
            use_alt_screen = true
          else
            # Switch to Normal Screen
            # Save alt cursor
            alt_cursor = { row: cursor[:row], col: cursor[:col] }

            grid = normal_grid
            cursor = normal_cursor
            saved_cursor = normal_saved_cursor
            use_alt_screen = false
          end
        end
      end

      if action.key?(:cursor_visible)
        cursor_visible = action[:cursor_visible]
      end

      if action.key?(:cursor_style)
        cursor_style = action[:cursor_style]
      end

      if action.key?(:mouse_mode)
        mouse_mode = action[:mouse_mode]
      end

      if action.key?(:mouse_format)
        mouse_format = action[:mouse_format]
      end

      i = j + 1
    elsif processed[i] == "\n" || processed[i] == "\r\n"
      cursor[:row] += 1
      cursor[:col] = 0
      i += processed[i..i + 1] == "\r\n" ? 2 : 1
    elsif processed[i] == "\r"
      cursor[:col] = 0
      i += 1
    elsif processed[i] == "\t"
      cursor[:col] = ((cursor[:col] / 8) + 1) * 8
      cursor[:col] = cols - 1 if cursor[:col] >= cols
      i += 1
    elsif processed[i] == "\b"
      cursor[:col] -= 1 if cursor[:col] > 0
      i += 1
    elsif processed[i] == "\a"
      # Bell — ignore
      i += 1
    elsif processed[i] == "\x0e"
      active_charset = :g1
      i += 1
    elsif processed[i] == "\x0f"
      active_charset = :g0
      i += 1
    elsif processed[i] == "\e"
      # Handle non-CSI escape sequences
      if processed[i + 1] == "7"
        # DECSC — Save Cursor
        if use_alt_screen
          alt_saved_cursor = { row: cursor[:row], col: cursor[:col] }
          saved_cursor = alt_saved_cursor
        else
          normal_saved_cursor = { row: cursor[:row], col: cursor[:col] }
          saved_cursor = normal_saved_cursor
        end
        i += 2
      elsif processed[i + 1] == "8"
        # DECRC — Restore Cursor
        if saved_cursor
          cursor[:row] = saved_cursor[:row]
          cursor[:col] = saved_cursor[:col]
        end
        i += 2
      elsif processed[i + 1] == "(" && (processed[i + 2] == "0" || processed[i + 2] == "B")
        g0_charset = (processed[i + 2] == "0" ? :dec : :ascii)
        i += 3
      elsif processed[i + 1] == ")" && (processed[i + 2] == "0" || processed[i + 2] == "B")
        g1_charset = (processed[i + 2] == "0" ? :dec : :ascii)
        i += 3
      elsif processed[i + 1] && processed[i + 1].match?(/[()*+\-.\/]/)
        # Other ISO 2022 charset sequences (e.g. G2/G3 or other charsets)
        i += 3
      else
        i += 1
      end
    elsif (char, char_len = _utf8_char_at(processed, i))
      # Printable character (including multi-byte UTF-8)
      if cursor[:row] < rows && cursor[:col] < cols
        cell = grid[cursor[:row]][cursor[:col]]
        current_charset = (active_charset == :g1 ? g1_charset : g0_charset)
        mapped_char = char
        if current_charset == :dec && DEC_MAP.key?(char)
          mapped_char = DEC_MAP[char]
        end
        cell[:char] = mapped_char
        cell.merge!(attrs)
        cursor[:col] += 1
        cursor[:col] = cols - 1 if cursor[:col] >= cols
      end
      i += char_len
    else
      i += 1
    end

    # Handle scrolling within the defined scroll region
    region_top = scroll_region[:top]
    region_bottom = scroll_region[:bottom]

    if cursor[:row] > region_bottom
      scroll_lines = [cursor[:row] - region_bottom, rows].min
      # Shift lines within the scroll region up
      (region_top..(region_bottom - scroll_lines)).each do |ri|
        src = ri + scroll_lines
        grid[ri] = src <= region_bottom ? grid[src] : Array.new(cols) { default_cell.dup }
      end
      # Fill bottom of scroll region with blank lines
      ((region_bottom - scroll_lines + 1)..region_bottom).each do |ri|
        grid[ri] = Array.new(cols) { default_cell.dup }
      end
      cursor[:row] = region_bottom
    end
  end

  {
    size: { rows: rows, cols: cols },
    cursor: {
      row: cursor[:row],
      col: cursor[:col],
      visible: cursor_visible,
      style: cursor_style
    },
    rows: grid,
    pending_dsr: pending_dsr,
    cursor_visible: cursor_visible,
    cursor_style: cursor_style,
    mouse_mode: mouse_mode,
    mouse_format: mouse_format
  }
end