summary refs log tree commit diff stats
path: root/code/cli.rb
blob: 3ef382374c1a9802e9f50c767b2bcde863bd5e68 (plain) (blame)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
require 'ncurses'

module CLI
	def self.keytable(key)
		case key
		when 12
			'<redraw>'
		when ?\n
			'<cr>'
		when ?\b, Ncurses::KEY_BACKSPACE, 127
			'<bs>'
		when Ncurses::KEY_RIGHT
			'<right>'
		when Ncurses::KEY_LEFT
			'<left>'
		when Ncurses::KEY_UP
			'<up>'
		when Ncurses::KEY_DOWN
			'<down>'
		when ?\e
			'<esc>'
		when Ncurses::KEY_BTAB
			'<s-tab>'
		when 9
			'<tab>'
		when 1..26 # CTRL + ...
			"<c-#{(key+96).chr}>"
		when 32..127
			key.chr
		else
			''
		end
	end

	def self.included(this)
		@@window = Ncurses.initscr
		starti
	end

	# (Re)Start the Interface
	def starti
		@@running = true
		@@screen = Ncurses.stdscr
		@@screen.keypad(true)
		Ncurses.start_color
		Ncurses.use_default_colors

		Ncurses.noecho
		Ncurses.curs_set 0
		Ncurses.halfdelay(200)
		@@colortable = []
	end

	def self.refresh
		Ncurses.refresh
	end

	# Close the Interface
	def closei
		@@running = false
		Ncurses.echo
		Ncurses.nocbreak
		Ncurses.curs_set 1
		Ncurses.endwin
	end

	def running?() @@running end

	def cleari
		Ncurses.mvaddstr(0, 0, ' ' * (lines * cols))
	end

	def geti
		CLI.keytable(Ncurses.getch)
	end

	def set_title(x)
		print "\e]2;#{x}\007"
	end

	def lines
		Ncurses.LINES
	end

	def cols
		Ncurses.COLS
	end

	def movi(y=0, x=0)
		y < 0 and y += lines
		Ncurses.move(y, x)
	end

	def puti *args
		case args.size
		when 1
			Ncurses.addstr(args[0].to_s)
		when 2
			if (y = args[0]) < 0 then y += Ncurses.LINES end
			Ncurses.mvaddstr(y, 0, args[1].to_s)
		when 3
			if (y = args[0]) < 0 then y += Ncurses.LINES end
			Ncurses.mvaddstr(y, args[1], args[2].to_s)
		end
	end

	def attr_set(fg=-1, bg=-1, attr = nil)
		fg, bg, attr = fg if fg.is_a? Array
		if attr
			Ncurses.attrset(attr | Ncurses.COLOR_PAIR(get_color(fg, bg)))
		else
			Ncurses.color_set(get_color(fg, bg), nil)
		end
	end

	def attr_at(y=0, x=0, len=-1, fg=-1, bg=-1, attr=0)
		fg, bg, attr = fg if fg.is_a? Array
		y += lines if y < 0
		x += cols if x < 0
		attr ||= 0

		Ncurses.mvchgat(y, x, len, attr, get_color(fg, bg), nil)
	end

	def get_color(fg, bg)
		n = bg+2 + 9*(fg+2)
		color = @@colortable[n]
		unless color
			# create a new pair
			size = @@colortable.reject{|x| x.nil? }.size + 1
			Ncurses::init_pair(size, fg, bg)
			color = @@colortable[n] = size
		end
		return color
	end
end