Java Examples for com.googlecode.lanterna.terminal.Terminal

The following java examples will help you to understand the usage of com.googlecode.lanterna.terminal.Terminal. These source code samples are taken from different open source projects.

Example 1
Project: lanterna-master  File: DefaultVirtualTerminalTest.java View source code
@Test
public void testVirtualTerminalListener() {
    final AtomicInteger flushCounter = new AtomicInteger(0);
    final AtomicInteger bellCounter = new AtomicInteger(0);
    final AtomicInteger resizeCounter = new AtomicInteger(0);
    final AtomicInteger closeCounter = new AtomicInteger(0);
    VirtualTerminalListener listener = new VirtualTerminalListener() {

        @Override
        public void onFlush() {
            flushCounter.incrementAndGet();
        }

        @Override
        public void onBell() {
            bellCounter.incrementAndGet();
        }

        @Override
        public void onResized(Terminal terminal, TerminalSize newSize) {
            resizeCounter.incrementAndGet();
        }

        @Override
        public void onClose() {
            closeCounter.incrementAndGet();
        }
    };
    virtualTerminal.flush();
    virtualTerminal.bell();
    virtualTerminal.setTerminalSize(new TerminalSize(40, 10));
    assertEquals(0, flushCounter.get());
    assertEquals(0, bellCounter.get());
    assertEquals(0, resizeCounter.get());
    assertEquals(0, closeCounter.get());
    virtualTerminal.addVirtualTerminalListener(listener);
    virtualTerminal.flush();
    virtualTerminal.bell();
    virtualTerminal.setTerminalSize(new TerminalSize(80, 20));
    assertEquals(1, flushCounter.get());
    assertEquals(1, bellCounter.get());
    assertEquals(1, resizeCounter.get());
    assertEquals(0, closeCounter.get());
    virtualTerminal.close();
    assertEquals(1, closeCounter.get());
    virtualTerminal.removeVirtualTerminalListener(listener);
    virtualTerminal.flush();
    virtualTerminal.bell();
    virtualTerminal.setTerminalSize(new TerminalSize(40, 10));
    virtualTerminal.close();
    assertEquals(1, flushCounter.get());
    assertEquals(1, bellCounter.get());
    assertEquals(1, resizeCounter.get());
    assertEquals(1, closeCounter.get());
}
Example 2
Project: snake-15-master  File: TerminalGameOverViewTest.java View source code
/*
	 * General setup for tests some of these stubbed methods will be overridden
	 * in the test methods but generally this return values will work.
	 */
@Before
public void setUp() throws Exception {
    key = Mockito.mock(Key.class);
    terminal = Mockito.mock(Terminal.class);
    terminalSize = Mockito.mock(TerminalSize.class);
    presenter = Mockito.mock(GameOverPresenter.class);
    gameOver = Mockito.spy(new TerminalGameOverView(presenter, terminal));
    Mockito.when(terminalSize.getRows()).thenReturn(100);
    Mockito.when(terminalSize.getColumns()).thenReturn(100);
    Mockito.when(terminal.getTerminalSize()).thenReturn(terminalSize);
}
Example 3
Project: multivim-master  File: Screen.java View source code
//WARNING!!! Should only be called in a block synchronized on mutex! See refresh()
private void resizeScreenIfNeeded() {
    TerminalSize newSize;
    synchronized (resizeQueue) {
        if (resizeQueue.isEmpty())
            return;
        newSize = resizeQueue.getLast();
        resizeQueue.clear();
    }
    int height = newSize.getRows();
    int width = newSize.getColumns();
    ScreenCharacter[][] newBackBuffer = new ScreenCharacter[height][width];
    ScreenCharacter[][] newVisibleScreen = new ScreenCharacter[height][width];
    ScreenCharacter newAreaCharacter = new ScreenCharacter('X', Terminal.Color.GREEN, Terminal.Color.BLACK);
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (backbuffer.length > 0 && x < backbuffer[0].length && y < backbuffer.length)
                newBackBuffer[y][x] = backbuffer[y][x];
            else
                newBackBuffer[y][x] = new ScreenCharacter(newAreaCharacter);
            if (visibleScreen.length > 0 && x < visibleScreen[0].length && y < visibleScreen.length)
                newVisibleScreen[y][x] = visibleScreen[y][x];
            else
                newVisibleScreen[y][x] = new ScreenCharacter(newAreaCharacter);
        }
    }
    backbuffer = newBackBuffer;
    visibleScreen = newVisibleScreen;
    wholeScreenInvalid = true;
    terminalSize = new TerminalSize(newSize);
}
Example 4
Project: GenericMBeanCLI-master  File: PrimaryGuiWindow.java View source code
/**
     * Do authentication.
     *
     * @param info            the info
     * @param usernameTextBox the username text box
     * @param passwordTextBox the password text box
     */
