Class: Rcurses::Pane

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

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

Returns a new instance of Pane.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rcurses/pane.rb', line 12

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
  @multiline_buffer = []   # Buffer to store lines from multi-line paste

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

Instance Attribute Details

#alignObject

Returns the value of attribute align.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def align
  @align
end

#bgObject

Returns the value of attribute bg.



6
7
8
# File 'lib/rcurses/pane.rb', line 6

def bg
  @bg
end

#borderObject

Returns the value of attribute border.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def border
  @border
end

#fgObject

Returns the value of attribute fg.



6
7
8
# File 'lib/rcurses/pane.rb', line 6

def fg
  @fg
end

#hObject

Returns the value of attribute h.



6
7
8
# File 'lib/rcurses/pane.rb', line 6

def h
  @h
end

#historyObject

Returns the value of attribute history.



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

def history
  @history
end

#indexObject

Returns the value of attribute index.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def index
  @index
end

#ixObject

Returns the value of attribute ix.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def ix
  @ix
end

#moredownObject

Returns the value of attribute moredown.



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

def moredown
  @moredown
end

#moreupObject

Returns the value of attribute moreup.



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

def moreup
  @moreup
end

#multiline_bufferObject

Returns the value of attribute multiline_buffer.



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

def multiline_buffer
  @multiline_buffer
end

#promptObject

Returns the value of attribute prompt.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def prompt
  @prompt
end

#recordObject

Returns the value of attribute record.



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

def record
  @record
end

#scrollObject

Returns the value of attribute scroll.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def scroll
  @scroll
end

#textObject

Returns the value of attribute text.



7
8
9
# File 'lib/rcurses/pane.rb', line 7

def text
  @text
end

#wObject

Returns the value of attribute w.



6
7
8
# File 'lib/rcurses/pane.rb', line 6

def w
  @w
end

#xObject

Returns the value of attribute x.



6
7
8
# File 'lib/rcurses/pane.rb', line 6

def x
  @x
end

#yObject

Returns the value of attribute y.



6
7
8
# File 'lib/rcurses/pane.rb', line 6

def y
  @y
end

Class Method Details

.finalizer_procObject



79
80
81
82
83
84
# File 'lib/rcurses/pane.rb', line 79

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



43
44
45
46
47
48
49
50
51
52
# File 'lib/rcurses/pane.rb', line 43

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



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

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

  if @border
    # Determine border characters based on environment
    if ENV['RCURSES_BORDERS'] == 'ascii'
      tl, tr, bl, br, h, v = '+', '+', '+', '+', '-', '|'
    else
      # Check if locale supports UTF-8
      locale = ENV['LANG'] || ENV['LC_ALL'] || ENV['LC_CTYPE'] || ''
      if locale.downcase.include?('utf-8') || locale.downcase.include?('utf8')
        tl, tr, bl, br, h, v = '┌', '┐', '└', '┘', '─', '│'
      else
        # Fallback to ASCII for non-UTF-8 locales
        tl, tr, bl, br, h, v = '+', '+', '+', '+', '-', '|'
      end
    end
    
    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



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

def bottom
  @ix = @text.split("\n").length - @h
  refresh
end

#cleanupObject



70
71
72
73
74
75
76
77
# File 'lib/rcurses/pane.rb', line 70

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

#clearObject



64
65
66
67
68
# File 'lib/rcurses/pane.rb', line 64

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

#downObject



470
471
472
473
474
475
476
477
478
479
480
# 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
  begin
    @pos = [@pos, @txt[@ix + @line].length].min
  rescue
  end
end

#editObject



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

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
      while IO.select([$stdin], nil, nil, 0)
        input_char = $stdin.read_nonblock(1) rescue nil
        break unless input_char
        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



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

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
    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'
      col(@x + prompt_len)
      cont = cont.slice(0, content_len)
      # Show indicator if multiline content detected
      display_cont = cont
      if @multiline_buffer && !@multiline_buffer.empty?
        lines_indicator = " [+#{@multiline_buffer.size} lines]"
        available = content_len - lines_indicator.length
        display_cont = cont.slice(0, [available, 0].max) + lines_indicator if available > 0
      end
      print display_cont.ljust(content_len).c(fmt)
      # Calculate display width up to cursor position
      display_pos = @pos > 0 ? Rcurses.display_width(cont[0...@pos]) : 0
      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, handle multiline paste
        if @multiline_buffer && !@multiline_buffer.empty?
          # Add current line if it's not empty
          @multiline_buffer << cont.dup unless cont.empty?
          @text = @multiline_buffer.shift # Return first line as @text
        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 /^.$/
        if @pos < content_len
          cont.insert(@pos, chr)
          @pos += 1
        end
      end

      while IO.select([$stdin], nil, nil, 0)
        chr = $stdin.read_nonblock(1) rescue nil
        break unless chr
        # 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.



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

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

