io.termd.core.util.Helper Java Examples

The following examples show how to use io.termd.core.util.Helper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Readline.java    From termd with Apache License 2.0 6 votes vote down vote up
private void refresh(LineBuffer update, int width) {
  LineBuffer copy3 = new LineBuffer();
  IntStream.Builder consumer = IntStream.builder();
  copy3.insert(Helper.toCodePoints(currentPrompt));
  copy3.insert(buffer().toArray());
  copy3.setCursor(currentPrompt.length() + buffer().getCursor());
  LineBuffer copy2 = new LineBuffer();
  copy2.insert(Helper.toCodePoints(currentPrompt));
  copy2.insert(update.toArray());
  copy2.setCursor(currentPrompt.length() + update.getCursor());
  copy3.update(copy2, data -> {
    for (int cp : data) {
      consumer.accept(cp);
    }
  }, width);
  conn.stdoutHandler().accept(consumer.build().toArray());
  buffer.clear();
  buffer.insert(update.toArray());
  buffer.setCursor(update.getCursor());
}
 
Example #2
Source File: BinaryEncodingTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoderUnderflow() throws Exception {
  final ArrayList<Integer> codePoints = new ArrayList<>();
  BinaryDecoder decoder = new BinaryDecoder(10, UTF8, new Consumer<int[]>() {
    @Override
    public void accept(int[] event) {
      codePoints.addAll(Helper.list(event));
    }
  });
  decoder.write(new byte[]{(byte) 0xE2});
  assertEquals(0, codePoints.size());
  decoder.write(new byte[]{(byte) 0x82});
  assertEquals(0, codePoints.size());
  decoder.write(new byte[]{(byte) 0xAC});
  assertEquals(1, codePoints.size());
  assertEquals('\u20AC', (int)codePoints.get(0));
}
 
Example #3
Source File: FileUtils.java    From arthas with Apache License 2.0 6 votes vote down vote up
public static List<int[]> loadCommandHistory(File file) {
    BufferedReader br = null;
    List<int[]> history = new ArrayList<int[]>();
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line;
        while ((line = br.readLine()) != null) {
            history.add(Helper.toCodePoints(line));
        }
    } catch (IOException e) {
        // ignore
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }
    return history;
}
 
Example #4
Source File: BinaryEncodingTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoderUnderflow() throws Exception {
  final ArrayList<Integer> codePoints = new ArrayList<Integer>();
  BinaryDecoder decoder = new BinaryDecoder(10, UTF8, new Consumer<int[]>() {
    @Override
    public void accept(int[] event) {
      codePoints.addAll(Helper.list(event));
    }
  });
  decoder.write(new byte[]{(byte) 0xE2});
  assertEquals(0, codePoints.size());
  decoder.write(new byte[]{(byte) 0x82});
  assertEquals(0, codePoints.size());
  decoder.write(new byte[]{(byte) 0xAC});
  assertEquals(1, codePoints.size());
  assertEquals('\u20AC', (int)codePoints.get(0));
}
 
Example #5
Source File: TelnetCharsetTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testBinaryDecoder() {
  byte[] input = { '\n', 0, 'A'};
  int[][] expectedOutput = {{'\r'},{'\r'},{'\r','A'}};
  for (int i = 0;i < input.length;i++) {
    final ArrayList<Integer> codePoints = new ArrayList<Integer>();
    BinaryDecoder decoder = new BinaryDecoder(512, TelnetCharset.INSTANCE, new Consumer<int[]>() {
      @Override
      public void accept(int[] event) {
        for (int j : event) {
          codePoints.add(j);
        }
      }
    });
    decoder.write(new byte[]{'\r'});
    assertEquals(1, codePoints.size());
    decoder.write(new byte[]{input[i]});
    assertEquals(Helper.list(expectedOutput[i]), codePoints);
  }
}
 
Example #6
Source File: TermImpl.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Override
public Term stdinHandler(Handler<String> handler) {
  if (inReadline) {
    throw new IllegalStateException();
  }
  stdinHandler = handler;
  if (handler != null) {
    conn.setStdinHandler(codePoints -> {
      handler.handle(Helper.fromCodePoints(codePoints));
    });
    checkPending();
  } else {
    conn.setStdinHandler(echoHandler);
  }
  return this;
}
 
Example #7
Source File: ShellImpl.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
public ShellImpl init() {

    term.interruptHandler(key -> jobController().foregroundJob().interrupt());

    term.suspendHandler(key -> {
      term.echo(Helper.fromCodePoints(new int[]{key, '\n'}));
      Job job = jobController.foregroundJob();
      term.echo(statusLine(job, ExecStatus.STOPPED) + "\n");
      job.suspend();
      return true;
    });

    term.closeHandler(v ->
        jobController.close(ar ->
            closedPromise.complete()
        )
    );
    if (welcome != null && welcome.length() > 0) {
      term.write(welcome);
    }
    return this;
  }
 
