Class: Rcurses::Pane

Inherits:
Object
  • Object
show all
Includes:
Cursor, Input
Defined in:
lib/rcurses/pane.rb

Direct Known Subclasses

Popup

Constant Summary

Constants included from Cursor

Cursor::CSI, Cursor::ESC

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Input

#getchr

Methods included from Cursor

clear_char, clear_line, clear_line_after, clear_line_before, clear_screen_down, col, colget, down, hide, left, next_line, pos, prev_line, restore, right, row, rowget, save, scroll_down, scroll_up, set, show, up

Constructor Details

#initialize(x = 1, y = 1, w = 1, h = 1, fg = nil, bg = nil) ⇒ Pane



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
# File 'lib/rcurses/pane.rb', line 19

def initialize(x = 1, y = 1, w = 1, h = 1, fg = nil, bg = nil)
  @max_h, @max_w = IO.console ? IO.console.winsize : [24, 80]
  @x          = x
  @y          = y
  @w          = w
  @h          = h
  @fg, @bg    = fg, bg
  @text       = ""     # Initialize text variable
  @align      = "l"    # Default alignment
  @scroll     = true   # Enable scroll indicators
  @prompt     = ""     # Prompt for editline
  @ix         = 0      # Starting text line index
  @prev_frame = nil    # Holds the previously rendered frame (array of lines)
  @line       = 0      # For cursor tracking during editing:
  @pos        = 0      # For cursor tracking during editing:
  @record     = false  # Don't record history unless explicitly set to true
  @history    = []     # History array
  @max_history_size = 100  # Limit history to prevent memory leaks
  @scroll_fg  = nil    # Scroll indicator color (defaults to @fg)
  @multiline_buffer = []   # Buffer to store lines from multi-line paste
  @update     = true   # When false, refresh is a no-op
  @emoji      = false  # Opt-in: C-E opens emoji picker in editline
  @emoji_refresh = nil  # Optional lambda to redraw UI after emoji picker

  ObjectSpace.define_finalizer(self, self.class.finalizer_proc)
end

Instance Attribute Details

#alignObject

Returns the value of attribute align.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def align
  @align
end

#bgObject

Returns the value of attribute bg.



10
11
12
# File 'lib/rcurses/pane.rb', line 10

def bg
  @bg
end

#borderObject

Returns the value of attribute border.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def border
  @border
end

#emojiObject

Returns the value of attribute emoji.



16
17
18
# File 'lib/rcurses/pane.rb', line 16

def emoji
  @emoji
end

#emoji_refreshObject

Optional callback to redraw UI after emoji picker closes



17
18
19
# File 'lib/rcurses/pane.rb', line 17

def emoji_refresh
  @emoji_refresh
end

#fgObject

Returns the value of attribute fg.



10
11
12
# File 'lib/rcurses/pane.rb', line 10

def fg
  @fg
end

#hObject

Returns the value of attribute h.



9
10
11
# File 'lib/rcurses/pane.rb', line 9

def h
  @h
end

#historyObject

Returns the value of attribute history.



13
14
15
# File 'lib/rcurses/pane.rb', line 13

def history
  @history
end

#indexObject

Returns the value of attribute index.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def index
  @index
end

#ixObject

Returns the value of attribute ix.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def ix
  @ix
end

#moredownObject

Returns the value of attribute moredown.



12
13
14
# File 'lib/rcurses/pane.rb', line 12

def moredown
  @moredown
end

#moreupObject

Returns the value of attribute moreup.



12
13
14
# File 'lib/rcurses/pane.rb', line 12

def moreup
  @moreup
end

#multiline_bufferObject

Returns the value of attribute multiline_buffer.



14
15
16
# File 'lib/rcurses/pane.rb', line 14

def multiline_buffer
  @multiline_buffer
end

#promptObject

Returns the value of attribute prompt.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def prompt
  @prompt
end

#recordObject

Returns the value of attribute record.



13
14
15
# File 'lib/rcurses/pane.rb', line 13

def record
  @record
end

#scrollObject

Returns the value of attribute scroll.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def scroll
  @scroll
end

#scroll_fgObject

Returns the value of attribute scroll_fg.



9
10
11
# File 'lib/rcurses/pane.rb', line 9

