Console.java 2.11 KB
package pad.prac1;

import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;
import java.util.regex.Pattern;

public class Console implements Observer 
{
	private int currentCol;
	private int currentRow;
	
	public void updateCurrentPos()
	{
		Coordinate pos = getCurrentPos();
		currentCol = pos.x();
		currentRow = pos.y();
	}
	
	public Coordinate getCurrentPos()
	{
		System.out.print((char)EditableBufferedReader.ESC);
		System.out.print((char)EditableBufferedReader.ESC_SEQ);
		System.out.print("6n");
		Pattern pattern = Pattern.compile("(\\d*);(\\d*)");
		Scanner scanner = new Scanner(System.in);
        scanner.findWithinHorizon(pattern,0); 
		return new Coordinate(Integer.parseInt(scanner.match().group(2)),
							  Integer.parseInt(scanner.match().group(1)));
	}
	
	public void moveCursorTo(Coordinate xy)
	{
		System.out.print((char)EditableBufferedReader.ESC);
		System.out.print((char)EditableBufferedReader.ESC_SEQ);
		System.out.print(xy.y());
		System.out.print(';');
		System.out.print(xy.x());
		System.out.print((char)EditableBufferedReader.GOTO);
	}
	
	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)
	{
		updateCurrentPos();
		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:
				Coordinate xy = new Coordinate(cmd.getValue(),currentRow);
				//Gestionar si excede el numero de columnas con modulos y asi
				moveCursorTo(xy);
			break;
		}
	}
}