예제 #1
0
 public void run() {
   try {
     for (; ; ) {
       byte[] buf = new byte[8192];
       int l = out.read(buf);
       InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(buf, 0, l));
       StringBuilder sb = new StringBuilder();
       for (; ; ) {
         int c = r.read();
         if (c == -1) {
           break;
         }
         sb.append((char) c);
       }
       if (sb.length() > 0) {
         terminal.write(sb.toString());
       }
       String s = terminal.read();
       if (s != null && s.length() > 0) {
         for (byte b : s.getBytes()) {
           in.write(b);
         }
       }
     }
   } catch (IOException e) {
     closed = true;
     e.printStackTrace();
   }
 }
예제 #2
0
  @Before
  public void init() {

    Nonterminal X = Nonterminal.withName("X");

    Nonterminal A = Nonterminal.withName("A");
    Nonterminal B = Nonterminal.withName("B");
    Nonterminal C = Nonterminal.withName("C");

    Rule r1 =
        Rule.withHead(X)
            .addSymbol(Nonterminal.builder(A).setLabel("a").build())
            .addSymbol(
                Star.builder(
                        Sequence.builder(
                                Code.code(
                                    Nonterminal.builder(B)
                                        .addPreCondition(predicate(equal(rExt("a"), lExt("b"))))
                                        .build(),
                                    stat(println(lExt("b")))),
                                Code.code(
                                    Nonterminal.builder(C).setLabel("b").build(),
                                    stat(println(var("b")))))
                            .build())
                    .setLabel("b")
                    .build())
            .build();

    Rule r2 = Rule.withHead(A).addSymbol(Terminal.from(Character.from('a'))).build();
    Rule r3 = Rule.withHead(B).addSymbol(Terminal.from(Character.from('b'))).build();
    Rule r4 = Rule.withHead(C).addSymbol(Terminal.from(Character.from('c'))).build();

    grammar = Grammar.builder().addRules(r1, r2, r3, r4).build();
  }
예제 #3
0
 public Terminal demote() {
   Terminal rv = new Terminal(branch, parent, id);
   int totalCount = getTotalCount();
   rv.setAggregateCount(totalCount);
   rv.setAggregateSum(getMean() * totalCount);
   return rv;
 }
예제 #4
0
 /**
  * The <code>printSeparator()</code> method prints a horizontal bar on the terminal that helps to
  * separate different sections of textual output. This implementation uses the '=' character,
  * providing a double-thick separator line and embeds a header string within the separating line.
  *
  * @param width the width of the horizontal separator bar
  * @param header the string to embed in the separator line
  */
 public static void printSeparator(int width, String header) {
   Terminal.print("=={ ");
   Terminal.print(header);
   Terminal.print(" }");
   Terminal.print(StringUtil.dup('=', width - 6 - header.length()));
   Terminal.nextln();
 }
예제 #5
0
 protected boolean execute(int address, String expectedOutput) {
   boolean isSuccess = false;
   Cpu cpu = computer.getCpu();
   cpu.writeRegister(false, Cpu.PC, address);
   long startTime = System.currentTimeMillis();
   while ((System.currentTimeMillis() - startTime) < MAX_EXECUTION_TIME
       || terminal.getWrittenData().length() > Terminal.MAX_DATA_LENGTH) {
     try {
       cpu.executeNextOperation();
       if (cpu.isHaltMode()) {
         throw new IllegalStateException("HALT mode");
       }
     } catch (Exception e) {
       e.printStackTrace();
       fail(
           "can't execute operation, PC: 0"
               + Integer.toOctalString(cpu.readRegister(false, Cpu.PC)));
     }
     if (expectedOutput.equals(terminal.getWrittenData())) {
       isSuccess = true;
       break;
     }
   }
   return isSuccess;
 }
예제 #6
0
 /** @see VtResponse#appendDescription(Terminal) */
 @Override
 protected Terminal appendDescription(final Terminal term) {
   term.print("Cursor location: +");
   term.print(this.x);
   term.print('+');
   term.print(this.y);
   return term;
 }
