01: package gnu.mapping;
02:
03: import java.io.*;
04: import gnu.text.*;
05:
06: /** An interactive input-port.
07: Supports prompting, auto-flush of tied output port, transcripts. */
08:
09: public class TtyInPort extends InPort {
10: protected OutPort tie;
11:
12: protected Procedure prompter;
13:
14: /** Get the current prompter function. */
15:
16: public Procedure getPrompter() {
17: return prompter;
18: }
19:
20: /** Set the prompter function.
21: * The argument is called when a new line is read.
22: * It is passed one argument (this input port), and should return
23: * a string. That string is printed as the prompt string. */
24:
25: public void setPrompter(Procedure prompter) {
26: this .prompter = prompter;
27: }
28:
29: public TtyInPort(InputStream in, Path name, OutPort tie) {
30: super (in, name);
31: setConvertCR(true);
32: this .tie = tie;
33: }
34:
35: public TtyInPort(Reader in, Path name, OutPort tie) {
36: super (in, name);
37: setConvertCR(true);
38: this .tie = tie;
39: }
40:
41: protected boolean promptEmitted;
42:
43: public int fill(int len) throws java.io.IOException {
44: int count = in.read(buffer, pos, len);
45: if (tie != null && count > 0)
46: tie.echo(buffer, pos, count);
47: return count;
48: }
49:
50: public void lineStart(boolean revisited) throws java.io.IOException {
51: if (!revisited && prompter != null) {
52: try {
53: tie.freshLine();
54: Object prompt = prompter.apply1(this );
55: if (prompt != null) {
56: String string = prompt.toString();
57: if (string != null && string.length() > 0) {
58: tie.print(string);
59: tie.flush();
60: tie.clearBuffer();
61: promptEmitted = true;
62: }
63: }
64: } catch (Throwable ex) {
65: throw new java.io.IOException(
66: "Error when evaluating prompt:" + ex);
67: }
68: }
69: }
70:
71: public int read() throws IOException {
72: if (tie != null)
73: tie.flush();
74: int ch = super .read();
75: if (ch < 0) {
76: if (promptEmitted & tie != null)
77: tie.println();
78: }
79: promptEmitted = false;
80: return ch;
81: }
82:
83: public int read(char cbuf[], int off, int len) throws IOException {
84: if (tie != null)
85: tie.flush();
86: int count = super .read(cbuf, off, len);
87: if (count < 0 && promptEmitted & tie != null)
88: tie.println();
89: promptEmitted = false;
90: return count;
91: }
92:
93: }
|