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