예제 #7
0
 @Override
 public boolean equals(Object o) {
   if (o instanceof Terminal) {
     Terminal temp = (Terminal) o;
     if (temp.matches(this.tokenType)) return true;
   }
   return false;
 }
예제 #8
0
 public void matchTerminal(Terminal ter) {
   if (ter.getName().equals("Epsilon")) {
     return;
   }
   if (!lookAhead.matches(ter.getRegex())) {
     System.err.println(
         "input wrong expected : " + ter.getName() + " get : " + lookAhead + " ,insert it");
   } else {
     lookAhead = getNextToken();
   }
 }
예제 #9
0
  public static String parse(
      Lexer lexer,
      HashMap<Nonterminal, HashMap<Terminal, Rule>> parsingTable,
      Nonterminal startSymbol) {

    Stack<Token> stack = new Stack<Token>();
    ArrayList<Terminal> inputs = lexer.getTokens();
    int count = 0;

    stack.push(startSymbol);
    while (!stack.isEmpty() && count < inputs.size()) {
      Token top = stack.peek();
      System.out.println(
          "Testing top: " + top.toString() + ", next input: " + inputs.get(count).toString());
      if (top instanceof Nonterminal) {

        Nonterminal nextNonTerm = (Nonterminal) top;
        Rule rules = parsingTable.get(nextNonTerm).get(inputs.get(count));
        if (rules == null)
          return "Invalid. No rule found for "
              + nextNonTerm.toString()
              + " and the input "
              + inputs.get(count);

        stack.pop();

        for (int i = rules.rule.length - 1; i > -1; i--) {
          if (!rules.rule[i].equals(new Terminal(Terminal.TerminalType.EPSILON)))
            stack.push(rules.rule[i]);
        }

      } else if (top instanceof Terminal) {

        Terminal nextTerm = (Terminal) top;
        Terminal nextInput = inputs.get(count);

        if (nextTerm.equals(nextInput)) {
          ++count;
          stack.pop();

        } else return nextTerm + " and " + nextInput + " do not match: invalid";
      }
      System.out.println("Current stack: " + stack.toString());
    }

    if (stack.isEmpty()) return "Valid";
    return "Invalid. Ran out of tokens early or ran over input count";
  }
예제 #10
0
    public SessionTerminal() throws IOException {
      try {
        this.terminal = new Terminal(TERM_WIDTH, TERM_HEIGHT);
        terminal.write("\u001b\u005B20\u0068"); // set newline mode on

        in = new PipedOutputStream();
        out = new PipedInputStream();
        PrintStream pipedOut = new PrintStream(new PipedOutputStream(out), true);

        final Subject subject = new Subject();
        subject.getPrincipals().add(new UserPrincipal("karaf"));
        Console console =
            consoleFactory.create(
                commandProcessor,
                new PipedInputStream(in),
                pipedOut,
                pipedOut,
                new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
                null);
        consoleFactory.startConsoleAs(console, subject);
      } catch (IOException e) {
        e.printStackTrace();
        throw e;
      } catch (Exception e) {
        e.printStackTrace();
        throw (IOException) new IOException().initCause(e);
      }
      new Thread(this).start();
    }
예제 #11
0
 private List<Value> ls(String... ss) {
   List<Value> list = new ArrayList<Value>();
   for (String s : ss) {
     list.add(Terminal.of(s));
   }
   return list;
 }
