From 241ae75875922da0b88166ff254e1f1cfe3098db Mon Sep 17 00:00:00 2001 From: Ken Mayer Date: Sat, 28 May 2022 17:04:35 +0000 Subject: [PATCH] Overload nonblock semantics with a timeout value Useful if you have an application that would like to sleep at the end of every loop. This will let it wait for & collect the keypress until the sleep would have expired. For example, this loop will sleep until approximately the start of the next second on the system clock. ``` loop do draw now = Time.now.to_f codes = reader.read_keypress(raw: true, nonblock: (now.ceil(0) - now)) command.interpret(codes) if codes end ``` --- lib/tty/reader.rb | 3 ++- lib/tty/reader/console.rb | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/tty/reader.rb b/lib/tty/reader.rb index c30062b..21fec40 100644 --- a/lib/tty/reader.rb +++ b/lib/tty/reader.rb @@ -221,8 +221,9 @@ def unbufferred(&block) # whether to echo chars back or not, defaults to false # @option [Boolean] raw # whenther raw mode is enabled, defaults to true - # @option [Boolean] nonblock + # @option [Boolean, Numeric] nonblock # whether to wait for input or not, defaults to false + # if it's Numeric, then use that for the timeout # # @return [String] # diff --git a/lib/tty/reader/console.rb b/lib/tty/reader/console.rb index d5d41b9..a2eb172 100644 --- a/lib/tty/reader/console.rb +++ b/lib/tty/reader/console.rb @@ -40,8 +40,9 @@ def initialize(input) # whether to echo input back or not, defaults to true # @param [Boolean] raw # whether to use raw mode or not, defaults to false - # @param [Boolean] nonblock + # @param [Boolean, Numeric] nonblock # whether to wait for input or not, defaults to false + # if it's Numeric, then use that for the timeout # # @return [String] # @@ -50,7 +51,7 @@ def get_char(echo: true, raw: false, nonblock: false) mode.raw(raw) do mode.echo(echo) do if nonblock - input.wait_readable(TIMEOUT) ? input.getc : nil + input.wait_readable(nonblock.is_a?(Numeric) ? nonblock : TIMEOUT) ? input.getc : nil else input.getc end