scanner/ncurses/ncurses.textinput.php

136 lines
3.1 KiB
PHP
Raw Normal View History

<?php
/**
* Text Input
*
* @package Nc
*/
class NcTextInput extends NcWindow {
/**
* @var string Current value
*/
var $value = '';
/**
* @var string Last value
*/
var $last_value = '';
/**
* @var boolean Active
*/
var $active = false;
/**
* @var string Perl regular expression for filtering input
*/
var $filter = false;
/**
* Constructor
*
* Creates a new text input widget
*
* @param NcWindow $parent Parent window
* @param integer $width Width
* @param integer $y Row
* @param integer $x Column
* @param string $value Initial value
* @param string $filter Perl regular expression for filtering input
*/
public function __construct( &$parent, $width, $y, $x, $value = '', $filter = false ) {
parent::__construct( $parent, 1, $width, $y, $x, false );
$this->last_value = $this->value = $value;
$this->filter = $filter !== false && @preg_match( $filter, '' ) !== false ? $filter : false;
$this->update();
}
/**
* Update the input control on the screen
*
* Widget is highlighted when active
*/
public function update() {
$this->attribute_on( NCURSES_A_UNDERLINE );
if( $this->active ) {
$this->attribute_on( NCURSES_A_REVERSE );
}
$this->write_fixed( 0, 0, substr( $this->value, - $this->width ) );
$this->attribute_off( NCURSES_A_UNDERLINE );
$this->attribute_off( NCURSES_A_REVERSE );
}
/**
* Get or set value
*/
public function value( $value = false ) {
if( $value === false ) {
return $this->value;
} else {
$this->value = $value;
}
}
/**
* Activate input widget and accept input
*
* Input ends when the user presses the enter key.
* If a filter has been set and the input does not pass the filter, the value
* reverts to the previous value, and this function returns false.
*
* @return string|boolean Text entered, or false
*/
public function get() {
$this->active = true;
$this->update();
while( $this->active ) {
$key = $this->get_char();
switch( $key ) {
case NCURSES_KEY_BACKSPACE:
$this->value = substr( $this->value, 0, strlen( $this->value ) - 1 );
break;
case 13:
$this->active = false;
break;
default:
if( in_array( $key, range( 32, 126 ) ) ) {
$this->value .= chr( $key );
}
}
$this->update();
}
$this->update();
return $this->filter !== false && @preg_match( $this->filter, $this->value ) < 1 ? false : $this->value;
}
public function focus() {
parent::focus();
$this->active = true;
$this->update();
}
public function blur() {
$this->active = false;
$this->update();
parent::blur();
}
public function on_key_press($key) {
switch( $key ) {
case NCURSES_KEY_BACKSPACE:
$this->value = substr( $this->value, 0, strlen( $this->value ) - 1 );
break;
case 27:
// ESC
$this->value = $this->last_value;
break;
case 9:
// TAB
case 13:
// RETURN
if( $this->value !== $this->last_value ) {
$this->emit('change', $this->value);
}
$this->blur();
break;
default:
if( in_array( $key, range( 32, 126 ) ) ) {
$this->value .= chr( $key );
}
parent::on_key_press($key);
}
$this->update();
}
}
?>