| 1 | package Dallycot::Channel::Terminal; | ||
| 2 | our $AUTHORITY = 'cpan:JSMITH'; | ||
| 3 | |||
| 4 | # ABSTRACT: Term::ReadLine-based i/o channel | ||
| 5 | |||
| 6 | use utf8; | ||
| 7 | use Moose; | ||
| 8 | extends 'Dallycot::Channel'; | ||
| 9 | |||
| 10 | use Promises qw(deferred); | ||
| 11 | use Term::ReadLine; | ||
| 12 | |||
| 13 | has term => ( | ||
| 14 | is => 'ro', | ||
| 15 | default => sub { | ||
| 16 | Term::ReadLine->new('Dallycot Terminal'); | ||
| 17 | } | ||
| 18 | ); | ||
| 19 | |||
| 20 | sub can_send { | ||
| 21 | my ($self) = @_; | ||
| 22 | |||
| 23 | return defined( $self->term->OUT ); | ||
| 24 | } | ||
| 25 | |||
| 26 | sub can_receive { | ||
| 27 | my ($self) = @_; | ||
| 28 | |||
| 29 | return defined( $self->term->IN ); | ||
| 30 | } | ||
| 31 | |||
| 32 | sub has_history { return 1 } | ||
| 33 | |||
| 34 | sub send_data { | ||
| 35 | my ( $self, @stuff ) = @_; | ||
| 36 | |||
| 37 | # For now, this is synchronous | ||
| 38 | |||
| 39 | my $OUT = $self->term->OUT; | ||
| 40 | return unless defined $OUT; | ||
| 41 | |||
| 42 | print $OUT @stuff; | ||
| 43 | |||
| 44 | return; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub receive_data { | ||
| 48 | my ( $self, %options ) = @_; | ||
| 49 | |||
| 50 | my $d = deferred; | ||
| 51 | |||
| 52 | if ( $self->can_receive ) { | ||
| 53 | my $prompt = $options{'prompt'}; | ||
| 54 | my $line; | ||
| 55 | if ( defined $prompt ) { | ||
| 56 | $prompt = $prompt->value; | ||
| 57 | $line = $self->term->readline($prompt); | ||
| 58 | } | ||
| 59 | else { | ||
| 60 | $line = $self->term->readline; | ||
| 61 | } | ||
| 62 | if ( defined $line ) { | ||
| 63 | $d->resolve( Dallycot::Value::String->new($line) ); | ||
| 64 | } | ||
| 65 | else { | ||
| 66 | $d->resolve( Dallycot::Value::Undefined->new ); | ||
| 67 | } | ||
| 68 | } | ||
| 69 | else { | ||
| 70 | $d->reject('Unable to read'); | ||
| 71 | } | ||
| 72 | |||
| 73 | return $d->promise; | ||
| 74 | } | ||
| 75 | |||
| 76 | sub add_history { | ||
| 77 | my ( $self, $line ) = @_; | ||
| 78 | |||
| 79 | $self->term->addhistory( $line->value ); | ||
| 80 | return; | ||
| 81 | } | ||
| 82 | |||
| 83 | __PACKAGE__ -> meta -> make_immutable; | ||
| 84 | |||
| 85 | 1; |