1 19 package jline; 20 21 import java.io.*; 22 import java.util.*; 23 24 25 37 public class UnixTerminal 38 extends Terminal 39 { 40 private Map terminfo; 41 private int width = -1; 42 private int height = -1; 43 44 45 49 public void initializeTerminal () 50 throws IOException, InterruptedException 51 { 52 final String ttyConfig = stty ("-g"); 54 55 if (ttyConfig.length () == 0 57 || (ttyConfig.indexOf ("=") == -1 58 && ttyConfig.indexOf (":") == -1)) 59 { 60 throw new IOException ("Unrecognized stty code: " + ttyConfig); 61 } 62 63 64 stty ("-icanon min 1"); 66 67 stty ("-echo"); 69 70 try 72 { 73 Runtime.getRuntime ().addShutdownHook (new Thread () 74 { 75 public void start () 76 { 77 try 78 { 79 stty (ttyConfig); 80 } 81 catch (Exception e) 82 { 83 } 84 } 85 }); 86 } 87 catch (AbstractMethodError ame) 88 { 89 } 91 } 92 93 94 public boolean isSupported () 95 { 96 return true; 97 } 98 99 100 public boolean getEcho () 101 { 102 return false; 103 } 104 105 106 114 public int getTerminalWidth () 115 { 116 if (width != -1) 117 return width; 118 119 int val = 80; 120 try 121 { 122 String size = stty ("size"); 123 if (size.length () != 0 && size.indexOf (" ") != -1) 124 { 125 val = Integer.parseInt ( 126 size.substring (size.indexOf (" ") + 1)); 127 } 128 } 129 catch (Exception e) 130 { 131 } 132 133 return width = val; 134 } 135 136 137 145 public int getTerminalHeight () 146 { 147 if (height != -1) 148 return height; 149 150 int val = 24; 151 152 try 153 { 154 String size = stty ("size"); 155 if (size.length () != 0 && size.indexOf (" ") != -1) 156 { 157 val = Integer.parseInt ( 158 size.substring (0, size.indexOf (" "))); 159 } 160 } 161 catch (Exception e) 162 { 163 } 164 165 return height = val; 166 } 167 168 169 173 private static String stty (String args) 174 throws IOException, InterruptedException 175 { 176 return exec ("stty " + args + " < /dev/tty").trim (); 177 } 178 179 180 184 private static String exec (String cmd) 185 throws IOException, InterruptedException 186 { 187 return exec (new String [] { "sh", "-c", cmd }); 188 } 189 190 191 195 private static String exec (String [] cmd) 196 throws IOException, InterruptedException 197 { 198 ByteArrayOutputStream bout = new ByteArrayOutputStream (); 199 200 Process p = Runtime.getRuntime ().exec (cmd); 201 int c; 202 InputStream in; 203 204 in = p.getInputStream (); 205 while ((c = in.read ()) != -1) 206 bout.write (c); 207 208 in = p.getErrorStream (); 209 while ((c = in.read ()) != -1) 210 bout.write (c); 211 212 p.waitFor (); 213 214 String result = new String (bout.toByteArray ()); 215 return result; 216 } 217 } 218 219 | Popular Tags |