Blame view

readline/src/pad/prac1/Console.java 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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;
		}
	}
}