public void doAuthentication(Label info, TextBox usernameTextBox, TextBox passwordTextBox) {
    AUTHENTICATION.login(usernameTextBox.getText(), passwordTextBox.getText());
    // If Authentication is successful then show the CLI Interface
    if (AUTHENTICATION.isLoggedIn()) {
        getInstance().removeAllComponents();
        getInstance().addComponent(CliGui.getInstance().drawGui());
    } else // Otherwise show an error message
    {
        final String message = "Wrong Username/Password combination!! Please try again";
        GUI_HELPER.displayMessage(info, message, Terminal.Color.RED, Theme.Category.SHADOW);
    }
}
Example 5
Project: eoulsan-master  File: LanternaUI.java View source code
/**
   * Put a string on the terminal with a defined color.
   * @param x x position of the string
   * @param y y position of the string
   * @param s the string to print
   * @param sgr the formatting attribute to use
   * @return x position after printing the line
   */
private int putStringSGR(final int x, final int y, final String s, final Terminal.SGR sgr) {
    if (sgr != null) {
        this.terminal.applySGR(sgr);
    }
    final int result = putString(x, y, s);
    if (sgr != null) {
        final Terminal.SGR exitSGR;
        switch(sgr) {
            case ENTER_BLINK:
                exitSGR = Terminal.SGR.EXIT_BLINK;
                break;
            case ENTER_BOLD:
                exitSGR = Terminal.SGR.EXIT_BOLD;
                break;
            case ENTER_REVERSE:
                exitSGR = Terminal.SGR.EXIT_REVERSE;
                break;
            case ENTER_UNDERLINE:
                exitSGR = Terminal.SGR.EXIT_UNDERLINE;
                break;
            default:
                exitSGR = Terminal.SGR.RESET_ALL;
                break;
        }
        this.terminal.applySGR(exitSGR);
    }
    return result;
}
Example 6
Project: condi-master  File: Tree.java View source code
@Override
public void repaint(TextGraphics graphics) {
    // Clear area
    graphics.setBackgroundColor(Terminal.Color.DEFAULT);
    graphics.setForegroundColor(Terminal.Color.WHITE);
    graphics.fillArea(' ');
    height = graphics.getHeight();
    itemsCount = buildChilds(graphics, 0, root, -1);
    if (itemsCount > 0) {
        // Draw scroll bar
        double proportion = (double) height / itemsCount;
        int startRow = (int) (firstVisibleRow * proportion);
        int fillRows = (int) (height * proportion) + 1;
        graphics.setBackgroundColor(Terminal.Color.DEFAULT);
        graphics.setForegroundColor(Terminal.Color.WHITE);
        graphics.fillRectangle('░', new TerminalPosition(graphics.getWidth() - 1, 0), new TerminalSize(1, height));
        graphics.fillRectangle('█', new TerminalPosition(graphics.getWidth() - 1, startRow), new TerminalSize(1, fillRows));
    }
}
Example 7
Project: opencit-master  File: Wizard.java View source code
@Override
public void execute(String[] args) throws Exception {
    // createTextTerminal requires the file stty.exe
    // createUnixTermainal requires the file /bin/sh
    Terminal terminal;
    if (Platform.isWindows()) {
        terminal = TerminalFacade.createSwingTerminal();
    } else if (Platform.isUnix()) {
        // can also pass Charset.forName("UTF8"),  or System.in, System.out, Charset.forName("UTF8")
        terminal = TerminalFacade.createUnixTerminal(Charset.forName("UTF8"));
    } else {
        System.err.println("Unrecognized platform: " + System.getProperty("os.name"));
        return;
    }
    //        terminal.enterPrivateMode();
    //        terminal.clearScreen();  // not needed in the beginning as it's done by default; but we could do it anytime later
    //        terminal.flush(); // ensure our actions are written to the terminal
    //        TerminalSize screenSize = terminal.getTerminalSize();
    //        terminal.moveCursor(screenSize.getColumns() - 1, screenSize.getRows() - 1);  //Place the cursor in the bottom right corner
    Screen screen = new Screen(terminal);
    screen.startScreen();
    /*
        screen.putString(10, 5, "Hello Lanterna!", Terminal.Color.RED, Terminal.Color.GREEN);
        screen.refresh();
        
        boolean keepRunning = true;
        while(keepRunning) {
            Key key = screen.readInput();
            if( key != null ) {
                if( key.getCharacter() == 'x' ) { keepRunning = false; }
                System.err.println("hit character "+key.getCharacter());
            }
        }
        
        * */
    GUIScreen gui = new GUIScreen(screen);
    if (gui == null) {
        System.err.println("Cannot initialize terminal");
        return;
    }
    MyWindow wnd = new MyWindow();
    gui.showWindow(wnd);
    screen.stopScreen();
//        terminal.exitPrivateMode();
}
Example 8
Project: analytics_util-master  File: CursesVisualize.java View source code
public void display(final TotalSummary totalSummary) throws IOException {
    // Setup terminal and screen layers
    Terminal terminal = new DefaultTerminalFactory().createTerminal();
    Screen screen = new TerminalScreen(terminal);
    screen.startScreen();
    Table<String> connectedColumns = new Table<>("Col 1", "Col 2");
    connectedColumns.setVisibleRows(10);
    for (Map<String, Object> columnConn : totalSummary.getConnectedColumns()) {
        String col1 = (String) columnConn.get("column 1");
        String col2 = (String) columnConn.get("column 2");
        connectedColumns.getTableModel().addRow(col1 + "  ", col2);
    }
    // Create gui and start gui
    final MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLUE));
    final BasicWindow window = new BasicWindow();
    window.setHints(Arrays.asList(Window.Hint.CENTERED));
    window.setCloseWindowWithEscape(true);
    Panel panel = new Panel();
    panel.setLayoutManager(new GridLayout(1).setVerticalSpacing(1).setHorizontalSpacing(0));
    /*
    Panel panel = new Panel();
    final ComboBox<String> comboBox = new ComboBox<String>().setReadOnly(false);
    for(Map.Entry<String, Summary> kv : totalSummary.getColumnSummaries().entrySet()) {
      comboBox.addItem(kv.getKey());
    }
    Button button = new Button("Show", new Runnable() {
      @Override
      public void run() {
        String column = comboBox.getSelectedItem();
        Summary summary = totalSummary.getColumnSummaries().get(column);
        new ColumnDisplayer(gui, summary, column).run();
      }
    });
    panel.addComponent(new Label("Column Statistical Details"));
    panel.addComponent(new EmptySpace(new TerminalSize(0, 0))); // Empty space underneath labels
    panel.addComponent(comboBox);
    panel.addComponent(button);
    panel.addComponent(new Label("Interesting Connections\nBased on Loglikelihood"));
    panel.addComponent(new EmptySpace(new TerminalSize(0,0))); // Empty space underneath labels
    panel.addComponent(connectedColumns);
    */
    ActionListBox actionListBox = new ActionListBox();
    NumberFormat percentFormatter;
    percentFormatter = NumberFormat.getPercentInstance();
    for (Map.Entry<String, Summary> kv : totalSummary.getColumnSummaries().entrySet()) {
        double percentMissing = kv.getValue().getNumInvalid().doubleValue() / kv.getValue().getTotalCount();
        String actionName = kv.getKey() + " (" + percentFormatter.format(percentMissing) + " Missing)";
        actionListBox.addItem(actionName, new ColumnDisplayer(gui, kv.getValue(), kv.getKey()));
    }
    panel.addComponent(new Label("Column Statistical Details"));
    panel.addComponent(actionListBox);
    window.setComponent(panel);
    gui.addWindowAndWait(window);
}
Example 9
Project: Omicron-master  File: MapView.java View source code
@Override
protected void drawForeground(final Screen screen) {
    super.drawForeground(screen);
    Optional<IGameController> gameController = OmicronCLI.get().getGameController();
    if (!gameController.isPresent())
        return;
    Optional<IPlayer> localPlayerOptional = OmicronCLI.get().getLocalPlayer();
    if (!localPlayerOptional.isPresent())
        return;
    IPlayer localPlayer = localPlayerOptional.get();
    // Create an empty grid.
    Size levelSize = gameController.get().getGame().getLevel(getLevelType()).getSize();
    Table<Integer, Integer, ITile> grid = HashBasedTable.create(levelSize.getHeight(), levelSize.getWidth());
    // Iterate observable tiles and populate the grid.
    localPlayer.observableTiles().forEach( tile -> {
        Vec2 coordinate = positionToMapCoordinate(tile.getPosition());
        grid.put(coordinate.getY(), coordinate.getX(), tile);
    });
    // Draw grid in view.
    Box contentBox = getContentBoxOnScreen();
    for (int screenX = contentBox.getLeft(); screenX <= contentBox.getRight(); ++screenX) for (int screenY = contentBox.getTop(); screenY <= contentBox.getBottom(); ++screenY) {
        int tileY = screenY - contentBox.getTop() + getOffset().getY();
        int tileX = screenX - contentBox.getLeft() + getOffset().getX();
        if (!levelSize.isInBounds(Vec2.create(tileX, tileY)))
            continue;
        ITile tile = grid.get(tileY, tileX);
        Maybe<? extends IGameObject> contents;
        Terminal.Color bgColor = getBackgroundColor();
        if (tile == null)
            contents = Maybe.empty();
        else {
            contents = tile.getContents();
            bgColor = levelTypeColors.get(tile.getLevel().getType());
            for (final ResourceType resourceType : ResourceType.values()) {
                Maybe<Integer> resourceQuantity = tile.getResourceQuantity(resourceType);
                if (resourceQuantity.presence() == Maybe.Presence.PRESENT)
                    bgColor = resourceTypeColors.get(resourceType);
            }
        }
        screen.putString(screenX + (screenY % 2 == 0 ? 0 : 1), screenY, contents.presence() == Maybe.Presence.PRESENT ? contents.get().getType().getTypeName().substring(0, 1) : " ", getMapColor(), bgColor, ScreenCharacterStyle.Bold);
    // Draw off-screen warning labels.
    }
    Inset offScreen = new Inset(Math.max(0, getOffset().getY()), Math.max(0, levelSize.getWidth() - contentBox.getSize().getWidth() - getOffset().getX() + 1), Math.max(0, levelSize.getHeight() - contentBox.getSize().getHeight() - getOffset().getY() - 1), Math.max(0, getOffset().getX()));
    int centerX = contentBox.getLeft() + (levelSize.getWidth() - offScreen.getHorizontal()) / 2 - getOffset().getX() + offScreen.getLeft();
    int centerY = contentBox.getTop() + (levelSize.getHeight() - offScreen.getVertical()) / 2 - getOffset().getY() + offScreen.getTop();
    centerX = Math.min(contentBox.getRight() - 3, Math.max(contentBox.getLeft(), centerX));
    centerY = Math.min(contentBox.getBottom() - 1, Math.max(contentBox.getTop() + 1, centerY));
    if (offScreen.getTop() > 0)
        //
        screen.putString(//
        centerX, //
        contentBox.getTop(), String.format("%+d", offScreen.getTop()), getInfoTextColor(), getInfoBackgroundColor());
    if (offScreen.getRight() > 0) {
        String label = String.format("%+d", offScreen.getRight());
        //
        screen.putString(//
        contentBox.getRight() - label.length(), //
        centerY, label, getInfoTextColor(), getInfoBackgroundColor());
    }
    if (offScreen.getBottom() > 0)
        //
        screen.putString(//
        centerX, //
        contentBox.getBottom(), String.format("%+d", offScreen.getBottom()), getInfoTextColor(), getInfoBackgroundColor());
    if (offScreen.getLeft() > 0)
        //
        screen.putString(//
        contentBox.getLeft(), //
        centerY, String.format("%+d", offScreen.getLeft()), getInfoTextColor(), getInfoBackgroundColor());
}