예제 #12
0
  /** Test method for {@link Sequence#compareTo(Value)}. */
  @Test
  public void testCompareTo_Unordered() {
    Sequence s1 = Sequence.unordered(ls("1", "2"));
    Sequence s2 = Sequence.unordered(ls("1", "2"));
    Sequence s3 = Sequence.unordered(ls("1"));
    Sequence s4 = Sequence.unordered(ls("1", "2", "3"));
    Sequence s5 = Sequence.unordered(ls("1", "3"));
    Sequence s6 = Sequence.unordered(ls("1", "1"));
    Sequence s7 = Sequence.unordered(ls("0", "3"));
    Sequence s8 = Sequence.unordered(ls("2", "1"));
    Terminal v1 = Terminal.of("12");
    Sequence v2 = Sequence.ordered(ls("1", "2"));
    Record v3 = Record.of(Arrays.<Entry>asList());

    // test is not an unordered list
    assertThat(s1.compareTo(v1), greaterThan(0));
    assertThat(s1.compareTo(v2), lessThan(0));
    assertThat(s1.compareTo(v3), lessThan(0));

    // entity
    assertThat(s1.compareTo(s1), is(0));
    assertThat(s1.compareTo(s2), is(0));
    assertThat(s1.compareTo(s3), greaterThan(0));
    assertThat(s1.compareTo(s4), lessThan(0));
    assertThat(s1.compareTo(s5), lessThan(0));
    assertThat(s1.compareTo(s6), greaterThan(0));
    assertThat(s1.compareTo(s7), greaterThan(0));
    assertThat(s1.compareTo(s8), is(0));
  }
예제 #13
0
  public void match(ArrayList<Token> rhs) {
    outer:
    for (Token i : rhs) {
      //            System.out.println("i:" + i);
      if (i.getClass().getName().equals("compiler.Terminal")) {
        matchTerminal((Terminal) i);
      } else if (i.getClass().getName().equals("compiler.NonTerminal")) {
        NonTerminal iNonTerminal = (NonTerminal) i;
        ArrayList<Integer> lhses = getIndexOfRulesWithLeftHandSide(gr.rules, iNonTerminal);
        for (Integer j : lhses) {
          if (gr.getFirsts(gr.rules.get(j).getRightSide())
              .contains(Terminal.getTerminalbyString(lookAhead))) {
            //                        System.out.println("using rule:" +
            // gr.rules.get(j).getRightSide());
            match(gr.rules.get(j).getRightSide());
            continue outer;
          }
        }

        /// no rule with input in first
        if (iNonTerminal.getFirsts().contains(Terminal.getTerminal("Epsilon"))) {
          if (iNonTerminal.getFollows().contains(Terminal.getTerminalbyString(lookAhead))) {
            ArrayList<Integer> indexOfRulesWithLeftHandSide =
                getIndexOfRulesWithLeftHandSide(gr.rules, iNonTerminal);
            for (Integer j : indexOfRulesWithLeftHandSide) {
              if (gr.getFirsts(gr.rules.get(j).getRightSide())
                  .contains(Terminal.getTerminal("Epsilon"))) {
                match(gr.rules.get(j).getRightSide());
                continue outer;
              }
            }
          }
        }

        if (iNonTerminal.getFollows().contains(Terminal.getTerminalbyString(lookAhead))) {
          System.err.println("missing " + iNonTerminal.getDesc() + " ,insert it");
        } else {
          System.err.println("misplaced " + lookAhead + " I'm Skipping it!");
          lookAhead = getNextToken();
        }

      } else if (i.getClass().getName().equals("compiler.Procedure")) {
        runProcedure(i.getName());
      }
    }
  }
예제 #14
0
 public String handle(String str, boolean forceDump) throws IOException {
   try {
     if (str != null && str.length() > 0) {
       String d = terminal.pipe(str);
       for (byte b : d.getBytes()) {
         in.write(b);
       }
       in.flush();
     }
   } catch (IOException e) {
     closed = true;
     throw e;
   }
   try {
     return terminal.dump(10, forceDump);
   } catch (InterruptedException e) {
     throw new InterruptedIOException(e.toString());
   }
 }
예제 #15
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((avion == null) ? 0 : avion.hashCode());
   result = prime * result + id;
   result = prime * result + ((pista == null) ? 0 : pista.hashCode());
   result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());
   return result;
 }
