Java ANSI console

Java ANSI console

--------------- AnsiConsole.java ---------------

public class AnsiConsole {

  static volatile double offs = 0, step1 = .15, step2 = .45;

  public static void main(String[] args) {
    if (System.console() == null) { System.err.println("Console is not available"); return; }
    double dblPI = 2 * Math.PI;
    Runnable trg = () -> {
      while (!Thread.currentThread().isInterrupted()) {
        if (offs >= dblPI) offs = 0;
        System.out.print("\033[s");   //save cursor position
        System.out.print("\033[22;1H");
        System.out.print("\033[1J");   //clear screen from cursor up
        double angle1 = offs, angle2 = offs;
        for (int r, c = 1; c < 80; c++) {
          if (angle1 >= dblPI) angle1 = 0;
          if (angle2 >= dblPI) angle2 = 0;
          r = 6 + (int)Math.round(Math.sin(angle1) * 4);
          System.out.print("\033["+r+";"+c+"H"+"*");
          r = 16 + (int)Math.round(Math.sin(angle2) * 4);
          System.out.print("\033["+r+";"+c+"H"+"*");
          angle1 += step1;
          angle2 += step2;
        }
        System.out.print("\033[u");   //restore cursor position 
        offs += .5;
        try { Thread.sleep(500); } catch (Exception e) { Thread.currentThread().interrupt(); }
      }
    };
    System.out.print("\033c");   //reset terminal to initial state
    exit: for (;;) {
      System.out.print("\033[22;1H");
      System.out.print("\033[J");   //clear screen from cursor down
      System.out.print("\033[24;1HPress enter key");
      Thread thread = new Thread(trg);
      thread.start();
      System.console().readPassword();
      thread.interrupt();
      try { thread.join(); } catch (Exception e) { }
      String inf = "";
      for(;;) {
        System.out.print("\033[22;1H");
        System.out.print("\033[J");   //clear screen from cursor down
        System.out.print("\033[23;1Ht#-Period of top graph (1-9), b#-Period of bottom graph (1-9), q-Quit");
        if (!inf.isEmpty()) System.out.print("\033[25;1H" + (inf.length() > 79 ? inf.substring(0, 79) : inf));
        System.out.print("\033[24;1H>");
        String st = System.console().readLine();
        String cmd = st.trim().toLowerCase();
        inf = "";
        if (cmd.isEmpty()) break;
        if ("q".equals(cmd)) break exit;
        if (cmd.length() > 1 && "tb".indexOf(cmd.charAt(0)) > -1) {
          int sn = 0;
          try { sn = Integer.parseInt(cmd.substring(1)); } catch (Exception e) { }
          if (sn > 0 && sn < 10) {
            double step = sn / 20D + .05;
            if (cmd.charAt(0) == 't') step1 = step;
            else step2 = step;
            break;
          } else inf = "Invalid parameter";
        }
        else inf = "Unknown command: " + st.trim();
      }
    }
  }
}

Download ZIP

Back