summaryrefslogtreecommitdiff
path: root/lib/highline/terminal/unix_stty.rb
blob: ad9c85df29e01d45b4e067dd9b96d35dd33394b3 (plain)
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
# coding: utf-8

class HighLine
  class Terminal
    # HighLine::Terminal option that uses external "stty" program
    # to control terminal options.
    class UnixStty < Terminal
      # A Unix savvy method using stty to fetch the console columns, and rows.
      # ... stty does not work in JRuby
      # @return (see Terminal#terminal_size)
      def terminal_size
        begin
          require "io/console"
          winsize = begin
                      IO.console.winsize.reverse
                    rescue NoMethodError
                      nil
                    end
          return winsize if winsize
        rescue LoadError
        end

        if /solaris/ =~ RUBY_PLATFORM &&
           `stty` =~ /\brows = (\d+).*\bcolumns = (\d+)/
          [Regexp.last_match(2), Regexp.last_match(1)].map(&:to_i)
        elsif `stty size` =~ /^(\d+)\s(\d+)$/
          [Regexp.last_match(2).to_i, Regexp.last_match(1).to_i]
        else
          [80, 24]
        end
      end

      # (see Terminal#raw_no_echo_mode)
      def raw_no_echo_mode
        @state = `stty -g`
        system "stty raw -echo -icanon isig"
      end

      # (see Terminal#restore_mode)
      def restore_mode
        system "stty #{@state}"
        print "\r"
      end

      # (see Terminal#get_character)
      def get_character(input = STDIN)
        input.getc
      end
    end
  end
end