예제 #16
0
  /* Checks that the method lengthTerminalLenght works fine. */
  @Test(timeout = 100)
  public void lengthTerminalTest() {

    int len = -2;
    Collection<Terminal> ct;
    Terminal t = null;
    Terminal t2 = null;
    Terminal t3 = null;

    ct = g.getTerminals();
    Assert.assertNotNull(ct);
    for (Terminal t4 : ct) {
      if ((t4.getSymbol()).equals("1")) {
        t = t4;
      }
      if ((t4.getSymbol()).equals("5")) {
        t2 = t4;
      }
    }
    Assert.assertNotNull(t);
    Assert.assertNotNull(t2);

    len = l.lengthTerminal(null, t);
    Assert.assertTrue(len == -2);

    len = l.lengthTerminal(g, null);
    Assert.assertTrue(len == -2);

    try {
      t3 = new TerminalImpl(0, "");
    } catch (GrammarExceptionImpl e) {
      System.out.println(e.getMessage());
    }

    len = l.lengthTerminal(g, t3);
    Assert.assertTrue(len == -2);

    len = l.lengthTerminal(g, t);
    Assert.assertTrue(len == 0);

    len = l.lengthTerminal(g, t2);
    Assert.assertTrue(len == 0);
  }
예제 #17
0
  /**
   * Read a character from the console.
   *
   * @return the character, or -1 if an EOF is received.
   */
  public final int readVirtualKey() throws IOException {
    int c = terminal.readVirtualKey(in);

    if (debugger != null) {
      debug("keystroke: " + c + "");
    }

    // clear any echo characters
    clearEcho(c);

    return c;
  }
예제 #18
0
  /** Clear the echoed characters for the specified character code. */
  int clearEcho(int c) throws IOException {
    // if the terminal is not echoing, then just return...
    if (!terminal.getEcho()) {
      return 0;
    }

    // otherwise, clear
    int num = countEchoCharacters((char) c);
    back(num);
    drawBuffer(num);

    return num;
  }
예제 #19
0
  /**
   * The <code>reportProportion()</code> method is a simply utility to print out a quantity's name
   * (such as "Number of instructions executed", the value (such as 2002), and the units (such as
   * cycles) in a colorized and standardized way.
   *
   * @param name the name of the quantity as a string
   * @param val the value of the quantity as a long integer
   * @param units the name of the units as a string
   */
  public static void reportProportion(String name, long val, long total, String units) {
    String sval = Long.toString(val);
    Terminal.printGreen(name);
    Terminal.print(": ");
    Terminal.printBrightCyan(sval);
    if (units != null && units.length() > 0) Terminal.print(' ' + units + ' ');
    else Terminal.print(" ");
    float pcnt = (100 * (float) val / total);

    Terminal.printBrightCyan(StringUtil.toFixedFloat(pcnt, 4));
    Terminal.println(" %");
  }
예제 #20
0
  protected void stopTerminal() {
    try {
      TerminalFactory f = DefaultTerminalFactory.getInstance();
      Terminal t = f.getTerminal();
      t.stop();
    } catch (IOException ex) {
      // Log info:
      {
        String message = "Failure to stop terminal!";
        log.log(Level.SEVERE, message, ex);
      }

      throw new RuntimeException(ex);
    } catch (Throwable ex) {
      // Log info:
      {
        String message = "Failure to stop terminal!";
        log.log(Level.SEVERE, message, ex);
      }

      throw new RuntimeException(ex);
    }
  }
예제 #21
0
  /** Clear the screen by issuing the ANSI "clear screen" code. */
  public boolean clearScreen() throws IOException {
    if (!terminal.isANSISupported()) {
      return false;
    }

    // send the ANSI code to clear the screen
    printString(((char) 27) + "[2J");
    flushConsole();

    // then send the ANSI code to go to position 1,1
    printString(((char) 27) + "[1;1H");
    flushConsole();

    redrawLine();

    return true;
  }
예제 #22
0
 private void commandLoop() throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   while (true) {
     TerminalCommand tc = Terminal.create(in.readLine());
     if (tc instanceof TerminalCommand.Guest) {
       TerminalCommand.Guest tcg = (TerminalCommand.Guest) tc;
       createGuest(tcg.count, tcg.drink, tcg.maxDrinkCount);
     } else if (tc == TerminalCommand.Status.Instance) {
       getStatus();
     } else if (tc == TerminalCommand.Quit.Instance) {
       system.shutdown();
       break;
     } else {
       TerminalCommand.Unknown u = (TerminalCommand.Unknown) tc;
       log.warning("Unknown terminal command {}!", u.command);
     }
   }
 }
