Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 250 lines (182 sloc) 6.24 kb
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
#!/usr/bin/perl -w

package POE::Wheel::Curses;

use strict;

use vars qw($VERSION);
$VERSION = '1.020'; # NOTE - Should be #.### (three decimal places)

use Carp qw(croak);
use Curses qw(
initscr start_color cbreak raw noecho nonl nodelay timeout keypad
intrflush meta typeahead mousemask ALL_MOUSE_EVENTS clear refresh
endwin COLS
);
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
use POE qw( Wheel );

sub SELF_STATE_READ () { 0 }
sub SELF_STATE_WRITE () { 1 }
sub SELF_EVENT_INPUT () { 2 }
sub SELF_ID () { 3 }

sub new {
  my $type = shift;
  my %params = @_;

  croak "$type needs a working Kernel" unless defined $poe_kernel;

  my $input_event = delete $params{InputEvent};
  croak "$type requires an InputEvent parameter" unless defined $input_event;

  if (scalar keys %params) {
    carp( "unknown parameters in $type constructor call: ",
          join(', ', keys %params)
        );
  }

  # Create the object.
  my $self = bless
    [ undef, # SELF_STATE_READ
      undef, # SELF_STATE_WRITE
      $input_event, # SELF_EVENT_INPUT
      &POE::Wheel::allocate_wheel_id(), # SELF_ID
    ];

  # Set up the screen, and enable color, mangle the terminal and
  # keyboard.

  initscr();
  start_color();

  cbreak();
  raw();
  noecho();
  nonl();

  # Both of these achieve nonblocking input.
  nodelay(1);
  timeout(0);

  keypad(1);
  intrflush(0);
  meta(1);
  typeahead(-1);

  my $old_mouse_events = 0;
  mousemask(ALL_MOUSE_EVENTS, $old_mouse_events);

  clear();
  refresh();

  # Define the input event.
  $self->_define_input_state();

  # Oop! Return ourself. I forgot to do this.
  $self;
}

sub _define_input_state {
  my $self = shift;

  # Register the select-read handler.
  if (defined $self->[SELF_EVENT_INPUT]) {
    # Stupid closure tricks.
    my $event_input = \$self->[SELF_EVENT_INPUT];
    my $unique_id = $self->[SELF_ID];

    $poe_kernel->state
      ( $self->[SELF_STATE_READ] = ref($self) . "($unique_id) -> select read",
        sub {

          # Prevents SEGV in older Perls.
          0 && CRIMSON_SCOPE_HACK('<');

          my ($k, $me) = @_[KERNEL, SESSION];

          # Curses' getch() normally blocks, but we've already
          # determined that STDIN has something for us. Be explicit
          # about which getch() to use.
          while ((my $keystroke = Curses::getch) ne '-1') {
            $k->call( $me, $$event_input, $keystroke, $unique_id );
          }
        }
      );

    # Now start reading from it.
    $poe_kernel->select_read( \*STDIN, $self->[SELF_STATE_READ] );

    # Turn blocking back on for STDIN. Some Curses implementations
    # don't deal well with non-blocking STDIN.
    my $flags = fcntl(STDIN, F_GETFL, 0) or die $!;
    fcntl(STDIN, F_SETFL, $flags & ~O_NONBLOCK) or die $!;
  }
  else {
    $poe_kernel->select_read( \*STDIN );
  }
}

sub DESTROY {
  my $self = shift;

  # Turn off the select.
  $poe_kernel->select( \*STDIN );

  # Remove states.
  if ($self->[SELF_STATE_READ]) {
    $poe_kernel->state($self->[SELF_STATE_READ]);
    $self->[SELF_STATE_READ] = undef;
  }

  # Restore the terminal.
  endwin if COLS;

  &POE::Wheel::free_wheel_id($self->[SELF_ID]);
}

1;

__END__

=head1 NAME

POE::Wheel::Curses - non-blocking input for Curses

=head1 SYNOPSIS

use Curses;
use POE qw(Wheel::Curses);

POE::Session->create(
inline_states => {
_start => sub {
$_[HEAP]{console} = POE::Wheel::Curses->new(
InputEvent => 'got_keystroke',
);
},
got_keystroke => sub {
my $keystroke = $_[ARG0];

# Make control and extended keystrokes printable.
if ($keystroke lt ' ') {
$keystroke = '<' . uc(unctrl($keystroke)) . '>';
}
elsif ($keystroke =~ /^\d{2,}$/) {
$keystroke = '<' . uc(keyname($keystroke)) . '>';
}

# Just display it.
addstr($keystroke);
noutrefresh();
doupdate;

# Gotta exit somehow.
delete $_[HEAP]{console} if $keystroke eq "<^C>";
},
}
);

POE::Kernel->run();
exit;

=head1 DESCRIPTION

POE::Wheel::Curses implements non-blocking input for Curses programs.

POE::Wheel::Curses will emit an "InputEvent" of your choosing whenever
an input event is registered on a recognized input device (keyboard
and sometimes mouse, depending on the curses library). Meanwhile,
applications can be doing other things like monitoring network
connections or child processes, or managing timers and stuff.

=head1 PUBLIC METHODS

POE::Wheel::Curses is rather simple.

=head2 new

new() creates a new POE::Wheel::Curses object. During construction,
the wheel registers an input watcher for STDIN (via select_read()) and
registers an internal handler to preprocess keystrokes.

new() accepts only one parameter C<InputEvent>. C<InputEvent>
contains the name of the event that the wheel will emit whenever there
is input on the console or terminal. As with all wheels, the event
will be sent to the session that was active when the wheel was
constructed.

It should be noted that an application may only have one active
POE::Wheel::Curses object.

=head1 EVENTS AND PARAMETERS

These are the events sent by POE::Wheel::Curses.

=head2 InputEvent

C<InputEvent> defines the event that will be emitted when
POE::Wheel::Curses detects and reads console input. This event
includes two parameters:

C<$_[ARG0]> contains the raw keystroke as received by Curses::getch().
An application may process the keystroke using Curses::unctrl() and
Curses::keyname() on the keystroke.

C<$_[ARG1]> contains the POE::Wheel::Curses object's ID.

=head1 SEE ALSO

L<Curses> documents what can be done with Curses. Also see the man
page for whichever version of libcurses happens to be installed
(curses, ncurses, etc.).

L<POE::Wheel> describes wheels in general.

The SEE ALSO section in L<POE> contains a table of contents covering
the entire POE distribution.

=head1 BUGS

None known, although curses implementations vary widely.

=head1 AUTHORS & COPYRIGHTS

Please see L<POE> for more information about authors and contributors.

=cut

# rocco // vim: ts=2 sw=2 expandtab
# TODO - Edit.
Something went wrong with that request. Please try again.