KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > mapping > TtyInPort


1 package gnu.mapping;
2 import java.io.*;
3
4 /** An interactive input-port.
5     Supports prompting, auto-flush of tied output port, transcripts. */

6
7 public class TtyInPort extends InPort
8 {
9   protected OutPort tie;
10
11   protected Procedure prompter;
12
13   /** Get the current prompter function. */
14
15   public Procedure getPrompter () { return prompter; }
16
17   /** Set the prompter function.
18    * The argument is called when a new line is read.
19    * It is passed one argument (this input port), and should return
20    * a string. That string is printed as the prompt string. */

21
22   public void setPrompter (Procedure prompter)
23   {
24     this.prompter = prompter;
25   }
26
27   public TtyInPort (InputStream in, String JavaDoc name, OutPort tie)
28   {
29     super(in, name);
30     setConvertCR(true);
31     this.tie = tie;
32   }
33
34   public TtyInPort (Reader in, String JavaDoc name, OutPort tie)
35   {
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 JavaDoc
44   {
45     int count = in.read(buffer, pos, len);
46     if (tie != null && count > 0)
47       tie.echo(buffer, pos, count);
48     return count;
49   }
50
51   public void lineStart (boolean revisited) throws java.io.IOException JavaDoc
52   {
53     if (! revisited && prompter != null)
54       {
55     try
56       {
57         tie.freshLine();
58         Object JavaDoc prompt = prompter.apply1(this);
59         if (prompt != null)
60           {
61         String JavaDoc string = prompt.toString();
62         if (string != null && string.length() > 0)
63           {
64             tie.print(string);
65             tie.flush();
66             tie.clearBuffer();
67             promptEmitted = true;
68           }
69           }
70       }
71     catch (Throwable JavaDoc ex)
72       { throw new java.io.IOException JavaDoc("Error when evaluating prompt:"
73                       + ex); }
74       }
75   }
76
77   public int read () throws IOException
78   {
79     if (tie != null)
80       tie.flush();
81     int ch = super.read();
82     if (ch < 0)
83       {
84     if (promptEmitted & tie != null)
85       tie.println();
86       }
87     promptEmitted = false;
88     return ch;
89   }
90
91   public int read (char cbuf[], int off, int len) throws IOException
92   {
93     if (tie != null)
94       tie.flush();
95     int count = super.read(cbuf, off, len);
96     if (count < 0 && promptEmitted & tie != null)
97       tie.println();
98     promptEmitted = false;
99     return count;
100   }
101
102 }
103
Popular Tags