def scroll_fg
  @scroll_fg
end

#textObject

Returns the value of attribute text.



11
12
13
# File 'lib/rcurses/pane.rb', line 11

def text
  @text
end

#updateObject

Returns the value of attribute update.



15
16
17
# File 'lib/rcurses/pane.rb', line 15

def update
  @update
end

#wObject

Returns the value of attribute w.



9
10
11
# File 'lib/rcurses/pane.rb', line 9

def w
  @w
end

#xObject

Returns the value of attribute x.



9
10
11
# File 'lib/rcurses/pane.rb', line 9

def x
  @x
end

#yObject

Returns the value of attribute y.



9
10
11
# File 'lib/rcurses/pane.rb', line 9

def y
  @y
end

Class Method Details

.finalizer_procObject



109
110
111
112
113
114
# File 'lib/rcurses/pane.rb', line 109

def self.finalizer_proc
  proc do
    # Cleanup code that doesn't reference instance variables
    # since the object is already being finalized
  end
end

Instance Method Details

#ask(prompt, text) ⇒ Object



73
74
75
76
77
78
79
80
81
82
# File 'lib/rcurses/pane.rb', line 73

def ask(prompt, text)
  @prompt = prompt
  @text   = text
  editline
  if @record && !@text.empty?
    @history << @text
    @history.shift while @history.size > @max_history_size
  end
  @text
end

#border_refreshObject

Refresh only the border



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
# File 'lib/rcurses/pane.rb', line 164

def border_refresh
  left_col   = @x - 1
  right_col  = @x + @w
  top_row    = @y - 1
  bottom_row = @y + @h

  if @border
    tl, tr, bl, br, h, v = border_chars

    fmt = [@fg.to_s, @bg.to_s].join(',')
    top = (tl + h * @w + tr).c(fmt)
    STDOUT.print "\e[#{top_row};#{left_col}H" + top
    (0...@h).each do |i|
      row = @y + i
      STDOUT.print "\e[#{row};#{left_col}H"  + v.c(fmt)
      STDOUT.print "\e[#{row};#{right_col}H" + v.c(fmt)
    end
    bottom = (bl + h * @w + br).c(fmt)
    STDOUT.print "\e[#{bottom_row};#{left_col}H" + bottom
  else
    STDOUT.print "\e[#{top_row};#{left_col}H" + " " * (@w + 2)
    (0...@h).each do |i|
      row = @y + i
      STDOUT.print "\e[#{row};#{left_col}H"  + " "
      STDOUT.print "\e[#{row};#{right_col}H" + " "
    end
    STDOUT.print "\e[#{bottom_row};#{left_col}H" + " " * (@w + 2)
  end
end

#bottomObject



147
148
149
150
# File 'lib/rcurses/pane.rb', line 147

def bottom
  @ix = line_count - @h
  refresh
end

#cleanupObject



100
101
102
103
104
105
106
107
# File 'lib/rcurses/pane.rb', line 100

def cleanup
  @prev_frame = nil
  @lazy_txt = nil
  @raw_txt = nil
  @cached_text = nil
  @txt = nil
  @history.clear if @history
end

#clearObject



94
95
96
97
98
# File 'lib/rcurses/pane.rb', line 94

def clear
  @text = ""
  @ix   = 0
  full_refresh 
end

#downObject



470
471
472
473
474
475
476
477
# File 'lib/rcurses/pane.rb', line 470

def down
  if @line == @h - 1
    @ix += 1 unless @ix + @line >= @txt.length - 1
  elsif @line + @ix + 1 < @txt.length
    @line += 1
  end
  @pos = [@pos, @txt[@ix + @line]&.length || 0].min
end

#editObject



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
# File 'lib/rcurses/pane.rb', line 491

