Class: Kitsune::Kit::Tui::Terminal

Inherits:
Object
  • Object
show all
Defined in:
lib/kitsune/kit/tui/terminal.rb

Constant Summary collapse

ALT_SCREEN =
"\e[?1049h"
MAIN_SCREEN =
"\e[?1049l"
DISABLE_WRAP =
"\e[?7l"
ENABLE_WRAP =
"\e[?7h"

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin, output: $stdout) ⇒ Terminal

Returns a new instance of Terminal.



15
16
17
18
# File 'lib/kitsune/kit/tui/terminal.rb', line 15

def initialize(input: $stdin, output: $stdout)
  @input = input
  @output = output
end

Instance Method Details

#draw(content) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/kitsune/kit/tui/terminal.rb', line 38

def draw(content)
  frame = content.lines(chomp: true).each_with_index.map do |line, index|
    "\e[#{index + 1};1H#{line}"
  end.join
  output.write(frame)
  output.flush
end

#read_key(timeout: 0.1) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/kitsune/kit/tui/terminal.rb', line 46

def read_key(timeout: 0.1)
  return unless input.wait_readable(timeout)

  first = input.read_nonblock(1)
  return first unless first == "\e"

  sequence = first.dup
  sequence << input.read_nonblock(1) while sequence.length < 6 && input.wait_readable(0.005)
  { "\e[A" => :up, "\e[B" => :down, "\e[5~" => :page_up, "\e[6~" => :page_down }
    .fetch(sequence, :escape)
rescue IO::WaitReadable
  nil
end

#runObject



22
23
24
25
26
27
28
29
# File 'lib/kitsune/kit/tui/terminal.rb', line 22

def run
  raise Errors::ConfigurationError, "the TUI requires an interactive terminal" unless tty?

  enter
  yield self
ensure
  restore
end

#sizeObject



31
32
33
34
35
36
# File 'lib/kitsune/kit/tui/terminal.rb', line 31

def size
  rows, columns = output.winsize
  [columns, rows]
rescue SystemCallError, NoMethodError
  [100, 30]
end

#tty?Boolean

Returns:

  • (Boolean)


20
# File 'lib/kitsune/kit/tui/terminal.rb', line 20

def tty? = input.tty? && output.tty?