Question

So, I just started trying to use the perl curses module for a project I'm working on. The documentation seems to be extremely lacking, what little I can find on cpan seems to be half-finished and assumes previous curses library experience, which I don't have. I have two issues I am trying to solve, my code so far:

#!/usr/bin/perl

use strict;
use Curses::UI;
use Term::ReadKey;

my ($cols, $rows, $wp, $hp) = GetTerminalSize();

my $cui = new Curses::UI( -color_support => 1);

sub eDialog {
    my $return = $cui->dialog(
        -message    => "Are you sure?",
        -title      => "Really quit?",
        -buttons    => ['yes', 'no']
        );
    exit(0) if $return;
}

sub entryUpdate {
    my $mainentry = shift;
    if($mainEntry->get() =~ m/.*\n$/)
    {
        print STDERR $mainEntry->get();
    }
}

$cui->set_binding( \&eDialog , "\cQ");

my $mainWin = $cui->add(
    'viewWin', 'Window',
    -border => 1,
    -height => ($rows - 3),
    -bfg    => 'green'
    );

my $mainView = $mainWin->add(
    "viewWid", "TextViewer",
    -wrapping => 1
    );


my $entryWin = $cui->add(
    'entryWin', 'Window',
    -border => 1,
    -y      => ($rows - 3),
    -height => 1,
    -bfg    => 1
    );

my $mainEntry = $entryWin->add(
    "entryWid", "TextEntry",
    -onchange => \&entryUpdate()
    );

$mainEntry->focus();
$cui->mainloop();

I managed to get the UI set up how I want it, but actually making it work is proving problematic.

1). I want to be able to, when text is typed into the $mainEntry widget, detect when enter/return is pressed, and execute a subroutine to do stuff with the text typed into the widget, then clear it out. (I tried accomplishing this with the entryUpdate subroutine, but that isn't working at all, no matter how I've tried to do it.)

2). I want to be able to periodically (Say, every 1 second or 500ms), execute another subroutine, and have the string it returns added to the $mainView widget.

Getting either or both of these to work has proven to be a huge issue thus far, I just dont know enough about how curses works and I haven't been able to find the information I need anywhere. Any help would be much appreciated.

Was it helpful?

Solution

1) You can simply bind the return key to a subrouting using set_binding:

use Curses qw(KEY_ENTER);
$mainEntry->set_binding(sub {
    $mainView->text($mainView->text . $mainEntry->get . "\n");
    $mainView->draw;
    $mainEntry->text("");
}, KEY_ENTER);

2) It seems that there are timer methods (found them by grepping the Curses-UI source code), but they are not documented, which is probably an issue. Here's how it's used:

$cui->set_timer('timer_name', sub {
    $mainView->text($mainView->text . scalar(localtime)."\n");
    $mainView->draw;
}, 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top