App-Lorem-Tickit

 view release on metacpan or  search on metacpan

Tickit/Widget.pm  view on Meta::CPAN

package App::Lorem::Tickit::Widget;

use parent 'Tickit::Widget';
use strict;
use warnings;

use App::Lorem::Tickit::TextWidget;
use Text::Lorem;
use Tickit::Pen;
use Tickit::Widget::Choice;
use Tickit::Widget::ScrollBox;

our $VERSION = 0.01;

sub new {
	my ($class, %args) = @_;

	my $self = $class->SUPER::new(%args);
	$self->{'_counts'} = {
		'paragraphs' => 3,
		'sentences' => 8,
		'words' => 50,
	};
	$self->{'_lorem'} = Text::Lorem->new;
	$self->{'_version'} = $args{'version'} || $VERSION;
	$self->{'_choice'} = Tickit::Widget::Choice->new(
		'choices' => [
			['paragraphs', 'paragraphs'],
			['sentences', 'sentences'],
			['words', 'words'],
		],
		'on_changed' => sub {
			$self->_regenerate;
			$self->redraw;
			return;
		},
	);
	$self->{'_text_widget'} = App::Lorem::Tickit::TextWidget->new;
	$self->{'_scrollbox'} = Tickit::Widget::ScrollBox->new(
		'vertical' => 'on_demand',
		'horizontal' => 0,
	)->set_child($self->{'_text_widget'});
	$self->_regenerate;

	return $self;
}

sub CAN_FOCUS {
	return 1;
}

sub cols {
	return 40;
}

sub lines {
	return 10;
}

sub window_gained {
	my $self = shift;

	$self->SUPER::window_gained(@_);
	$self->reshape;

	return;
}

sub window_lost {
	my $self = shift;

	if ($self->{'_choice'}->window) {
		$self->{'_choice'}->window->close;
		$self->{'_choice'}->set_window(undef);
	}
	if ($self->{'_scrollbox'}->window) {
		$self->{'_scrollbox'}->window->close;
		$self->{'_scrollbox'}->set_window(undef);
	}

	$self->SUPER::window_lost(@_);

	return;
}

sub on_key {
	my $self = shift;
	my ($ev) = @_;
	my $key = $ev->str;

	if ($key eq '+') {
		$self->_change_count(1);
		return 1;
	} elsif ($key eq '-') {
		$self->_change_count(-1);
		return 1;
	} elsif ($key eq 'Tab' || $key eq 'Down' || $key eq 'Right') {
		$self->_next_choice;
		return 1;
	} elsif ($key eq 'Up' || $key eq 'Left') {
		$self->_prev_choice;
		return 1;
	} elsif ($key eq 'Enter' || $key eq 'Space') {
		$self->_regenerate;
		$self->redraw;
		return 1;
	} elsif ($key eq 'PageUp') {
		$self->_scroll_page(-1);
		return 1;
	} elsif ($key eq 'PageDown') {
		$self->_scroll_page(1);
		return 1;
	} elsif ($key eq 'q' || $key eq 'C-c') {
		$self->window->tickit->stop if $self->window;
		return 1;
	}

	return 0;
}

sub reshape {
	my $self = shift;
	my $win = $self->window;

	return if ! $win;

	my $cols = $win->cols;
	my $choice_win = $self->{'_choice'}->window;
	my $text_top = 3;
	my $text_lines = _max(0, $win->lines - $text_top - 1);
	my $scroll_win = $self->{'_scrollbox'}->window;

	if ($choice_win) {
		$choice_win->change_geometry(0, 0, 1, $cols);
	} else {
		$choice_win = $win->make_sub(0, 0, 1, $cols);
		$self->{'_choice'}->set_window($choice_win);
	}
	$self->{'_choice'}->take_focus;
	$self->_sync_text_widget;



( run in 1.840 second using v1.01-cache-2.11-cpan-98e64b0badf )