Added examples for `Terminal#term`
[nfoiled.git] / lib / nfoiled / terminal.rb
blobc60c414a6226c1ea0fbbfaebd7b054824cf50e09
1 module Nfoiled
2   ##
3   # An `Nfoiled::Terminal` is a specific set of Nfoiled windows and
4   # configuration. In the vast majority of cases, you only need one of these,
5   # and that one will be created for you by `Nfoiled::initialize`. A general
6   # user shouldn't need to deal with `Terminal` at all.
7   class Terminal
8     
9     class MissingTerminalError < StandardError; end
10     
11     class <<self
12       # An array of known `Terminal` instances
13       attr_reader :terminals
14       def terminals; @terminals ||= Array.new; end
15       
16       # The currently active `Terminal` instance
17       attr_accessor :current
18       
19       # The initial `Terminal` instance, if Nfoiled is initialized without an
20       # existing `Terminal`.
21       attr_accessor :default
22     end
23     
24     # The IO object to which output will be managed
25     attr_reader :output
26     
27     # The IO object on which input will be watched
28     attr_reader :input
29     
30     # The type of the terminal ('vt102', 'xterm', etc)
31     attr_reader :term
32     
33     # The actual terminal object as returned by Ncurses
34     attr_reader :wrapee
35     
36     # An array of known windows belonging to this Terminal
37     attr_reader :windows
38     def windows; @windows ||= Array.new; end
39     
40     ##
41     # Responsible for creating a new `Terminal`. See `newterm(3X)`.
42     def initialize opts = Hash.new
43       { :output => STDOUT, :input => STDIN }.merge opts
44       @output = opts[:output]
45       @input = opts[:input]
46       @term = opts[:term]
47       
48       @wrapee = ::Ncurses.newterm(opts[:term], opts[:out], opts[:in])
49       Terminal.current = self
50       Terminal.terminals << self
51       Nfoiled::initialize
52     end
53     
54     ##
55     # This method raises an error if it is called when this `Terminal` is no
56     # longer useable.
57     def require_wrapee!
58       raise MissingTerminalError, "Terminal not found! (did you `#destroy!` it?)" unless
59         @wrapee and Terminal.terminals.include?(self)
60     end
61     
62     ##
63     # Destroys the `wrapee` of this `Terminal`, and removes this `Terminal`
64     # from `Terminal.terminals`.
65     def destroy!
66       require_wrapee!
67       ::Ncurses.delscreen(@wrapee)
68       Terminal.terminals.delete self
69       @wrapee = nil
70     end
71   end
72 end