#leftObject



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/rcurses/pane.rb', line 442

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

#linedownObject



92
93
94
95
96
# File 'lib/rcurses/pane.rb', line 92

def linedown
  @ix += 1
  @ix = @text.split("\n").length if @ix > @text.split("\n").length - 1
  refresh
end

#lineupObject



98
99
100
101
102
# File 'lib/rcurses/pane.rb', line 98

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

#move(dx, dy) ⇒ Object



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

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

#pagedownObject



104
105
106
107
108
# File 'lib/rcurses/pane.rb', line 104

def pagedown
  @ix = @ix + @h - 1
  @ix = @text.split("\n").length - @h if @ix > @text.split("\n").length - @h
  refresh
end

#pageupObject



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

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

#parse(cont) ⇒ Object



482
483
484
485
486
487
488
489
490
491
492
# File 'lib/rcurses/pane.rb', line 482

def parse(cont)
  cont.gsub!(/\*(.+?)\*/, '\1'.b)
  cont.gsub!(/\/(.+?)\//, '\1'.i)
  cont.gsub!(/_(.+?)_/, '\1'.u)
  cont.gsub!(/#(.+?)#/, '\1'.r)
  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.



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

def refresh(cont = @text)
  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

  begin
    o_row, o_col = pos
  rescue => e
    # Fallback cursor position
    o_row, o_col = 1, 1
  end

  # Hide cursor, disable auto-wrap, reset all SGR and scroll margins
  # (so stray underline, scroll regions, etc. can’t leak out)
  STDOUT.print "\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("\n").map { |line| line.chomp("\r") }
      @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 or 4x codes)
      has_bg_color = @txt[l] =~ /\e\[(?:\d+;)*4[0-9](?:;\d+)*m/ || @txt[l] =~ /\e\[(?:\d+;)*48(?:;\d+)*m/
      
      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

    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 wrap, then also reset SGR and scroll-region one more time
  diff_buf << "\e[#{o_row};#{o_col}H\e[?7h\e[0m\e[r"
  begin
    # Debug: check what's actually being printed
    if diff_buf.include?("Purpose") && diff_buf.include?("[38;5;")
      File.open("/tmp/rcurses_debug.log", "a") do |f|
        f.puts "=== PRINT DEBUG ==="
        f.puts "diff_buf sample: #{diff_buf[0..200].inspect}"
        f.puts "Has escape byte 27: #{diff_buf.bytes.include?(27)}"
        f.puts "Escape count: #{diff_buf.bytes.count(27)}"
      end
    end
    
    print diff_buf
  rescue => e
    # If printing fails, at least try to restore terminal state
    begin
      print "\e[0m\e[?25h\e[?7h"
    rescue
    end
  end
  @prev_frame = new_frame

  # Draw scroll markers after printing the frame.
  if @scroll
    marker_col = @x + @w - 1
    if @ix > 0
      print "\e[#{@y};#{marker_col}H" + "∆".c(fmt)
    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(fmt)
    end
  end

  if @border
    # Determine border characters based on environment
    if ENV['RCURSES_BORDERS'] == 'ascii'
      tl, tr, bl, br, h, v = '+', '+', '+', '+', '-', '|'
    else
      # Check if locale supports UTF-8
      locale = ENV['LANG'] || ENV['LC_ALL'] || ENV['LC_CTYPE'] || ''
      if locale.downcase.include?('utf-8') || locale.downcase.include?('utf8')
        tl, tr, bl, br, h, v = '┌', '┐', '└', '┘', '─', '│'
      else
        # Fallback to ASCII for non-UTF-8 locales
        tl, tr, bl, br, h, v = '+', '+', '+', '+', '-', '|'
      end
    end
    
    # 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



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

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



54
55
56
57
58
59
60
61
62
# File 'lib/rcurses/pane.rb', line 54

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



408
409
410
411
412
413
414
415
416
417
418
# File 'lib/rcurses/pane.rb', line 408

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



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

def top
  @ix = 0
  refresh
end

#upObject



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

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