Removed some functionality from `Key`. Going to re-work that API into a `KeySequence...
[nfoiled.git] / lib / nfoiled.rb
blob8c97c44dd31faf6df8302fd43d9ca5fe9fe7d516
1 require 'nfoiled/terminal'
2 require 'nfoiled/window'
4 require 'ncurses'
6 ##
7 # See `README.markdown`.
8 module Nfoiled
9   Version = 0
10   
11   class <<self
12     attr_accessor :initialized; alias_method :initialized?, :initialized
13     
14     ##
15     # This module method is responsible for setting up the entirety of Nfoiled's
16     # overall environment. It will be called before any other Nfoiled
17     # functionality is allowed. In most cases, this will be called for you.
18     # 
19     # This method also schedules `Nfoiled::finalize` to be automatically run
20     # `at_exit`.
21     def initialize!
22       self.initialized = true
23       Terminal.default = Terminal.new unless Terminal.current
24       
25       ::Ncurses.noecho # Characters will not be printed to the terminal by Ncurses for us
26       ::Ncurses.cbreak # No character processing is done, each individual character will be returned to `#getch`
27       ::Ncurses.raw    # Interrupt etc signals are all directed to us instead of handled by Ncurses
28       
29       at_exit { Nfoiled.finalize }
30     end
31     
32     ##
33     # This module method ensures that Nfoiled is initialized. It simply calls
34     # `Nfoiled::initialize!` if Nfoiled hasn't already been initialized.
35     def initialize
36       initialize! unless initialized?
37     end
38     public :initialize
39     
40     ##
41     # Causes an cycling of the physical window with the virtual window.
42     # 
43     # Warning: You have to update the virtual window first!
44     def update!
45       # We need to ensure that the current input acceptor will have the cursor
46       # at all times, so we force a refresh on it (Ncurses leaves the cursor
47       # on the last window to be updated). See `doupdate(3X)`.
48       Terminal.current.acceptor.update
49       ::Ncurses.doupdate
50     end
51     
52     ##
53     # This method is responsible for tearing down any environment set up by the
54     # `Ncurses::initialize!` method. See `endwin(3X)`.
55     def finalize!
56       self.initialized = false
57       ::Ncurses.endwin
58       Terminal.terminals.each {|t| t.destroy! }
59       Terminal.current, Terminal.default = nil
60     end
61     
62     ##
63     # This module method ensures that Nfoiled is finalize. It simply calls
64     # `Nfoiled::finalize!` if Nfoiled hasn't already been finalized.
65     def finalize
66       # TODO: Ensure finalization on fatal errors or interrupts
67       finalize! if initialized?
68     end
69   end
70   
71 end