##
## editfield.py -- Single line editor.
##
## Copyleft 1997 Teemu Kalvas <chery@s2.org>
##

## +class EditField         (screen)  parent screen object
##  -method reset           ()
##  -method insert          (ch)      character to insert (int)
##  -method get_string      ()
##  -method char_left       ()
##  -method char_right      ()
##  -method line_beg        ()
##  -method line_end        ()
##  -method del_char_left   ()
##  -method del_char_right  ()
##  -method reposition      ()
##  -method redraw          ()
##  -method touch           ()

import curses

class EditField:
    def __init__(self, screen):
	self.screen = screen
	self.prompt = '> '
	self.reset()

    def reset(self):
	self.string = self.prompt
	self.offset = 0
	self.position = len(self.string)
	self.redraw()

    def insert(self, ch):
	window = self.screen.edit_area
	width = window.getmaxyx()[1]
	self.string = self.string[:self.position] + chr(ch) + \
		      self.string[self.position:]
	self.position = self.position + 1
	if self.position < self.offset + width:
	    window.insch(0, self.position - self.offset - 1, ch)
	    self.touch()
	else:
	    self.reposition()

    def get_string(self):
	return self.string[len(self.prompt):]

    def char_left(self):
	if self.position > len(self.prompt):
	    self.position = self.position - 1
	    self.reposition()

    def char_right(self):
	if self.position < len(self.string):
	    self.position = self.position + 1
	    self.reposition()

    def line_beg(self):
	self.position = len(self.prompt)
	self.reposition()

    def line_end(self):
	self.position = len(self.string)
	self.reposition()

    def del_char_left(self):
	if self.position > len(self.prompt):
	    self.position = self.position - 1
	    self.string = self.string[:self.position] + \
			  self.string[self.position + 1:]
	    self.redraw()

    def del_char_right(self):
	if self.position < len(self.string):
	    self.string = self.string[:self.position] + \
			  self.string[self.position + 1:]
	    self.redraw()

    def del_line_end(self):
	self.string = self.string[:self.position]
	self.redraw()

    def reposition(self):
	width = self.screen.edit_area.getmaxyx()[1]
	if self.position < self.offset or self.position >= self.offset + width:
	    self.offset = max(0, self.position - width / 2)
	    self.redraw()
	else:
	    self.touch()

    def redraw(self):
	window = self.screen.edit_area
	width = window.getmaxyx()[1]
	if self.position < self.offset or self.position >= self.offset + width:
	    self.offset = max(0, self.position - width / 2)
	window.addstr(0, 0, self.string[self.offset:self.offset + width] +
		      '\n')
	self.touch()

    def touch(self):
	screen = self.screen
	screen.touched = screen.touched | 4
	
## End. ##