def edit
  begin
    STDIN.cooked!  rescue nil
    STDIN.echo = true rescue nil
    # Prepare content with visible newline markers
    content = @text.pure.gsub("\n", "¬\n")
    # Reset editing cursor state
    @ix = 0
    @line = 0
    @pos = 0
    # Initial render sets @txt internally for display and cursor math
    refresh(content)
    Rcurses::Cursor.show
    input_char = ''

    while input_char != 'ESC'
      # Move the terminal cursor to the logical text cursor
      row(@y + @line)
      # Calculate display width up to cursor position on current line
      current_line_text = @txt[@ix + @line] || ""
      display_pos = @pos > 0 ? Rcurses.display_width(current_line_text.pure[0...@pos]) : 0
      col(@x + display_pos)
      input_char = getchr(flush: false)
      case input_char
      when 'C-L'
        @align = 'l'
      when 'C-R'
        @align = 'r'
      when 'C-C'
        @align = 'c'
      when 'C-Y'
        Clipboard.copy(@text.pure)
      when 'C-S'
        content = content.gsub('¬', "\n")
        content = parse(content)
        @text = content
        input_char = 'ESC'
      when 'DEL'
        posx = calculate_posx
        content.slice!(posx)
      when 'BACK'
        if @pos > 0
          left
          posx = calculate_posx
          content.slice!(posx)
        end
      when 'WBACK'
        while @pos > 0 && content[calculate_posx - 1] != ' '
          left
          posx = calculate_posx
          content.slice!(posx)
        end
      when 'C-K'
        line_start_pos = calculate_line_start_pos
        line_length = @txt[@ix + @line]&.length || 0
        content.slice!(line_start_pos + @pos, line_length - @pos)
      when 'UP'
        up
      when 'DOWN'
        down
      when 'RIGHT'
        right
      when 'LEFT'
        left
      when 'HOME'
        @pos = 0
      when 'END'
        current_line_length = @txt[@ix + @line]&.length || 0
        @pos = current_line_length
      when 'C-HOME'
        @ix = 0; @line = 0; @pos = 0
      when 'C-END'
        total_lines = @txt.length
        @ix = [total_lines - @h, 0].max
        @line = [@h - 1, total_lines - @ix - 1].min
        current_line_length = @txt[@ix + @line]&.length || 0
        @pos = current_line_length
      when 'ENTER'
        posx = calculate_posx
        content.insert(posx, "¬\n")
        right
      when /^.$/
        posx = calculate_posx
        content.insert(posx, input_char)
        right
      end

      # Handle any buffered input (multi-line paste)
      while IO.select([$stdin], nil, nil, 0)
        input_char = $stdin.read_nonblock(1) rescue nil
        break unless input_char
        # ESC byte starts an escape sequence (arrow key, etc.)
        # Push it back for getchr to parse properly on next iteration
        if input_char == "\e"
          $stdin.ungetbyte(0x1b)
          break
        end
        posx = calculate_posx
        content.insert(posx, input_char)
        right
      end

      # Re-render without overwriting the internal @txt
      refresh(content)
      Rcurses::Cursor.show
    end
  ensure
    STDIN.raw!         rescue nil  
    STDIN.echo = false rescue nil
    while IO.select([$stdin], nil, nil, 0)
      $stdin.read_nonblock(4096) rescue break
    end
  end
  Rcurses::Cursor.hide
end

#editlineObject



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
# File 'lib/rcurses/pane.rb', line 607

