Added a proc to deal with keys to `Window`
[nfoiled.git] / lib / nfoiled / window.rb
blob18e36af7ff7b4e5b2ff0e3e12e7a882a3892ba90
1 module Nfoiled
2   ##
3   # An `Nfoiled::Window` is a "box" in the terminal to which output can be
4   # printed and from which input can be received. A basic Nfoiled application
5   # will utilize only one of these, a single `Window` covering the entirety
6   # of the `Terminal`'s available area.
7   class Window
8     
9     class <<self
10       # This is simply an accessor for all the windows on the current Terminal.
11       attr_reader :windows
12       def windows; Terminal.current.windows; end
13     end
14     
15     # ==============
16     # = Attributes =
17     # ==============
18     
19     # The Y co-ordinate of the top left corner of this `Window`'s bounding box
20     attr_reader :top
21     # The X co-ordinate of the top left corner of this `Window`'s bounding box
22     attr_reader :left
23     # The height in lines of this `Window`'s bounding box
24     attr_reader :height
25     # The width in columns of this `Window`'s bounding box
26     attr_reader :width
27     
28     # The actual window object as returned by Ncurses
29     attr_reader :wrapee
30     
31     # The `Terminal` that this `Window` pertains to
32     attr_reader :owner
33     
34     # The proc to be run when a character is received
35     attr_accessor :on_key
36     
37     # ====================
38     # = Setup / Teardown =
39     # ====================
40     
41     ##
42     # Responsible for creating a new `Window`, this will also take care of
43     # initializing Ncurses if necessary.
44     def initialize opts = Hash.new
45       Nfoiled::initialize
46       
47       @wrapee = ::Ncurses.newwin(
48         opts[:height] ? @height = opts[:height] : ::Ncurses.LINES,
49         opts[:width]  ? @width =  opts[:width]  : ::Ncurses.COLS,
50         opts[:top]    ? @top =    opts[:top]    : 0,
51         opts[:left]   ? @left =   opts[:left]   : 0)
52       
53       (@owner = Terminal.current).windows << self
54     end
55     
56     ##
57     # Destroys the `wrapee` of this `Window`, and removes this `Window`
58     # from its owning `Terminal`'s `#windows`.
59     def destroy!
60       ::Ncurses.delwin(@wrapee)
61       @wrapee = nil
62       @owner.windows.delete self
63     end
64     
65     # =========
66     # = Input =
67     # =========
68     
69     # This acts as both a getter & setter, depending on whether a block is
70     # passed in or not.
71     def on_key
72       block_given? ? @on_key = Proc.new : @on_key
73     end
74     
75     # ==========
76     # = Output =
77     # ==========
78     
79     ##
80     # Prints a string to the window
81     def print string
82       @wrapee.printw string
83       @wrapee.wnoutrefresh
84     end
85     
86     ##
87     # Prints a string, followed by a newline, to the window
88     def puts string
89       self.print string.to_s + "\n"
90     end
91   end
92 end