Class: Dephine::TUI

Inherits:
Object
  • Object
show all
Defined in:
lib/dephine/tui.rb

Overview

Public: Terminal User Interface for making a simple UI. All methods are instance methods and should be called on an instance.

Examples

t = TUI.new
t.puts 'it uses ncurses'
t.close
# => 'it uses ncurses'

Instance Method Summary collapse

Constructor Details

#initializeTUI

Public: Initialize a terminal user interface.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/dephine/tui.rb', line 16

def initialize
  Ncurses.initscr
  Ncurses.nonl
  Ncurses.cbreak
  Ncurses.noecho

  @screen = Ncurses.stdscr
  @screen.scrollok(true)
  @screen.keypad(true)

  @top = 0
  @contexts = []
  @callbacks = {}
end

Instance Method Details

#closeObject

Public: Close the created terminal user interface. This method should be called for closing the terminal user interface.

Returns nothing.



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/dephine/tui.rb', line 152

def close
  @contexts[0..maxy-1].each_with_index do |line, idx|
    @screen.move(idx, 0)
    @screen.addstr(line.to_s)
  end

  @screen.move(0, 0)
  @screen.refresh
  hotkeys
  Ncurses.endwin
end

#maxyObject



31
32
33
# File 'lib/dephine/tui.rb', line 31

def maxy
  @screen.getmaxy
end

#puts(text = '') ⇒ Object

Public: Add a String to an Array named ‘contexts’. This method basically doesn’t act like the built-in method ‘puts’, but values of ‘contexts’ will be printed.

text - The String that will be pushed to an Array.

Returns the contexts Array.



42
43
44
# File 'lib/dephine/tui.rb', line 42

def puts(text = '')
  @contexts << text
end

#scroll_downObject

Public: Move down the scroll.

Returns true or false.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/dephine/tui.rb', line 70

def scroll_down
  if @top + maxy < @contexts.length
    @screen.scrl(1)
    @top += 1
    str = @contexts[@top + maxy - 1]

    if str
      @screen.move(maxy - 1, 0)
      @screen.addstr(str)
    end

    true

  else
    false
  end
end

#scroll_upObject

Public: Move up the scroll.

Returns true or fase.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/dephine/tui.rb', line 49

def scroll_up
  if @top > 0
    @screen.scrl(-1)
    @top -= 1
    str = @contexts[@top]

    if str
      @screen.move(0, 0)
      @screen.addstr(str)
    end

    true

  else
    false
  end
end

#set_key(key, &block) ⇒ Object

Public: Set a hot-key for calling a block.

key - The key to be set as a hot-key. block - The block to be called when pressing the key.

Examples

set_key 'q' do
  quit
end
# => nil

Returns nothing.



144
145
146
# File 'lib/dephine/tui.rb', line 144

def set_key(key, &block)
  @callbacks[key.ord] = block
end