1 package gnu.mapping; 2 import java.io.*; 3 4 6 7 public class TtyInPort extends InPort 8 { 9 protected OutPort tie; 10 11 protected Procedure prompter; 12 13 14 15 public Procedure getPrompter () { return prompter; } 16 17 21 22 public void setPrompter (Procedure prompter) 23 { 24 this.prompter = prompter; 25 } 26 27 public TtyInPort (InputStream in, String name, OutPort tie) 28 { 29 super(in, name); 30 setConvertCR(true); 31 this.tie = tie; 32 } 33 34 public TtyInPort (Reader in, String 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 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 52 { 53 if (! revisited && prompter != null) 54 { 55 try 56 { 57 tie.freshLine(); 58 Object prompt = prompter.apply1(this); 59 if (prompt != null) 60 { 61 String 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 ex) 72 { throw new java.io.IOException ("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 |