/**
   * 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;
  }
  /** 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;
  }
  /** 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;
  }
Beispiel #4
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");
  }
  /**
   * 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);
    }
  }
 /**
  * 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();
 }
 /**
  * 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();
 }
  /**
   * Create a new reader.
   *
   * @param in the input
   * @param out the output
   * @param bindings the key bindings to use
   * @param term the terminal to use
   */
  public ConsoleReader(InputStream in, Writer out, InputStream bindings, Terminal term)
      throws IOException {
    this.terminal = term;
    setInput(in);
    this.out = out;

    if (bindings == null) {
      try {
        String bindingFile =
            System.getProperty(
                "jline.keybindings",
                new File(System.getProperty("user.home", ".jlinebindings.properties"))
                    .getAbsolutePath());

        if (new File(bindingFile).isFile()) {
          bindings = new FileInputStream(new File(bindingFile));
        }
      } catch (Exception e) {
        // swallow exceptions with option debugging
        if (debugger != null) {
          e.printStackTrace(debugger);
        }
      }
    }

    if (bindings == null) {
      bindings = terminal.getDefaultBindings();
    }

    this.keybindings = new short[Character.MAX_VALUE * 2];

    Arrays.fill(this.keybindings, UNKNOWN);

    /**
     * Loads the key bindings. Bindings file is in the format:
     *
     * <p>keycode: operation name
     */
    if (bindings != null) {
      Properties p = new Properties();
      p.load(bindings);
      bindings.close();

      for (Iterator i = p.keySet().iterator(); i.hasNext(); ) {
        String val = (String) i.next();

        try {
          Short code = new Short(val);
          String op = (String) p.getProperty(val);

          Short opval = (Short) KEYMAP_NAMES.get(op);

          if (opval != null) {
            keybindings[code.shortValue()] = opval.shortValue();
          }
        } catch (NumberFormatException nfe) {
          consumeException(nfe);
        }
      }

      // hardwired arrow key bindings
      // keybindings[VK_UP] = PREV_HISTORY;
      // keybindings[VK_DOWN] = NEXT_HISTORY;
      // keybindings[VK_LEFT] = PREV_CHAR;
      // keybindings[VK_RIGHT] = NEXT_CHAR;
    }
  }
 public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings)
     throws IOException {
   this(in, out, bindings, Terminal.getTerminal());
 }