def editline
  begin
    STDIN.cooked!  rescue nil
    STDIN.echo = true rescue nil
    Rcurses::Cursor.show
    @x = [[@x, 1].max, @max_w - @w + 1].min
    @y = [[@y, 1].max, @max_h - @h + 1].min
    @scroll = false
    @ix = 0
    row(@y)
    fmt = [@fg.to_s, @bg.to_s].join(',')
    col(@x)
    print @prompt.c(fmt)
    prompt_len = @prompt.pure.length
    content_len = @w - prompt_len
    return nil if content_len < 1
    cont = @text.pure.slice(0, content_len)
    @pos = cont.length
    chr = ''
    history_index = @history.size
    @multiline_buffer = []  # Clear buffer at start of input

    while chr != 'ESC'
      row(@y)
      col(@x + prompt_len)
      # Truncate content to fit display width
      disp_w = Rcurses.display_width(cont)
      while disp_w > content_len && cont.length > 0
        cont = cont[0..-2]
        disp_w = Rcurses.display_width(cont)
      end
      @pos = cont.length if @pos > cont.length
      # Show indicator if multiline content detected
      display_cont = cont
      if @multiline_buffer && !@multiline_buffer.empty?
        lines_indicator = " [+#{@multiline_buffer.size} lines]"
        available = content_len - Rcurses.display_width(lines_indicator)
        if available > 0
          # Truncate cont to fit indicator
          trunc = cont
          while Rcurses.display_width(trunc) > available && trunc.length > 0
            trunc = trunc[0..-2]
          end
          display_cont = trunc + lines_indicator
        end
      end
      # Pad to full width using spaces (each space = 1 column)
      pad_needed = content_len - Rcurses.display_width(display_cont)
      padded = display_cont + (" " * [pad_needed, 0].max)
      print padded.c(fmt)
      # Calculate display width up to cursor position and ensure correct row
      display_pos = @pos > 0 ? Rcurses.display_width(cont[0...@pos]) : 0
      row(@y)
      col(@x + prompt_len + display_pos)
      chr = getchr(flush: false)
      case chr
      when 'LEFT'
        @pos -= 1 if @pos > 0
      when 'RIGHT'
        @pos += 1 if @pos < cont.length
      when 'HOME'
        @pos = 0
      when 'END'
        @pos = cont.length
      when 'DEL'
        cont[@pos] = '' if @pos < cont.length
      when 'BACK'
        if @pos > 0
          @pos -= 1
          cont[@pos] = ''
        end
      when 'WBACK'
        while @pos > 0 && cont[@pos - 1] != ' '
          @pos -= 1
          cont[@pos] = ''
        end
      when 'C-K'
        cont = ''
        @pos = 0
      when 'ENTER'
        # If there are lines in multiline_buffer, join all pasted lines
        if @multiline_buffer && !@multiline_buffer.empty?
          @multiline_buffer << cont.dup unless cont.empty?
          @text = @multiline_buffer.join("\n")
        else
          @text = cont
        end
        chr = 'ESC'
      when 'UP'
        if @history.any? && history_index > 0
          history_index -= 1
          cont = @history[history_index].pure.slice(0, content_len)
          @pos = cont.length
        end
      when 'DOWN'
        if history_index < @history.size - 1
          history_index += 1
          cont = @history[history_index].pure.slice(0, content_len)
          @pos = cont.length
        elsif history_index == @history.size - 1
          history_index += 1
          cont = ""
          @pos = 0
        end
      when 'C-E'
        if @emoji
          require_relative 'emoji' unless defined?(Rcurses::EmojiPicker)
          picked = Rcurses::EmojiPicker.pick(self)
          if picked
            cont.insert(@pos, picked)
            @pos += picked.length
          end
          # Redraw UI behind the overlay (full refresh to clear overlay artifacts)
          @emoji_refresh.call if @emoji_refresh
          # Redraw prompt line
          row(@y)
          col(@x)
          print @prompt.c(fmt)
        end
      when /^.$/
        if @pos < content_len
          cont.insert(@pos, chr)
          @pos += 1
        end
      end

      last_was_cr = false
      while IO.select([$stdin], nil, nil, 0)
        chr = $stdin.read_nonblock(1) rescue nil
        break unless chr
        # ESC byte starts an escape sequence (arrow key, etc.)
        # Push it back for getchr to parse properly on next iteration
        if chr == "\e"
          $stdin.ungetbyte(0x1b)
          break
        end
        # Normalize \r\n to a single newline: skip \n after \r
        if chr == "\n" && last_was_cr
          last_was_cr = false
          next
        end
        last_was_cr = (chr == "\r")
        # Handle newlines in multi-line paste (\n or \r)
        if chr == "\n" || chr == "\r"
          @multiline_buffer << cont.dup unless cont.empty?
          cont = ""
          @pos = 0
          next
        end
        if @pos < content_len
          cont.insert(@pos, chr)
          @pos += 1
        end
      end
    end
  ensure
    STDIN.raw!         rescue nil  
    STDIN.echo = false rescue nil
    while IO.select([$stdin], nil, nil, 0)
      $stdin.read_nonblock(4096) rescue break
    end
  end
  prompt_len = @prompt.pure.length
  # Calculate display width for final cursor position
  final_display_pos = @pos > 0 ? Rcurses.display_width(cont[0...(@pos - 1).clamp(0, cont.length)]) : 0
  new_col = @x + prompt_len + final_display_pos
  col(new_col)
  Rcurses::Cursor.hide