Example #8
Source File: HistoryTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testHistory() {
  TestTerm term = new TestTerm(this);
  term.readline.getHistory().add(Helper.toCodePoints("abc"));
  term.readline.getHistory().add(Helper.toCodePoints("def"));
  term.readlineComplete();
  term.read(Keys.UP.sequence);
  term.assertScreen("% abc");
  term.assertAt(0, 5);
  term.read(Keys.UP.sequence);
  term.assertScreen("% def");
  term.assertAt(0, 5);
  term.read(Keys.UP.sequence);
  term.assertScreen("% def");
  term.assertAt(0, 5);
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% abc");
  term.assertAt(0, 5);
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% ");
  term.assertAt(0, 2);
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% ");
  term.assertAt(0, 2);
}
 
Example #9
Source File: TelnetCharsetTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testBinaryDecoder() {
  byte[] input = { '\n', 0, 'A'};
  int[][] expectedOutput = {{'\r'},{'\r'},{'\r','A'}};
  for (int i = 0;i < input.length;i++) {
    final ArrayList<Integer> codePoints = new ArrayList<>();
    BinaryDecoder decoder = new BinaryDecoder(512, TelnetCharset.INSTANCE, event -> {
      for (int j : event) {
        codePoints.add(j);
      }
    });
    decoder.write(new byte[]{'\r'});
    assertEquals(1, codePoints.size());
    decoder.write(new byte[]{input[i]});
    assertEquals(Helper.list(expectedOutput[i]), codePoints);
  }
}
 
Example #10
Source File: HistoryTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testHistory() {
  TestTerm term = new TestTerm(this);
  term.readline.getHistory().add(Helper.toCodePoints("abc"));
  term.readline.getHistory().add(Helper.toCodePoints("def"));
  term.readlineComplete();
  term.read(Keys.UP.sequence);
  term.assertScreen("% abc");
  term.assertAt(0, 5);
  term.read(Keys.UP.sequence);
  term.assertScreen("% def");
  term.assertAt(0, 5);
  term.read(Keys.UP.sequence);
  term.assertScreen("% def");
  term.assertAt(0, 5);
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% abc");
  term.assertAt(0, 5);
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% ");
  term.assertAt(0, 2);
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% ");
  term.assertAt(0, 2);
}
 
Example #11
Source File: Readline.java    From termd with Apache License 2.0 6 votes vote down vote up
private void refresh(LineBuffer update, int width) {
  LineBuffer copy3 = new LineBuffer(update.getCapacity());
  final List<Integer> codePoints = new LinkedList<Integer>();
  copy3.insert(Helper.toCodePoints(currentPrompt));
  copy3.insert(buffer().toArray());
  copy3.setCursor(currentPrompt.length() + buffer().getCursor());
  LineBuffer copy2 = new LineBuffer(copy3.getCapacity());
  copy2.insert(Helper.toCodePoints(currentPrompt));
  copy2.insert(update.toArray());
  copy2.setCursor(currentPrompt.length() + update.getCursor());
  copy3.update(copy2, new Consumer<int[]>() {
    @Override
    public void accept(int[] data) {
      for (int cp : data) {
        codePoints.add(cp);
      }
    }
  }, width);
  conn.stdoutHandler().accept(Helper.convert(codePoints));
  buffer.clear();
  buffer.insert(update.toArray());
  buffer.setCursor(update.getCursor());
}
 
Example #12
Source File: CompletionTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompletionBlock1() throws Exception {
  TestTerm term = new TestTerm(this);
  AtomicBoolean completed = new AtomicBoolean();
  Supplier<String> line = term.readlineComplete(completion -> {
    completion.suggest(Helper.toCodePoints("a\r\nb\r\nc\r\n"));
    completed.set(true);
  });
  term.read('a', 'b');
  term.read(BACKWARD_KEY);
  term.assertScreen("% ab");
  term.assertAt(0, 3);
  term.read('\t');
  assertTrue(completed.get());
  term.assertScreen("% ab", "a", "b", "c", "% ab");
  term.assertAt(4, 3);
  term.read('c');
  term.assertScreen("% ab", "a", "b", "c", "% acb");
  term.assertAt(4, 4);
  term.read('\r');
  term.assertScreen("% ab", "a", "b", "c", "% acb");
  term.assertAt(5, 0);
  assertEquals("acb", line.get());
}
 
