Skip to content

Commit 9bed219

Browse files
committed
getch with timeout
1 parent c52dd97 commit 9bed219

File tree

4 files changed

+13
-7
lines changed

4 files changed

+13
-7
lines changed

justfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ coverage:
1616
open /tmp/coverage/index.html
1717

1818
# format with rubocop
19-
format: (lint "-a")
19+
fmt: (lint "-a")
2020

2121
gem-local:
2222
just banner rake install:local...

lib/table_tennis/util/console.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def winsize(...)
1010
end
1111

1212
# not supported, don't call these
13-
%i[fileno getbyte raw syswrite].each do |name|
13+
%i[fileno getch raw syswrite].each do |name|
1414
define_method(name) do |*args, **kwargs, &block|
1515
if !IO.console
1616
raise "IO.console.#{name} not supported when IO.console is nil"

lib/table_tennis/util/termbg.rb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,18 +118,18 @@ def osc_query(attr)
118118
def read_term_response
119119
# fast forward to ESC
120120
loop do
121-
return if !(ch = Util::Console.getbyte&.chr)
121+
return if !(ch = getch)
122122
break ch if ch == ESC
123123
end
124124
# next char should be either [ or ]
125-
return if !(type = Util::Console.getbyte&.chr)
125+
return if !(type = getch)
126126
return if !(type == "[" || type == "]")
127127

128128
# now read the response. note that the response can end in different ways
129129
# and we have to check for all of them
130130
buf = "#{ESC}#{type}"
131131
loop do
132-
return if !(ch = Util::Console.getbyte&.chr)
132+
return if !(ch = getch)
133133
buf << ch
134134
break if type == "[" && buf.end_with?("R")
135135
break if type == "]" && buf.end_with?(BEL, ST)
@@ -138,6 +138,10 @@ def read_term_response
138138
end
139139
private_class_method :read_term_response
140140

141+
# get the next character, with a 100ms timeout
142+
def getch = Util::Console.getch(min: 0, time: 0.1)
143+
private_class_method :read_term_response
144+
141145
#
142146
# color math
143147
#
@@ -205,7 +209,9 @@ def env_colorfgbg(env = ENV["COLORFGBG"])
205209
private_class_method :env_colorfgbg
206210

207211
def debug(s)
208-
puts "termbg: #{s}" if ENV["TT_DEBUG"]
212+
return if !ENV["TT_DEBUG"]
213+
$stderr.write "termbg: #{s}\r\n"
214+
$stderr.flush
209215
end
210216
private_class_method :debug
211217
end

test/test_helper.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def with_env(env, &block)
8989

9090
class FakeConsole
9191
def fileno = 123
92-
def getbyte = fakeread.shift
92+
def getch(...) = fakeread.shift&.chr
9393
def raw = yield
9494
def syswrite(str) = fakewrite << str
9595
def winsize = [24, 80]

0 commit comments

Comments
 (0)