end

#full_refresh(cont = @text) ⇒ Object

full_refresh forces a complete repaint.



158
159
160
161
# File 'lib/rcurses/pane.rb', line 158

def full_refresh(cont = @text)
  @prev_frame = nil
  refresh(cont)
end

#leftObject



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/rcurses/pane.rb', line 445

def left
  if @pos == 0
    if @line == 0
      unless @ix == 0
        @ix -= 1
        @pos = @txt[@ix + @line].length
      end
    else
      @line -= 1
      @pos = @txt[@ix + @line].length
    end
  else
    @pos -= 1
  end
end

#line_countObject



69
70
71
# File 'lib/rcurses/pane.rb', line 69

def line_count
  @line_count ||= @text.to_s.count("\n") + 1
end

#linedownObject



122
123
124
125
126
# File 'lib/rcurses/pane.rb', line 122

def linedown
  @ix += 1
  @ix = line_count - 1 if @ix > line_count - 1
  refresh
end

#lineupObject



128
129
130
131
132
# File 'lib/rcurses/pane.rb', line 128

def lineup
  @ix -= 1
  @ix = 0 if @ix < 0
  refresh
end

#move(dx, dy) ⇒ Object



116
117
118
119
120
# File 'lib/rcurses/pane.rb', line 116

def move(dx, dy)
  @x += dx
  @y += dy
  refresh
end

#pagedownObject



134
135
136
137
138
139
# File 'lib/rcurses/pane.rb', line 134

def pagedown
  @ix = @ix + @h - 1
  max = line_count - @h
  @ix = max if @ix > max
  refresh
end

#pageupObject



141
142
143
144
145
# File 'lib/rcurses/pane.rb', line 141

def pageup
  @ix = @ix - @h + 1
  @ix = 0 if @ix < 0
  refresh
end

#parse(cont) ⇒ Object



479
480
481
482
483
484
485
486
487
488
489
# File 'lib/rcurses/pane.rb', line 479

