Sha256: d855f72954eed47ba70edaeb250b5be8eeb06e439ff2345bc11761ea59d5e187

Contents?: true

Size: 1.73 KB

Versions: 1

Compression:

Stored size: 1.73 KB

Contents

module AnsiTerm

  # # AnsiTerm::Buffer #
  #
  # A terminal buffer that will eventually handle ANSI style strings
  # fully. For now it will handle the sequences AnsiTerm::String handles
  # but e.g. cursor movement etc. needs to be explicitly handled.
  #
  # Extracted out of https://github.com/vidarh/re
  #
  # FIXME: Provide method of setting default background color
  #
  class Buffer
    attr_reader :w,:h, :lines

    def initialize(w=80, h=25)
      @lines = []
      @x = 0
      @y = 0
      @w = w
      @h = h
      @cache = []
    end

    def cls
      @lines = (1..@h).map { nil }
    end

    def reset
      cls
      @cache=[]
    end

    def move_cursor(x,y)
      @x = x
      @y = y
      @x = @w-1 if @x >= @w
      @y = @y-1 if @y >= @h
    end

    def resize(w,h)
      if @w != w || @h != h
        @w, @h = w,h
        @cache = []
      end
    end

    def print *args
      args.each do |str|
        @lines[@y] ||= AnsiTerm::String.new
        l = @lines[@y]

        if l.length < @x
          l << (" "*(@x - l.length))
        end

        r=@x..@x+str.length-1
        #p [r, str]
        l[r] = str
      end
    end

    def to_s
      out = ""
      cachehit=0
      cachemiss=0
      @lines.each_with_index do |line,y|
        line ||= ""
        line = line[0..@w]
        l = line.length
        s = line.to_str
        if @cache[y] != s
          # Move to start of line; output line; clear to end
          #if l > 0
            out << "\e[#{y+1};1H" << s
            if l < @w
              out << "\e[0m\e[0K"
            end
          #end
          cachemiss += s.length
          old = @cache[y]
          @cache[y] = s
        else
          cachehit += @cache[y].length
        end
      end
      out
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ansiterm-0.4.1 lib/ansiterm/buffer.rb