Example #13
Source File: CompletionTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompletionBlock3() throws Exception {
  TestTerm term = new TestTerm(this);
  AtomicBoolean completed = new AtomicBoolean();
  Supplier<String> line = term.readlineComplete(completion -> {
    completion.suggest(Helper.toCodePoints("a\r\nb\r\nc\r\n"));
    completed.set(true);
  });
  term.read('a', '"', '\r', 'b', 'c');
  term.read(BACKWARD_KEY);
  term.assertScreen("% a\"", "> bc");
  term.assertAt(1, 3);
  term.read('\t');
  assertTrue(completed.get());
  term.assertScreen("% a\"", "> bc", "a", "b", "c", "> bc");
  term.assertAt(5, 3);
  term.read('d');
  term.assertScreen("% a\"", "> bc", "a", "b", "c", "> bdc");
  term.assertAt(5, 4);
  term.read('"', '\r');
  term.assertScreen("% a\"", "> bc", "a", "b", "c", "> bd\"c");
  term.assertAt(6, 0);
  assertEquals("a\"\nbd\"c", line.get());
}
 
Example #14
Source File: TermImpl.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
void checkPending() {
  if (stdinHandler != null && readline.hasEvent()) {
    stdinHandler.handle(Helper.fromCodePoints(readline.nextEvent().buffer().array()));
    vertx.runOnContext(v -> {
      checkPending();
    });
  }
}
 
Example #15
Source File: HistoryTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiline() {
  TestTerm term = new TestTerm(this);
  term.readline.getHistory().add(Helper.toCodePoints("abc\ndef\nghi"));
  term.readlineComplete();
  term.read(Keys.UP.sequence);
  term.assertScreen("% abc", "def", "ghi");
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% ", "", "");
}
 
Example #16
Source File: TermInfoTest.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Compare two terminal escape sequences.
 *
 * @param expected the expected sequence
 * @param actual the sequence
 */
public static void assertSequenceEquals(String expected, String actual) {
  try {
    assertEquals(expected, actual);
  } catch (AssertionError e) {
    throw new AssertionError("Was expecting sequence <" + Helper.escape(actual) + "> to be equals to <"
        + Helper.escape(expected) + ">");
  }
}
 
Example #17
Source File: CompletionTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private void assertCompleteInline(String line, String inline, boolean terminate, String... expected) {
  TestTerm term = new TestTerm(this);
  final AtomicReference<Completion> completion = new AtomicReference<Completion>();
  term.readlineComplete(new Consumer<Completion>() {
    @Override
    public void accept(Completion c) {
      completion.set(c);
    }
  });
  term.read(Helper.toCodePoints(line));
  term.read('\t');
  completion.get().complete(Helper.toCodePoints(inline), terminate);
  term.assertScreen(expected);
}
 
Example #18
Source File: CompletionTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private void assertPrefix(String line, String expected) {
  TestTerm term = new TestTerm(this);
  final AtomicReference<String> prefix = new AtomicReference<String>();
  term.readlineComplete(new Consumer<Completion>() {
    @Override
    public void accept(Completion completion) {
      prefix.set(Helper.fromCodePoints(completion.prefix()));
    }
  });
  term.read(Helper.toCodePoints(line));
  term.read('\t');
  assertEquals(expected, prefix.get());
}
 
Example #19
Source File: TtyOutputModeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
private void assertOutput(String expected, String actual) {
  Stream.Builder<int[]> builder = Stream.<int[]>builder();
  TtyOutputMode out = new TtyOutputMode(builder);
  out.accept(Helper.toCodePoints(actual));
  String result = Helper.fromCodePoints(builder.build().flatMapToInt(IntStream::of).toArray());
  assertEquals(expected, result);
}
 
Example #20
Source File: TermImpl.java    From arthas with Apache License 2.0 5 votes vote down vote up
public void handleEof(Integer key) {
    // Pseudo signal
    if (stdinHandler != null) {
        stdinHandler.handle(Helper.fromCodePoints(new int[]{key}));
    } else {
        echo(key);
        readline.queueEvent(new int[]{key});
    }
}
 
Example #21
Source File: CompletionUtils.java    From arthas with Apache License 2.0 5 votes vote down vote up
public static String findLongestCommonPrefix(Collection<String> values) {
    List<int[]> entries = new LinkedList<int[]>();
    for (String value : values) {
        int[] entry = Helper.toCodePoints(value);
        entries.add(entry);
    }
    return Helper.fromCodePoints(io.termd.core.readline.Completion.findLongestCommonPrefix(entries));
}
 