def parse(cont)
  cont.gsub!(/\*(.+?)\*/, '\1'.bd)
  cont.gsub!(/\/(.+?)\//, '\1'.it)
  cont.gsub!(/_(.+?)_/, '\1'.ul)
  cont.gsub!(/#(.+?)#/, '\1'.rv)
  cont.gsub!(/<([^|]+)\|([^>]+)>/) do
    text = $2; codes = $1
    text.c(codes)
  end
  cont
end

#refresh(cont = @text) ⇒ Object

Diff-based refresh that minimizes flicker. In this updated version we lazily process only the raw lines required to fill the pane.



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
# File 'lib/rcurses/pane.rb', line 196

def refresh(cont = @text)
  return @prev_frame&.join("\n") || "" unless @update
  begin
    @max_h, @max_w = IO.console.winsize
  rescue => e
    # Fallback to reasonable defaults if terminal size can't be determined
    @max_h, @max_w = 24, 80
  end

  # Ensure minimum viable dimensions
  @max_h = [[@max_h, 3].max, 1000].min  # Between 3 and 1000 rows
  @max_w = [[@max_w, 10].max, 1000].min  # Between 10 and 1000 columns
  
  # Ensure pane dimensions are reasonable
  @w = [[@w, 1].max, @max_w].min
  @h = [[@h, 1].max, @max_h].min

  if @border
    @w = @max_w - 2 if @w > @max_w - 2
    @h = @max_h - 2 if @h > @max_h - 2
    @x = [[2, @x].max, @max_w - @w].min
    @y = [[2, @y].max, @max_h - @h].min
  else
    @w = @max_w if @w > @max_w
    @h = @max_h if @h > @max_h
    @x = [[1, @x].max, @max_w - @w + 1].min
    @y = [[1, @y].max, @max_h - @h + 1].min
  end

  # Save cursor with ANSI save (no stdin read needed)
  # Hide cursor, disable auto-wrap, reset all SGR and scroll margins
  STDOUT.print "\e7\e[?25l\e[?7l\e[0m\e[r"

  fmt = [@fg.to_s, @bg.to_s].join(',')
  
  # Skip color application if fg and bg are both nil or empty
  @skip_colors = (@fg.nil? && @bg.nil?) || (fmt == ",")
  

  # Lazy evaluation: If the content or pane width has changed, reinitialize the lazy cache.
  if !defined?(@cached_text) || @cached_text != cont || @cached_w != @w
    begin
      @raw_txt   = (cont || "").split(/\r?\n|\r/).map { |line| line }
      @lazy_txt  = []   # This will hold the processed (wrapped) lines as needed.
      @lazy_index = 0   # Pointer to the next raw line to process.
      @cached_text = (cont || "").dup
      @cached_w = @w
    rescue => e
      # Fallback if content processing fails
      @raw_txt = [""]
      @lazy_txt = []
      @lazy_index = 0
      @cached_text = ""
      @cached_w = @w
    end
  end

  content_rows = @h
  # Ensure we have processed enough lines for the current scroll position + visible area.
  # Dynamically process more lines as needed when scrolling through large lists
  required_lines = @ix + content_rows + 100  # Larger buffer for smoother scrolling
  
  # Safety limit to prevent excessive memory usage (but still very generous)
  max_allowed = 100000  # Allow up to 100k lines which should handle any reasonable directory
  
  # Process lines on demand as we scroll
  while @lazy_txt.size < required_lines && @lazy_index < @raw_txt.size
    # Safety check to prevent runaway memory usage
    break if @lazy_txt.size > max_allowed
    
    raw_line = @raw_txt[@lazy_index]
    # If the raw line is short, no wrapping is needed.
    if raw_line.respond_to?(:pure) && Rcurses.display_width(raw_line.pure) <= @w
      processed = [raw_line]
    else
      processed = split_line_with_ansi(raw_line, @w)
    end
    @lazy_txt.concat(processed)
    @lazy_index += 1
  end
  
  # Simplified: just limit max processing, don't trim existing cache
  # This avoids expensive array operations during scrolling
  
  @txt = @lazy_txt

  @ix = @txt.length - 1 if @ix > @txt.length - 1
  @ix = 0 if @ix < 0

  new_frame = []

  content_rows.times do |i|
    line_str = ""
    l = @ix + i
    if @txt[l].to_s != ""
      pl = @w - Rcurses.display_width(@txt[l].pure)
      pl = 0 if pl < 0
      hl = pl / 2
      
      # Check if text has ANSI background colors (48;5;N or 48;2;R;G;B)
      has_bg_color = @txt[l] =~ /\e\[[\d;]*48;[25];/
      
      if @skip_colors || (@txt[l].include?("\e[") && !@bg)
        # No pane colors to apply, or text has ANSI but pane has no bg
        case @align
        when "l"
          line_str = @txt[l] + " " * pl
        when "r"
          line_str = " " * pl + @txt[l]
        when "c"
          line_str = " " * hl + @txt[l] + " " * (pl - hl)
        end
      elsif @txt[l].include?("\e[") && @bg && !has_bg_color
        # Text has ANSI codes but no bg color - apply pane fg and bg to text and padding
        case @align
        when "l"
          line_str = @txt[l].c(fmt) + " ".c(fmt) * pl
        when "r"
          line_str = " ".c(fmt) * pl + @txt[l].c(fmt)
        when "c"
          line_str = " ".c(fmt) * hl + @txt[l].c(fmt) + " ".c(fmt) * (pl - hl)
        end
      elsif @txt[l].include?("\e[") && has_bg_color
        # Text has its own bg color - preserve it, only apply pane bg to padding
        case @align
        when "l"
          line_str = @txt[l] + " ".c(fmt) * pl
        when "r"
          line_str = " ".c(fmt) * pl + @txt[l]
        when "c"
          line_str = " ".c(fmt) * hl + @txt[l] + " ".c(fmt) * (pl - hl)
        end
      else
        # No ANSI codes - apply pane colors normally
        case @align
        when "l"
          line_str = @txt[l].c(fmt) + " ".c(fmt) * pl
        when "r"
          line_str = " ".c(fmt) * pl + @txt[l].c(fmt)
        when "c"
          line_str = " ".c(fmt) * hl + @txt[l].c(fmt) + " ".c(fmt) * (pl - hl)
        end
      end
    else
      # Empty line
      line_str = @skip_colors ? " " * @w : " ".c(fmt) * @w
    end

    # Strip non-SGR ANSI sequences (cursor movement, clear, etc.)
    # Keep only SGR sequences (ending in 'm') for colors/styles
    line_str = line_str.gsub(ANSI_CSI_RE, '')
    # Strip any raw control characters (except tab and ANSI ESC sequences)
    line_str = line_str.gsub(/[\x00-\x08\x0b-\x1a\x7f]/, '?')

    # Hard-clip line to pane width to prevent overflow into adjacent panes
    visible_w = Rcurses.display_width(line_str.respond_to?(:pure) ? line_str.pure : line_str.gsub(ANSI_RE, ''))
    if visible_w > @w
      line_str = line_str.respond_to?(:shorten) ? line_str.shorten(@w) : line_str[0, @w]
    end

    new_frame << line_str
  end

  diff_buf = ""
  new_frame.each_with_index do |line, i|
    row_num = @y + i
    col_num = @x
    if @prev_frame.nil? || @prev_frame[i] != line
      diff_buf << "\e[#{row_num};#{col_num}H" << line
    end
  end

  # Restore cursor, reset SGR and scroll-region (keep auto-wrap disabled)
  diff_buf << "\e8\e[0m\e[r"
  begin
    print diff_buf
  rescue StandardError
    begin
      print "\e[0m\e[?25h"
    rescue StandardError
    end
  end
  @prev_frame = new_frame

  # Draw scroll markers after printing the frame.
  if @scroll
    marker_col = @x + @w - 1
    sfmt = @scroll_fg ? [(@scroll_fg).to_s, @bg.to_s].join(',') : fmt
    if @ix > 0
      print "\e[#{@y};#{marker_col}H" + "∆".c(sfmt)
    end
    # If there are more processed lines than fit in the pane
    # OR there remain raw lines to process, show the down marker.
    if (@txt.length - @ix) > @h || (@lazy_index < @raw_txt.size)
      print "\e[#{@y + @h - 1};#{marker_col}H" + "∇".c(sfmt)
    end
  end

  if @border
    tl, tr, bl, br, h, v = border_chars

    # top
    print "\e[#{@y - 1};#{@x - 1}H" + (tl + h * @w + tr).c(fmt)
    # sides
    (0...@h).each do |i|
      print "\e[#{@y + i};#{@x - 1}H"  + v.c(fmt)
      print "\e[#{@y + i};#{@x + @w}H" + v.c(fmt)
    end
    # bottom
    print "\e[#{@y + @h};#{@x - 1}H" + (bl + h * @w + br).c(fmt)
  end

  new_frame.join("\n")
end

#rightObject



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/rcurses/pane.rb', line 423

def right
  if @pos < @txt[@ix + @line].length
    @pos += 1
    if @pos == @w
      @pos = 0
      if @line == @h - 1
        @ix += 1
      else
        @line += 1
      end
    end
  else
    if @line == @h - 1
      @ix += 1 unless @ix >= @txt.length - @h
      @pos = 0
    elsif @line + @ix + 1 < @txt.length
      @line += 1
      @pos = 0
    end
  end
end

#say(text) ⇒ Object



84
85
86
87
88
89
90
91
92
# File 'lib/rcurses/pane.rb', line 84

def say(text)
  if @record && !text.empty?
    @history << text
    @history.shift while @history.size > @max_history_size
  end
  @text = text
  @ix   = 0
  refresh 
end

#textformat(cont) ⇒ Object



411
412
413
414
415
416
417
418
419
420
421
# File 'lib/rcurses/pane.rb', line 411

def textformat(cont)
  # This method is no longer used in refresh since we process lazily,
  # but is kept here if needed elsewhere.
  lines = cont.split("\n")
  result = []
  lines.each do |line|
    split_lines = split_line_with_ansi(line, @w)
    result.concat(split_lines)
  end
  result
end

#topObject



152
153
154
155
# File 'lib/rcurses/pane.rb', line 152

def top
  @ix = 0
  refresh
end

#upObject



461
462
463
464
465
466
467
468
# File 'lib/rcurses/pane.rb', line 461

def up
  if @line == 0
    @ix -= 1 unless @ix == 0
  else
    @line -= 1
  end
  @pos = [@pos, @txt[@ix + @line]&.length || 0].min
end