Class: RubyTUI::Input::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/rubytui/input/reader.rb

Overview

Reads terminal input without blocking and decodes it with a Parser.

A lone ESC byte is told apart from the start of an escape sequence by waiting up to ESC_TIMEOUT_MS for more bytes.

Examples:

reader = Input::Reader.new
event = reader.poll(timeout_ms: 50)  # => KeyEvent, MouseEvent or nil

Constant Summary collapse

ESC_TIMEOUT_MS =

Timeout for disambiguating standalone ESC from escape sequences (ms)

50

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin) ⇒ Reader

Returns a new instance of Reader.

Parameters:

  • input (IO) (defaults to: $stdin) —

    input stream; must support IO.select and read_nonblock (default: $stdin)



21
22
23
24
# File 'lib/rubytui/input/reader.rb', line 21

def initialize(input: $stdin)
  @input = input
  @parser = Parser.new
end

Instance Method Details

#poll(timeout_ms: 100) ⇒ KeyEvent, ...

Poll for an event with the given timeout.

Parameters:

  • timeout_ms (Integer) (defaults to: 100) —

    maximum time to wait for input, in milliseconds (default: 100)

Returns:

  • (KeyEvent, MouseEvent, nil) —

    the decoded event, or nil if no input arrived within the timeout or the bytes read were not recognised



32
33
34
35
36
37
38
# File 'lib/rubytui/input/reader.rb', line 32

def poll(timeout_ms: 100)
  timeout_sec = timeout_ms / 1000.0
  ready = IO.select([@input], nil, nil, timeout_sec)
  return nil unless ready

  read_event
end

#read ⇒ KeyEvent, MouseEvent

Blocking read - waits indefinitely for an event.

Calls #poll in a loop until it returns an event.

Returns:



45
46
47
48
49
50
# File 'lib/rubytui/input/reader.rb', line 45

def read
  loop do
    event = poll(timeout_ms: 1000)
    return event if event
  end
end