Blame view

readline/src/pad/prac1/EditableBufferedReader.java 1.39 KB
Imanol-Mikel Barba Sabariego authored
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
69
70
71
72
73
74
75
76
77
78
package pad.prac1;
import java.io.*;


public class EditableBufferedReader extends BufferedReader 
{
	private String line = "";
	private boolean returnKey = false;

	public EditableBufferedReader(Reader in)
	{
		super(in);
	}

	public EditableBufferedReader(Reader in, int sz)
	{
		super(in,sz);
	}

	private void setRaw() throws IOException, InterruptedException
	{
		String[] cmd = {"/bin/sh", "-c", "stty raw -echo </dev/tty"};
		Runtime.getRuntime().exec(cmd).waitFor();
	}

	private void unsetRaw() throws IOException, InterruptedException
	{
		String[] cmd = {"/bin/sh", "-c", "stty -raw echo </dev/tty"};
		Runtime.getRuntime().exec(cmd).waitFor();
	}

	public int read() throws IOException
	{
		return super.read();
	}

	public String readLine()
	{
		try 
		{
			setRaw();
		} 
		catch (Exception e) 
		{
			System.out.println("Couldn't set terminal in raw mode");
			return "";
		}
		while(!returnKey)
		{
			try 
			{
				int character = read();
				switch(character)
				{
					case 0x0D:
						returnKey = true;
						break;
					default:
						line += (char)character;
						System.out.print((char)character);
						break;
				}
			} 
			catch (IOException e)
			{
				System.out.println("Couldn't unset raw mode");
				break;
			}
		}
		try 
		{
			unsetRaw();
		} 
		catch (Exception e) 
		{
			System.out.println("Couldn't unset raw mode");
			return "";
		}
79
		System.out.println("");
Imanol-Mikel Barba Sabariego authored
80
81
82
		return line;
	}
}