예제 #23
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   Vuelo other = (Vuelo) obj;
   if (avion == null) {
     if (other.avion != null) return false;
   } else if (!avion.equals(other.avion)) return false;
   if (id != other.id) return false;
   if (pista == null) {
     if (other.pista != null) return false;
   } else if (!pista.equals(other.pista)) return false;
   if (terminal == null) {
     if (other.terminal != null) return false;
   } else if (!terminal.equals(other.terminal)) return false;
   return true;
 }
예제 #24
0
  public void doClockIn(Terminal terminal, Shift shift, Calendar currentTime) {
    setClockedIn(true);
    setCurrentShift(shift);
    setCurrentTerminal(terminal);
    setLastClockInTime(currentTime.getTime());

    LogFactory.getLog(Application.class)
        .info("terminal id befor saving clockIn=" + terminal.getId());

    AttendenceHistory attendenceHistory = new AttendenceHistory();
    attendenceHistory.setClockInTime(currentTime.getTime());
    attendenceHistory.setClockInHour(Short.valueOf((short) currentTime.get(Calendar.HOUR)));
    attendenceHistory.setUser(this);
    attendenceHistory.setTerminal(terminal);
    attendenceHistory.setShift(shift);

    UserDAO.getInstance().saveClockIn(this, attendenceHistory, shift, currentTime);
  }
예제 #25
0
  // ================================ main ===============================
  //
  // You can use command line arguments to have the output and/or input
  // come from a file versus the command line.
  //
  // If there are two arguments then the first one is the file from where
  // the input is read and the second is the file where a transcript is
  // saved.
  //
  // If there is just one argument then it is the file where a transcript
  // is saved.
  public static void main(String args[]) {
    XYPoint points[];

    if (args.length >= 1) {
      Terminal.startTranscript(args[0]);
    }
    if (args.length >= 2) {
      // Read points from file
      points = PointReader.readXYPoints(args[1]);
    } else {
      // You can change "" to something else when testing,
      // but it MUST  be "3861" for your submitted output!

      java.util.Random randseq = new java.util.Random(3861);

      // Use this line if you want a different random set of
      // points for each run.  This code uses the system
      // clock as the seed to the random number generator.
      //
      // java.util.Random randseq = new java.util.Random();

      Terminal.println("How many points? ");

      int nPoints = Terminal.readInt();

      points = genPointsAtRandom(nPoints, randseq);
    }

    XComparator lessThanX = new XComparator();
    YComparator lessThanY = new YComparator();

    Date startTime = new Date();

    //////////////////////////////////////////////////////////////////////
    // CLOSEST-PAIR ALGORITHM STARTS HERE

    // The algorithm expects two arrays containing the same points.
    XYPoint pointsByX[] = new XYPoint[points.length];
    XYPoint pointsByY[] = new XYPoint[points.length];
    for (int j = 0; j < points.length; j++) {
      pointsByX[j] = points[j];
      pointsByY[j] = points[j];
    }
    // Ensure sorting precondition for divide-and-conquer CP algorithm.
    // You should *not* have to call msort() in your own code!
    Sort.msort(pointsByX, lessThanX); // sort by x-coord
    Sort.msort(pointsByY, lessThanY); // sort by y-coord

    Result rMin = ClosestPair.findClosestPair(pointsByX, pointsByY);
    rMin.print();

    // CLOSEST-PAIR ALGORITHM ENDS HERE
    //////////////////////////////////////////////////////////////////////

    Date endTime = new Date();
    long elapsedTime = endTime.getTime() - startTime.getTime();
    Terminal.println(
        "For n = " + points.length + ", the elapsed time is " + elapsedTime + " milliseconds.\n");

    // *** NOTE: for your submitted output for Part Two, you MUST print
    // *** the closest pair of points and the distance between them!

    //////////////////////////////////////////////////////////////////////
    // THE FOLLOWING LINES DEMONSTRATE HOW TO USE THE PROVIDED
    // PLOTTER ROUTINE.  Uncomment them as you wish for debugging
    // purposes, or use them in your closest pair code to inspect
    // the point arrays at any time.  For example, you could color
    // all points in the left half red and all points in the right
    // half blue and then visually check that you divided them
    // properly by calling the plotter before you recurse.  Note
    // that if you make several calls, all the plots will
    // initially be on top of each other -- just move them so you
    // can see everything.
    //

    // Here the points are plotted and labelled by X-coordinate

    // new Plotter(pointsByY, true, "Sorted by X-coordinate");

    // Here the points are plotted and labelled by Y-coordinate

    // new Plotter(pointsByY, true, "Sorted by Y-coordinate");

    // Here's a call to the plot routine in which the points
    // aren't labeled. A nice thing to do at this point (if you
    // computed the two closest points) would be to color the two
    // closest points a different color For a XYPoint p, you could
    // color p (say red) with the line:
    //
    // p.color = Color.red;

    // new Plotter(pointsByX, true, "Output");
  }