Example #22
Source File: TermImpl.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
public TermImpl(Vertx vertx, Keymap keymap, TtyConnection conn) {
  this.vertx = vertx;
  this.conn = conn;
  readline = new Readline(keymap);
  readlineFunctions.forEach(readline::addFunction);
  echoHandler = codePoints -> {
    // Echo
    echo(codePoints);
    readline.queueEvent(codePoints);
  };
  conn.setStdinHandler(echoHandler);
  conn.setEventHandler((event, key) -> {
    switch (event) {
      case INTR:
        if (interruptHandler == null || !interruptHandler.deliver(key)) {
          echo(key, '\n');
        }
        break;
      case EOF:
        // Pseudo signal
        if (stdinHandler != null) {
          stdinHandler.handle(Helper.fromCodePoints(new int[]{key}));
        } else {
          echo(key);
          readline.queueEvent(new int[]{key});
        }
        break;
      case SUSP:
        if (suspendHandler == null || !suspendHandler.deliver(key)) {
          echo(key, 'Z' - 64);
        }
        break;
    }
  });
}
 
Example #23
Source File: TtyConnectionSupport.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Write a string to the client.
 *
 * @param s the string to write
 */
@Override
public TtyConnection write(String s) {
    int[] codePoints = Helper.toCodePoints(s);
    stdoutHandler().accept(codePoints);
    return this;
}
 
Example #24
Source File: TestTtyConnection.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Override
public Consumer<int[]> stdoutHandler() {
  return codePoints -> {
    synchronized (TestTtyConnection.this) {
      Helper.appendCodePoints(codePoints, out());
      notify();
    }
  };
}
 
Example #25
Source File: Shell.java    From termd with Apache License 2.0 5 votes vote down vote up
public void accept(final TtyConnection conn) {
  InputStream inputrc = Keymap.class.getResourceAsStream("inputrc");
  Keymap keymap = new Keymap(inputrc);
  Readline readline = new Readline(keymap);
  for (io.termd.core.readline.Function function : Helper.loadServices(Thread.currentThread().getContextClassLoader(), io.termd.core.readline.Function.class)) {
    readline.addFunction(function);
  }
  conn.write("Welcome to Term.d shell example\n\n");
  read(conn, readline);
}
 
Example #26
Source File: Readline.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Redraw the current line.
 */
public void redraw() {
  LineBuffer toto = new LineBuffer();
  toto.insert(Helper.toCodePoints(currentPrompt));
  toto.insert(buffer.toArray());
  toto.setCursor(currentPrompt.length() + buffer.getCursor());
  LineBuffer abc = new LineBuffer();
  abc.update(toto, conn.stdoutHandler(), size.x());
}
 
Example #27
Source File: TermInfoTest.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Compare two terminal escape sequences.
 *
 * @param expected the expected sequence
 * @param actual the sequence
 */
public static void assertSequenceEquals(String expected, String actual) {
  try {
    assertEquals(expected, actual);
  } catch (AssertionError e) {
    throw new AssertionError("Was expecting sequence <" + Helper.escape(actual) + "> to be equals to <"
        + Helper.escape(expected) + ">");
  }
}
 
Example #28
Source File: Function.java    From termd with Apache License 2.0 5 votes vote down vote up
/**
 * Load the defaults function via the {@link java.util.ServiceLoader} SPI.
 *
 * @return the loaded function
 */
static List<Function> loadDefaults() {
  List<Function> functions = new ArrayList<>();
  for (io.termd.core.readline.Function function : Helper.loadServices(Thread.currentThread().getContextClassLoader(), io.termd.core.readline.Function.class)) {
    functions.add(function);
  }
  return functions;
}
 
Example #29
Source File: TtyTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignalInterleaving() throws Exception {
  StringBuilder buffer = new StringBuilder();
  AtomicInteger count = new AtomicInteger();
  server(conn -> {
    conn.setStdinHandler(event -> {
      Helper.appendCodePoints(event, buffer);
    });
    conn.setEventHandler((event, cp) -> {
      if (event == TtyEvent.INTR) {
        switch (count.get()) {
          case 0:
            assertEquals("hello", buffer.toString());
            buffer.setLength(0);
            count.set(1);
            break;
          case 1:
            assertEquals("bye", buffer.toString());
            count.set(2);
            testComplete();
            break;
          default:
            fail("Not expected");
        }
      }
    });
  });
  assertConnect();
  assertWrite('h', 'e', 'l', 'l', 'o', 3, 'b', 'y', 'e', 3);
  await();
}
 
Example #30
Source File: HistoryTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiline() {
  TestTerm term = new TestTerm(this);
  term.readline.getHistory().add(Helper.toCodePoints("abc\ndef\nghi"));
  term.readlineComplete();
  term.read(Keys.UP.sequence);
  term.assertScreen("% abc", "def", "ghi");
  term.read(Keys.DOWN.sequence);
  term.assertScreen("% ", "", "");
}