lib/ruby_jard/console.rb in ruby_jard-0.3.0 vs lib/ruby_jard/console.rb in ruby_jard-0.3.1

- old
+ new

@@ -6,38 +6,66 @@ module RubyJard # Wrapper for utilities to control screen class Console class << self - def start_alternative_terminal(output) - return unless output.tty? + def attachable? + return false unless output.tty? - output.print tput('smcup') - rescue RubyJard::Error - # If tput not found, fallback to hard-coded sequence. - output.print "\e[?1049h\e[22;0;0t" + width, height = screen_size(output) + width != 0 && height != 0 end - def stop_alternative_terminal(output) - return unless output.tty? + def redirected? + output != $stdout + end - output.print tput('rmcup') - rescue RubyJard::Error - # If tput not found, fallback to hard-coded sequence. - output.print "\e[?1049l\e[23;0;0t" + def output + return @output if defined?(@output) + + @output = + if STDOUT.tty? + STDOUT + else + begin + File.open('/dev/tty', 'w+') + rescue StandardError + STDOUT # Give up now. + end + end end + def input + return @input if defined?(@input) + + @input = + if STDIN.tty? + STDIN + else + begin + File.open('/dev/tty', 'r+') + rescue StandardError + STDIN # Give up. + end + end + end + def move_to(output, x, y) return unless output.tty? output.print format("\e[%<row>d;%<col>dH", row: y + 1, col: x + 1) end def screen_size(output) return [0, 0] unless output.tty? - [TTY::Screen.width, TTY::Screen.height] + if output.respond_to?(:winsize) + height, width = output.winsize + [width, height] + else + [TTY::Screen.width, TTY::Screen.height] + end end def clear_screen(output) return unless output.tty? @@ -48,20 +76,20 @@ return unless output.tty? output.print "\e[0J" end - def disable_cursor!(output = STDOUT) + def disable_cursor!(output) return unless output.tty? output.print tput('civis') rescue RubyJard::Error # If tput not found, fallback to hard-coded sequence. output.print "\e[?25l" end - def enable_cursor!(output = STDOUT) + def enable_cursor!(output) return unless output.tty? output.print tput('cnorm') rescue RubyJard::Error # If tput not found, fallback to hard-coded sequence. @@ -79,42 +107,42 @@ end rescue IO::WaitWritable nil end - def raw!(output = STDOUT) + def raw!(output) return unless output.tty? begin output.raw! rescue StandardError stty('raw') end end - def cooked!(output = STDOUT) + def cooked!(output) return unless output.tty? begin output.cooked! rescue StandardError # If stty not found, or raise error, nothing I can do stty('-raw') end end - def disable_echo!(output = STDOUT) + def disable_echo!(output) return unless output.tty? begin output.echo = false rescue StandardError # If stty not found, or raise error, nothing I can do stty('-echo') end end - def enable_echo!(output = STDOUT) + def enable_echo!(output) return unless output.tty? begin output.echo = true rescue StandardError