Console.java 1.6 KB
package pad.prac1;

import java.util.Observable;
import java.util.Observer;

public class Console implements Observer 
{
	public void moveCursorTo(int pos, int currentPos, int length)
	{
		if(pos > currentPos)
		{
			System.out.print((char)EditableBufferedReader.ESC);
			System.out.print((char)EditableBufferedReader.ESC_SEQ);
			System.out.print(pos - currentPos);
			System.out.print((char)EditableBufferedReader.FORWARD);
		}
		else if(pos < currentPos)
		{
			System.out.print((char)EditableBufferedReader.ESC);
			System.out.print((char)EditableBufferedReader.ESC_SEQ);
			System.out.print(currentPos-pos);
			System.out.print((char)EditableBufferedReader.BACKWARD);
		}
	}
	
	private void insertSpace()
	{
		System.out.print((char)EditableBufferedReader.ESC);
		System.out.print((char)EditableBufferedReader.ESC_SEQ);
		System.out.print((char)EditableBufferedReader.INS_SPACE);
	}
	
	private void delChar()
	{
		System.out.print((char)EditableBufferedReader.ESC);
		System.out.print((char)EditableBufferedReader.ESC_SEQ);
		System.out.print((char)EditableBufferedReader.DEL_CHAR);
	}
	
	public void addChar(char c, Line line)
	{
		if(line.getCursorPosition() != line.length()+1)
		{
			insertSpace();
		}
		System.out.print(c);
	}
	
	public void update(Observable obs, Object arg)
	{
		Line line = (Line)obs;
		Command cmd = (Command)arg;		
		switch(cmd.getType())
		{
			case Command.INSERT_CHAR:
				addChar((char)cmd.getValue(),line);
			break;
			
			case Command.DELETE_CHAR:
				delChar();
			break;
			
			case Command.MOVE_CURSOR:
				moveCursorTo(cmd.getValue(),line.getCursorPosition(),line.length());
			break;
		}
	}
}