File: win_console.rb

package info (click to toggle)
ruby-tty-reader 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 772 kB
  • sloc: ruby: 1,759; sh: 4; makefile: 4
file content (90 lines) | stat: -rw-r--r-- 2,101 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# frozen_string_literal: true

require_relative "keys"

module TTY
  class Reader
    class WinConsole
      ESC     = "\e"
      NUL_HEX = "\x00"
      EXT_HEX = "\xE0"

      # Key codes
      #
      # @return [Hash[Symbol]]
      #
      # @api public
      attr_reader :keys

      # Escape codes
      #
      # @return [Array[Integer]]
      #
      # @api public
      attr_reader :escape_codes

      def initialize(input)
        require_relative "win_api"
        @input = input
        @keys = Keys.ctrl_keys.merge(Keys.win_keys)
        @escape_codes = [[NUL_HEX.ord], [ESC.ord], EXT_HEX.bytes.to_a]
      end

      # Get a character from console blocking for input
      #
      # @param [Boolean] echo
      #   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
      #   whether to wait for input or not, defaults to false
      #
      # @return [String]
      #
      # @api private
      def get_char(echo: true, raw: false, nonblock: false)
        if raw && echo
          if nonblock
            get_char_echo_non_blocking
          else
            get_char_echo_blocking
          end
        elsif raw && !echo
          nonblock ? get_char_non_blocking : get_char_blocking
        elsif !raw && !echo
          nonblock ? get_char_non_blocking : get_char_blocking
        else
          @input.getc
        end
      end

      # Get the char for last key pressed, or if no keypress return nil
      #
      # @api private
      def get_char_non_blocking
        input_ready? ? get_char_blocking : nil
      end

      def get_char_echo_non_blocking
        input_ready? ? get_char_echo_blocking : nil
      end

      def get_char_blocking
        WinAPI.getch.chr
      end

      def get_char_echo_blocking
        WinAPI.getche.chr
      end

      # Check if IO has user input
      #
      # @return [Boolean]
      #
      # @api private
      def input_ready?
        !WinAPI.kbhit.zero?
      end
    end # Console
  end # Reader
end # TTY