예제 #26
0
  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {
    if (localName.compareToIgnoreCase("term") == 0) {
      String tid = attributes.getValue("tid");
      String address = attributes.getValue("addr");

      Terminal terminal;
      if (terminals.containsKey(tid)) terminal = terminals.get(tid);
      else {
        terminal = new Terminal(tid, address);
        terminals.put(tid, terminal);
        ++count;
      }
      // статус
      terminal.state = getInt(attributes, "rs", Terminal.STATE_ERROR);
      // состояние принтера
      terminal.printer_state = getString(attributes, "rp", "none");
      // состояние купироприемника
      terminal.cashbin_state = getString(attributes, "rc", "none");
      // сумма
      terminal.cash = getInt(attributes, "cs");
      // последняя активность
      terminal.lastActivity = getString(attributes, "lat");
      // последний платеж
      terminal.lastPayment = getString(attributes, "lpd");
      // Число купюр
      terminal.bondsCount = getInt(attributes, "nc");
      // Баланс сим карты
      terminal.balance = getString(attributes, "ss");
      // Уровень сигнала сим карты
      terminal.bondsCount = getInt(attributes, "sl");
      // Версия софта
      terminal.softVersion = getString(attributes, "csoft");
      // Модель принтера
      terminal.printerModel = getString(attributes, "pm");
      terminal.cashbinModel = getString(attributes, "dm");
      terminal.bonds10count = getInt(attributes, "b_co_10");
      terminal.bonds50count = getInt(attributes, "b_co_50");
      terminal.bonds100count = getInt(attributes, "b_co_100");
      terminal.bonds500count = getInt(attributes, "b_co_500");
      terminal.bonds1000count = getInt(attributes, "b_co_1000");
      terminal.bonds5000count = getInt(attributes, "b_co_5000");
      terminal.bonds10000count = getInt(attributes, "b_co_10000");
      terminal.paysPerHour = getString(attributes, "pays_per_hour");
      terminal.agentId = getString(attributes, "aid");
      terminal.agentName = getString(attributes, "an");
    } else if (localName.compareToIgnoreCase("result-code") == 0) tagState = TAG_RESULT;
    else if (localName.compareToIgnoreCase("extra") == 0) {
      tagState = TAG_EXTRA;
      String extra_name = attributes.getValue("name");
      if (extra_name.compareToIgnoreCase("balance") == 0) extraState = EXTRA_BALANCE;
      else if (extra_name.compareToIgnoreCase("overdraft") == 0) extraState = EXTRA_OVERDRAFT;
      else extraState = EXTRA_UNKNOWN;
    } else tagState = TAG_NONE;
    // не допускаем вложенности
    text.delete(0, text.length());
  }
예제 #27
0
 /** Copy terminal fields. */
 public final void link(Terminal terminal) {
   set(F_TERMINALID, new Long(terminal.getId()));
   set(F_TERMINALNAME, terminal.getName());
   set(F_BUILDINGID, new Long(terminal.getBuildingId()));
   set(F_BUILDINGNAME, terminal.getBuildingName());
 }
예제 #28
0
  /**
   * Read a line from the <i>in</i> {@link InputStream}, and return the line (without any trailing
   * newlines).
   *
   * @param prompt the prompt to issue to the console, may be null.
   * @return a line that is read from the terminal, or null if there was null input (e.g.,
   *     <i>CTRL-D</i> was pressed).
   */
  public String readLine(final String prompt, final Character mask) throws IOException {
    this.mask = mask;
    if (prompt != null) this.prompt = prompt;

    try {
      terminal.beforeReadLine(this, this.prompt, mask);

      if ((this.prompt != null) && (this.prompt.length() > 0)) {
        out.write(this.prompt);
        out.flush();
      }

      // if the terminal is unsupported, just use plain-java reading
      if (!terminal.isSupported()) {
        return readLine(in);
      }

      while (true) {
        int[] next = readBinding();

        if (next == null) {
          return null;
        }

        int c = next[0];
        int code = next[1];

        if (c == -1) {
          return null;
        }

        boolean success = true;

        switch (code) {
          case EXIT: // ctrl-d
            if (buf.buffer.length() == 0) {
              return null;
            }

          case COMPLETE: // tab
            success = complete();
            break;

          case MOVE_TO_BEG:
            success = setCursorPosition(0);
            break;

          case KILL_LINE: // CTRL-K
            success = killLine();
            break;

          case CLEAR_SCREEN: // CTRL-L
            success = clearScreen();
            break;

          case KILL_LINE_PREV: // CTRL-U
            success = resetLine();
            break;

          case NEWLINE: // enter
            moveToEnd();
            printNewline(); // output newline
            return finishBuffer();

          case DELETE_PREV_CHAR: // backspace
            success = backspace();
            break;

          case DELETE_NEXT_CHAR: // delete
            success = deleteCurrentCharacter();
            break;

          case MOVE_TO_END:
            success = moveToEnd();
            break;

          case PREV_CHAR:
            success = moveCursor(-1) != 0;
            break;

          case NEXT_CHAR:
            success = moveCursor(1) != 0;
            break;

          case NEXT_HISTORY:
            success = moveHistory(true);
            break;

          case PREV_HISTORY:
            success = moveHistory(false);
            break;

          case REDISPLAY:
            break;

          case PASTE:
            success = paste();
            break;

          case DELETE_PREV_WORD:
            success = deletePreviousWord();
            break;

          case PREV_WORD:
            success = previousWord();
            break;

          case NEXT_WORD:
            success = nextWord();
            break;

          case START_OF_HISTORY:
            success = history.moveToFirstEntry();
            if (success) setBuffer(history.current());
            break;

          case END_OF_HISTORY:
            success = history.moveToLastEntry();
            if (success) setBuffer(history.current());
            break;

          case CLEAR_LINE:
            moveInternal(-(buf.buffer.length()));
            killLine();
            break;

          case INSERT:
            buf.setOvertyping(!buf.isOvertyping());
            break;

          case UNKNOWN:
          default:
            if (c != 0) { // ignore null chars
              ActionListener action =
                  (ActionListener) triggeredActions.get(new Character((char) c));
              if (action != null) action.actionPerformed(null);
              else putChar(c, true);
            } else success = false;
        }

        if (!(success)) {
          beep();
        }

        flushConsole();
      }
    } finally {
      terminal.afterReadLine(this, this.prompt, mask);
    }
  }
예제 #29
0
 /**
  * Query the terminal to find the current width;
  *
  * @see Terminal#getTerminalHeight
  * @return the height of the current terminal.
  */
 public int getTermheight() {
   return Terminal.setupTerminal().getTerminalHeight();
 }
예제 #30
0
 /**
  * Query the terminal to find the current width;
  *
  * @see Terminal#getTerminalWidth
  * @return the width of the current terminal.
  */
 public int getTermwidth() {
   return Terminal.setupTerminal().getTerminalWidth();
 }