Java Code Examples for com.googlecode.lanterna.TerminalSize#getRows()

The following examples show how to use com.googlecode.lanterna.TerminalSize#getRows() . 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: BasicTextImage.java    From lanterna with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new BasicTextImage by copying a region of a two-dimensional array of TextCharacter:s. If the area to be 
 * copied to larger than the source array, a filler character is used.
 * @param size Size to create the new BasicTextImage as (and size to copy from the array)
 * @param toCopy Array to copy initial data from
 * @param initialContent Filler character to use if the source array is smaller than the requested size
 */
private BasicTextImage(TerminalSize size, TextCharacter[][] toCopy, TextCharacter initialContent) {
    if(size == null || toCopy == null || initialContent == null) {
        throw new IllegalArgumentException("Cannot create BasicTextImage with null " +
                (size == null ? "size" : (toCopy == null ? "toCopy" : "filler")));
    }
    this.size = size;
    
    int rows = size.getRows();
    int columns = size.getColumns();
    buffer = new TextCharacter[rows][];
    for(int y = 0; y < rows; y++) {
        buffer[y] = new TextCharacter[columns];
        for(int x = 0; x < columns; x++) {
            if(y < toCopy.length && x < toCopy[y].length) {
                buffer[y][x] = toCopy[y][x];
            }
            else {
                buffer[y][x] = initialContent;
            }
        }
    }
}
 
Example 2
Source File: DefaultShapeRenderer.java    From lanterna with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void fillRectangle(TerminalPosition topLeft, TerminalSize size, TextCharacter character) {
    final boolean characterDoubleWidth = character.isDoubleWidth();
    for(int y = 0; y < size.getRows(); y++) {
        for(int x = 0; x < size.getColumns(); x++) {
            // Don't put a double-width character at the right edge of the area
            if (characterDoubleWidth && x + 1 == size.getColumns()) {
                callback.onPoint(topLeft.getColumn() + x, topLeft.getRow() + y, character.withCharacter(' '));
            }
            else {
                // Default case
                callback.onPoint(topLeft.getColumn() + x, topLeft.getRow() + y, character);
            }
            if (characterDoubleWidth) {
                x++;
            }
        }
    }
}
 
Example 3
Source File: LinearLayout.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
private TerminalSize getPreferredSizeVertically(List<Component> components) {
    int maxWidth = 0;
    int height = 0;
    for(Component component: components) {
        TerminalSize preferredSize = component.getPreferredSize();
        if(maxWidth < preferredSize.getColumns()) {
            maxWidth = preferredSize.getColumns();
        }
        height += preferredSize.getRows();
    }
    height += spacing * (components.size() - 1);
    return new TerminalSize(maxWidth, Math.max(0, height));
}
 
Example 4
Source File: BasicTextImage.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public BasicTextImage resize(TerminalSize newSize, TextCharacter filler) {
    if(newSize == null || filler == null) {
        throw new IllegalArgumentException("Cannot resize BasicTextImage with null " +
                (newSize == null ? "newSize" : "filler"));
    }
    if(newSize.getRows() == buffer.length &&
            (buffer.length == 0 || newSize.getColumns() == buffer[0].length)) {
        return this;
    }
    return new BasicTextImage(newSize, buffer, filler);
}
 
Example 5
Source File: VirtualTerminalTextGraphics.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public TextGraphics setCharacter(int columnIndex, int rowIndex, TextCharacter textCharacter) {
    TerminalSize size = getSize();
    if(columnIndex < 0 || columnIndex >= size.getColumns() ||
            rowIndex < 0 || rowIndex >= size.getRows()) {
        return this;
    }
    synchronized(virtualTerminal) {
        virtualTerminal.setCursorPosition(new TerminalPosition(columnIndex, rowIndex));
        virtualTerminal.putCharacter(textCharacter);
    }
    return this;
}
 
Example 6
Source File: InteractableLookupMap.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
InteractableLookupMap(TerminalSize size) {
    lookupMap = new int[size.getRows()][size.getColumns()];
    interactables = new ArrayList<>();
    for (int[] aLookupMap : lookupMap) {
        Arrays.fill(aLookupMap, -1);
    }
}
 
Example 7
Source File: NewSwingTerminalTest.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates new form NewSwingTerminalTest
 */
public NewSwingTerminalTest() {
    initComponents();

    final SwingTerminal leftTerminal = new SwingTerminal();
    final SwingTerminal rightTerminal = new SwingTerminal();
    splitPane.setLeftComponent(leftTerminal);
    splitPane.setRightComponent(rightTerminal);
    pack();

    Timer timer = new Timer(500, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            drawRandomHello(leftTerminal);
            drawRandomHello(rightTerminal);
        }

        private void drawRandomHello(IOSafeTerminal terminal) {
            TerminalSize size = terminal.getTerminalSize();
            if(size.getColumns() > 6 && size.getRows() > 1) {
                int positionX = RANDOM.nextInt(size.getColumns() - 6);
                int positionY = RANDOM.nextInt(size.getRows());

                terminal.setCursorPosition(positionX, positionY);
                terminal.setBackgroundColor(new TextColor.Indexed(RANDOM.nextInt(256)));
                terminal.setForegroundColor(new TextColor.Indexed(RANDOM.nextInt(256)));
                String hello = "Hello!";
                for(int i = 0; i < hello.length(); i++) {
                    terminal.putCharacter(hello.charAt(i));
                }
                terminal.flush();
            }
        }
    });
    timer.start();
}
 
Example 8
Source File: LinearLayout.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
private TerminalSize getPreferredSizeHorizontally(List<Component> components) {
    int maxHeight = 0;
    int width = 0;
    for(Component component: components) {
        TerminalSize preferredSize = component.getPreferredSize();
        if(maxHeight < preferredSize.getRows()) {
            maxHeight = preferredSize.getRows();
        }
        width += preferredSize.getColumns();
    }
    width += spacing * (components.size() - 1);
    return new TerminalSize(Math.max(0,width), maxHeight);
}
 
Example 9
Source File: TerminalResizeTest.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onResized(Terminal terminal, TerminalSize newSize) {
    try {
        terminal.setCursorPosition(0, 0);
        String string = newSize.getColumns() + "x" + newSize.getRows() + "                     ";
        char[] chars = string.toCharArray();
        for(char c : chars) {
            terminal.putCharacter(c);
        }
        terminal.flush();
    }
    catch(IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: DefaultWindowManager.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Called by {@link DefaultWindowManager} when iterating through all windows to decide their size and position. If
 * you override {@link DefaultWindowManager} to add your own logic to how windows are placed on the screen, you can
 * override this method and selectively choose which window to interfere with. Note that the two key properties that
 * are read by the GUI system after preparing all windows are the position and decorated size. Your custom
 * implementation should set these two fields directly on the window. You can infer the decorated size from the
 * content size by using the window decoration renderer that is attached to the window manager.
 *
 * @param screenSize Size of the terminal that is available to draw on
 * @param window Window to prepare decorated size and position for
 */
protected void prepareWindow(TerminalSize screenSize, Window window) {
    TerminalSize contentAreaSize;
    if(window.getHints().contains(Window.Hint.FIXED_SIZE)) {
        contentAreaSize = window.getSize();
    }
    else {
        contentAreaSize = window.getPreferredSize();
    }
    TerminalSize size = getWindowDecorationRenderer(window).getDecoratedSize(window, contentAreaSize);
    TerminalPosition position = window.getPosition();

    if(window.getHints().contains(Window.Hint.FULL_SCREEN)) {
        position = TerminalPosition.TOP_LEFT_CORNER;
        size = screenSize;
    }
    else if(window.getHints().contains(Window.Hint.EXPANDED)) {
        position = TerminalPosition.OFFSET_1x1;
        size = screenSize.withRelative(
                -Math.min(4, screenSize.getColumns()),
                -Math.min(3, screenSize.getRows()));
        if(!size.equals(window.getDecoratedSize())) {
            window.invalidate();
        }
    }
    else if(window.getHints().contains(Window.Hint.FIT_TERMINAL_WINDOW) ||
            window.getHints().contains(Window.Hint.CENTERED)) {
        //If the window is too big for the terminal, move it up towards 0x0 and if that's not enough then shrink
        //it instead
        while(position.getRow() > 0 && position.getRow() + size.getRows() > screenSize.getRows()) {
            position = position.withRelativeRow(-1);
        }
        while(position.getColumn() > 0 && position.getColumn() + size.getColumns() > screenSize.getColumns()) {
            position = position.withRelativeColumn(-1);
        }
        if(position.getRow() + size.getRows() > screenSize.getRows()) {
            size = size.withRows(screenSize.getRows() - position.getRow());
        }
        if(position.getColumn() + size.getColumns() > screenSize.getColumns()) {
            size = size.withColumns(screenSize.getColumns() - position.getColumn());
        }
        if(window.getHints().contains(Window.Hint.CENTERED)) {
            int left = (lastKnownScreenSize.getColumns() - size.getColumns()) / 2;
            int top = (lastKnownScreenSize.getRows() - size.getRows()) / 2;
            position = new TerminalPosition(left, top);
        }
    }

    window.setPosition(position);
    window.setDecoratedSize(size);
}
 
Example 11
Source File: DirectoryDialog.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Default constructor for {@code DirectoryDialog}
 *
 * @param title          Title of the dialog
 * @param description    Description of the dialog, is displayed at the top of the content area
 * @param actionLabel    Label to use on the "confirm" button, for example "open" or "save"
 * @param dialogSize     Rough estimation of how big you want the dialog to be
 * @param showHiddenDirs If {@code true}, hidden directories will be visible
 * @param selectedObject Initially selected directory node
 */
public DirectoryDialog(
        String title,
        String description,
        String actionLabel,
        TerminalSize dialogSize,
        boolean showHiddenDirs,
        File selectedObject) {
    super(title);
    this.selectedDir = null;
    this.showHiddenDirs = showHiddenDirs;

    if (selectedObject == null || !selectedObject.exists()) {
        selectedObject = new File("").getAbsoluteFile();
    }
    selectedObject = selectedObject.getAbsoluteFile();

    Panel contentPane = new Panel();
    contentPane.setLayoutManager(new BorderLayout());

    Panel dirsPane = new Panel();
    dirsPane.setLayoutManager(new BorderLayout());
    contentPane.addComponent(dirsPane, Location.CENTER);

    if (description != null)
        contentPane.addComponent(new Label(description), Location.TOP);

    int unitHeight = dialogSize.getRows();

    dirListBox = new ActionListBox(new TerminalSize(dialogSize.getColumns(), unitHeight));
    dirsPane.addComponent(dirListBox.withBorder(Borders.singleLine()), Location.CENTER);

    dirBox = new TextBox(new TerminalSize(dialogSize.getColumns(), 1));
    dirsPane.addComponent(dirBox.withBorder(Borders.singleLine()), Location.BOTTOM);

    Panel panelButtons = new Panel(new GridLayout(2));
    panelButtons.setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.END, GridLayout.Alignment.CENTER, false, false, 2, 1));
    panelButtons.addComponent(new Button(actionLabel, new OkHandler()));
    panelButtons.addComponent(new Button(LocalizedString.Cancel.toString(), new CancelHandler()));
    contentPane.addComponent(panelButtons, Location.BOTTOM);

    if (selectedObject.isFile()) {
        directory = selectedObject.getParentFile();
    }
    else if (selectedObject.isDirectory()) {
        directory = selectedObject;
    }

    reloadViews(directory);
    setComponent(contentPane);
}
 
Example 12
Source File: LinearLayout.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Deprecated
private void doHorizontalLayout(TerminalSize area, List<Component> components) {
    int remainingHorizontalSpace = area.getColumns();
    int availableVerticalSpace = area.getRows();
    for(Component component: components) {
        if(remainingHorizontalSpace <= 0) {
            component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
            component.setSize(TerminalSize.ZERO);
        }
        else {
            Alignment alignment = Alignment.Beginning;
            LayoutData layoutData = component.getLayoutData();
            if (layoutData instanceof LinearLayoutData) {
                alignment = ((LinearLayoutData)layoutData).alignment;
            }

            TerminalSize preferredSize = component.getPreferredSize();
            TerminalSize decidedSize = new TerminalSize(
                    Math.min(remainingHorizontalSpace, preferredSize.getColumns()),
                    Math.min(availableVerticalSpace, preferredSize.getRows()));
            if(alignment == Alignment.Fill) {
                decidedSize = decidedSize.withRows(availableVerticalSpace);
                alignment = Alignment.Beginning;
            }

            TerminalPosition position = component.getPosition();
            position = position.withColumn(area.getColumns() - remainingHorizontalSpace);
            switch(alignment) {
                case End:
                    position = position.withRow(availableVerticalSpace - decidedSize.getRows());
                    break;
                case Center:
                    position = position.withRow((availableVerticalSpace - decidedSize.getRows()) / 2);
                    break;
                case Beginning:
                default:
                    position = position.withRow(0);
                    break;
            }
            component.setPosition(position);
            component.setSize(component.getSize().with(decidedSize));
            remainingHorizontalSpace -= decidedSize.getColumns() + spacing;
        }
    }
}
 
Example 13
Source File: ScreenTriangleTest.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    boolean useAnsiColors = false;
    boolean useFilled = false;
    boolean slow = false;
    boolean rotating = false;
    boolean square = false;
    for(String arg : args) {
        if(arg.equals("--ansi-colors")) {
            useAnsiColors = true;
        }
        if(arg.equals("--filled")) {
            useFilled = true;
        }
        if(arg.equals("--slow")) {
            slow = true;
        }
        if(arg.equals("--rotating")) {
            rotating = true;
        }
        if(arg.equals("--square")) {
            square = true;
        }
    }
    Screen screen = new TestTerminalFactory(args).createScreen();
    screen.startScreen();

    TextGraphics graphics = new ScreenTextGraphics(screen);
    if(square) {
        graphics = new DoublePrintingTextGraphics(graphics);
    }
    Random random = new Random();

    TextColor color = null;
    double rad = 0.0;
    while(true) {
        KeyStroke keyStroke = screen.pollInput();
        if(keyStroke != null &&
                (keyStroke.getKeyType() == KeyType.Escape || keyStroke.getKeyType() == KeyType.EOF)) {
            break;
        }
        screen.doResizeIfNecessary();
        TerminalSize size = graphics.getSize();
        if(useAnsiColors) {
            if(color == null || !rotating) {
                color = TextColor.ANSI.values()[random.nextInt(TextColor.ANSI.values().length)];
            }
        }
        else {
            if(color == null || !rotating) {
                //Draw a rectangle in random indexed color
                color = new TextColor.Indexed(random.nextInt(256));
            }
        }

        TerminalPosition p1;
        TerminalPosition p2;
        TerminalPosition p3;
        if(rotating) {
            screen.clear();
            double triangleSize = 15.0;
            int x0 = (size.getColumns() / 2) + (int) (Math.cos(rad) * triangleSize);
            int y0 = (size.getRows() / 2) + (int) (Math.sin(rad) * triangleSize);
            int x1 = (size.getColumns() / 2) + (int) (Math.cos(rad + oneThirdOf2PI) * triangleSize);
            int y1 = (size.getRows() / 2) + (int) (Math.sin(rad + oneThirdOf2PI) * triangleSize);
            int x2 = (size.getColumns() / 2) + (int) (Math.cos(rad + twoThirdsOf2PI) * triangleSize);
            int y2 = (size.getRows() / 2) + (int) (Math.sin(rad + twoThirdsOf2PI) * triangleSize);
            p1 = new TerminalPosition(x0, y0);
            p2 = new TerminalPosition(x1, y1);
            p3 = new TerminalPosition(x2, y2);
            rad += Math.PI / 90.0;
        }
        else {
            p1 = new TerminalPosition(random.nextInt(size.getColumns()), random.nextInt(size.getRows()));
            p2 = new TerminalPosition(random.nextInt(size.getColumns()), random.nextInt(size.getRows()));
            p3 = new TerminalPosition(random.nextInt(size.getColumns()), random.nextInt(size.getRows()));
        }

        graphics.setBackgroundColor(color);
        if(useFilled) {
            graphics.fillTriangle(p1, p2, p3, ' ');
        }
        else {
            graphics.drawTriangle(p1, p2, p3, ' ');
        }
        screen.refresh(Screen.RefreshType.DELTA);
        if(slow) {
            Thread.sleep(500);
        }
    }
    screen.stopScreen();
}
 
Example 14
Source File: TextBox.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void drawComponent(TextGUIGraphics graphics, TextBox component) {
    TerminalSize realTextArea = graphics.getSize();
    if(realTextArea.getRows() == 0 || realTextArea.getColumns() == 0) {
        return;
    }
    boolean drawVerticalScrollBar = false;
    boolean drawHorizontalScrollBar = false;
    int textBoxLineCount = component.getLineCount();
    if(!hideScrollBars && textBoxLineCount > realTextArea.getRows() && realTextArea.getColumns() > 1) {
        realTextArea = realTextArea.withRelativeColumns(-1);
        drawVerticalScrollBar = true;
    }
    if(!hideScrollBars && component.longestRow > realTextArea.getColumns() && realTextArea.getRows() > 1) {
        realTextArea = realTextArea.withRelativeRows(-1);
        drawHorizontalScrollBar = true;
        if(textBoxLineCount > realTextArea.getRows() && !drawVerticalScrollBar) {
            realTextArea = realTextArea.withRelativeColumns(-1);
            drawVerticalScrollBar = true;
        }
    }

    drawTextArea(graphics.newTextGraphics(TerminalPosition.TOP_LEFT_CORNER, realTextArea), component);

    //Draw scrollbars, if any
    if(drawVerticalScrollBar) {
        verticalScrollBar.onAdded(component.getParent());
        verticalScrollBar.setViewSize(realTextArea.getRows());
        verticalScrollBar.setScrollMaximum(textBoxLineCount);
        verticalScrollBar.setScrollPosition(viewTopLeft.getRow());
        verticalScrollBar.draw(graphics.newTextGraphics(
                new TerminalPosition(graphics.getSize().getColumns() - 1, 0),
                new TerminalSize(1, graphics.getSize().getRows() - (drawHorizontalScrollBar ? 1 : 0))));
    }
    if(drawHorizontalScrollBar) {
        horizontalScrollBar.onAdded(component.getParent());
        horizontalScrollBar.setViewSize(realTextArea.getColumns());
        horizontalScrollBar.setScrollMaximum(component.longestRow - 1);
        horizontalScrollBar.setScrollPosition(viewTopLeft.getColumn());
        horizontalScrollBar.draw(graphics.newTextGraphics(
                new TerminalPosition(0, graphics.getSize().getRows() - 1),
                new TerminalSize(graphics.getSize().getColumns() - (drawVerticalScrollBar ? 1 : 0), 1)));
    }
}
 
Example 15
Source File: TextBox.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void drawTextArea(TextGUIGraphics graphics, TextBox component) {
    TerminalSize textAreaSize = graphics.getSize();
    if(viewTopLeft.getColumn() + textAreaSize.getColumns() > component.longestRow) {
        viewTopLeft = viewTopLeft.withColumn(component.longestRow - textAreaSize.getColumns());
        if(viewTopLeft.getColumn() < 0) {
            viewTopLeft = viewTopLeft.withColumn(0);
        }
    }
    if(viewTopLeft.getRow() + textAreaSize.getRows() > component.getLineCount()) {
        viewTopLeft = viewTopLeft.withRow(component.getLineCount() - textAreaSize.getRows());
        if(viewTopLeft.getRow() < 0) {
            viewTopLeft = viewTopLeft.withRow(0);
        }
    }
    ThemeDefinition themeDefinition = component.getThemeDefinition();
    if (component.isFocused()) {
        if(component.isReadOnly()) {
            graphics.applyThemeStyle(themeDefinition.getSelected());
        }
        else {
            graphics.applyThemeStyle(themeDefinition.getActive());
        }
    }
    else {
        if(component.isReadOnly()) {
            graphics.applyThemeStyle(themeDefinition.getInsensitive());
        }
        else {
            graphics.applyThemeStyle(themeDefinition.getNormal());
        }
    }

    Character fillCharacter = unusedSpaceCharacter;
    if(fillCharacter == null) {
        fillCharacter = themeDefinition.getCharacter("FILL", ' ');
    }
    graphics.fill(fillCharacter);

    if(!component.isReadOnly()) {
        //Adjust caret position if necessary
        TerminalPosition caretPosition = component.getCaretPosition();
        String caretLine = component.getLine(caretPosition.getRow());
        caretPosition = caretPosition.withColumn(Math.min(caretPosition.getColumn(), caretLine.length()));

        //Adjust the view if necessary
        int trueColumnPosition = TerminalTextUtils.getColumnIndex(caretLine, caretPosition.getColumn());
        if (trueColumnPosition < viewTopLeft.getColumn()) {
            viewTopLeft = viewTopLeft.withColumn(trueColumnPosition);
        }
        else if (trueColumnPosition >= textAreaSize.getColumns() + viewTopLeft.getColumn()) {
            viewTopLeft = viewTopLeft.withColumn(trueColumnPosition - textAreaSize.getColumns() + 1);
        }
        if (caretPosition.getRow() < viewTopLeft.getRow()) {
            viewTopLeft = viewTopLeft.withRow(caretPosition.getRow());
        }
        else if (caretPosition.getRow() >= textAreaSize.getRows() + viewTopLeft.getRow()) {
            viewTopLeft = viewTopLeft.withRow(caretPosition.getRow() - textAreaSize.getRows() + 1);
        }

        //Additional corner-case for CJK characters
        if(trueColumnPosition - viewTopLeft.getColumn() == graphics.getSize().getColumns() - 1) {
            if(caretLine.length() > caretPosition.getColumn() &&
                    TerminalTextUtils.isCharCJK(caretLine.charAt(caretPosition.getColumn()))) {
                viewTopLeft = viewTopLeft.withRelativeColumn(1);
            }
        }
    }

    for (int row = 0; row < textAreaSize.getRows(); row++) {
        int rowIndex = row + viewTopLeft.getRow();
        if(rowIndex >= component.lines.size()) {
            continue;
        }
        String line = component.lines.get(rowIndex);
        if(component.getMask() != null) {
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i < line.length(); i++) {
                builder.append(component.getMask());
            }
            line = builder.toString();
        }
        graphics.putString(0, row, TerminalTextUtils.fitString(line, viewTopLeft.getColumn(), textAreaSize.getColumns()));
    }
}
 
Example 16
Source File: ScreenLineTest.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    boolean useAnsiColors = false;
    boolean slow = false;
    boolean circle = false;
    for(String arg: args) {
        if(arg.equals("--ansi-colors")) {
            useAnsiColors = true;
        }
        if(arg.equals("--slow")) {
            slow = true;
        }
        if(arg.equals("--circle")) {
            circle = true;
        }
    }
    Screen screen = new TestTerminalFactory(args).createScreen();
    screen.startScreen();

    TextGraphics textGraphics = new ScreenTextGraphics(screen);
    Random random = new Random();
    while(true) {
        KeyStroke keyStroke = screen.pollInput();
        if(keyStroke != null &&
                (keyStroke.getKeyType() == KeyType.Escape || keyStroke.getKeyType() == KeyType.EOF)) {
            break;
        }
        screen.doResizeIfNecessary();
        TerminalSize size = textGraphics.getSize();
        TextColor color;
        if(useAnsiColors) {
            color = TextColor.ANSI.values()[random.nextInt(TextColor.ANSI.values().length)];
        }
        else {
            //Draw a rectangle in random indexed color
            color = new TextColor.Indexed(random.nextInt(256));
        }

        TerminalPosition p1;
        TerminalPosition p2;
        if(circle) {
            p1 = new TerminalPosition(size.getColumns() / 2, size.getRows() / 2);
            if(CIRCLE_LAST_POSITION == null) {
                CIRCLE_LAST_POSITION = new TerminalPosition(0, 0);
            }
            else if(CIRCLE_LAST_POSITION.getRow() == 0) {
                if(CIRCLE_LAST_POSITION.getColumn() < size.getColumns() - 1) {
                    CIRCLE_LAST_POSITION = CIRCLE_LAST_POSITION.withRelativeColumn(1);
                }
                else {
                    CIRCLE_LAST_POSITION = CIRCLE_LAST_POSITION.withRelativeRow(1);
                }
            }
            else if(CIRCLE_LAST_POSITION.getRow() < size.getRows() - 1) {
                if(CIRCLE_LAST_POSITION.getColumn() == 0) {
                    CIRCLE_LAST_POSITION = CIRCLE_LAST_POSITION.withRelativeRow(-1);
                }
                else {
                    CIRCLE_LAST_POSITION = CIRCLE_LAST_POSITION.withRelativeRow(1);
                }
            }
            else {
                if(CIRCLE_LAST_POSITION.getColumn() > 0) {
                    CIRCLE_LAST_POSITION = CIRCLE_LAST_POSITION.withRelativeColumn(-1);
                }
                else {
                    CIRCLE_LAST_POSITION = CIRCLE_LAST_POSITION.withRelativeRow(-1);
                }
            }
            p2 = CIRCLE_LAST_POSITION;
        }
        else {
            p1 = new TerminalPosition(random.nextInt(size.getColumns()), random.nextInt(size.getRows()));
            p2 = new TerminalPosition(random.nextInt(size.getColumns()), random.nextInt(size.getRows()));
        }
        textGraphics.setBackgroundColor(color);
        textGraphics.drawLine(p1, p2, ' ');
        textGraphics.setBackgroundColor(TextColor.ANSI.BLACK);
        textGraphics.setForegroundColor(TextColor.ANSI.WHITE);
        textGraphics.putString(4, size.getRows() - 1, "P1 " + p1 + " -> P2 " + p2);
        screen.refresh(Screen.RefreshType.DELTA);
        if(slow) {
            Thread.sleep(500);
        }
    }
    screen.stopScreen();
}
 
Example 17
Source File: BasicTextImage.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void copyTo(
        TextImage destination,
        int startRowIndex,
        int rows,
        int startColumnIndex,
        int columns,
        int destinationRowOffset,
        int destinationColumnOffset) {

    // If the source image position is negative, offset the whole image
    if(startColumnIndex < 0) {
        destinationColumnOffset += -startColumnIndex;
        columns += startColumnIndex;
        startColumnIndex = 0;
    }
    if(startRowIndex < 0) {
        destinationRowOffset += -startRowIndex;
        rows += startRowIndex;
        startRowIndex = 0;
    }

    // If the destination offset is negative, adjust the source start indexes
    if(destinationColumnOffset < 0) {
        startColumnIndex -= destinationColumnOffset;
        columns += destinationColumnOffset;
        destinationColumnOffset = 0;
    }
    if(destinationRowOffset < 0) {
        startRowIndex -= destinationRowOffset;
        rows += destinationRowOffset;
        destinationRowOffset = 0;
    }

    //Make sure we can't copy more than is available
    rows = Math.min(buffer.length - startRowIndex, rows);
    columns = rows>0 ? Math.min(buffer[0].length - startColumnIndex, columns) : 0;

    //Adjust target lengths as well
    columns = Math.min(destination.getSize().getColumns() - destinationColumnOffset, columns);
    rows = Math.min(destination.getSize().getRows() - destinationRowOffset, rows);

    if(columns <= 0 || rows <= 0) {
        return;
    }

    TerminalSize destinationSize = destination.getSize();
    if(destination instanceof BasicTextImage) {
        int targetRow = destinationRowOffset;
        for(int y = startRowIndex; y < startRowIndex + rows && targetRow < destinationSize.getRows(); y++) {
            System.arraycopy(buffer[y], startColumnIndex, ((BasicTextImage)destination).buffer[targetRow++], destinationColumnOffset, columns);
        }
    }
    else {
        //Manually copy character by character
        for(int y = startRowIndex; y < startRowIndex + rows; y++) {
            for(int x = startColumnIndex; x < startColumnIndex + columns; x++) {
                TextCharacter character = buffer[y][x];
                if (character.isDoubleWidth()) {
                    // If we're about to put a double-width character, first reset the character next to it
                    if (x + 1 < startColumnIndex + columns) {
                        destination.setCharacterAt(
                                x - startColumnIndex + destinationColumnOffset,
                                y - startRowIndex + destinationRowOffset,
                                character.withCharacter(' '));
                    }
                    // If the last character is a double-width character, it would exceed the dimension so reset it
                    else if (x + 1 == startColumnIndex + columns) {
                        character = character.withCharacter(' ');
                    }
                }
                destination.setCharacterAt(
                        x - startColumnIndex + destinationColumnOffset, 
                        y - startRowIndex + destinationRowOffset,
                        character);
                if (character.isDoubleWidth()) {
                    x++;
                }
            }
        }
    }

    // If the character immediately to the left in the destination is double-width, then reset it
    if (destinationColumnOffset > 0) {
        int destinationX = destinationColumnOffset - 1;
        for(int y = startRowIndex; y < startRowIndex + rows; y++) {
            int destinationY = y - startRowIndex + destinationRowOffset;
            TextCharacter neighbour = destination.getCharacterAt(destinationX, destinationY);
            if (neighbour.isDoubleWidth()) {
                destination.setCharacterAt(destinationX, destinationY, neighbour.withCharacter(' '));
            }
        }
    }
}
 
Example 18
Source File: LinearLayout.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Deprecated
private void doVerticalLayout(TerminalSize area, List<Component> components) {
    int remainingVerticalSpace = area.getRows();
    int availableHorizontalSpace = area.getColumns();
    for(Component component: components) {
        if(remainingVerticalSpace <= 0) {
            component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
            component.setSize(TerminalSize.ZERO);
        }
        else {
            Alignment alignment = Alignment.Beginning;
            LayoutData layoutData = component.getLayoutData();
            if (layoutData instanceof LinearLayoutData) {
                alignment = ((LinearLayoutData)layoutData).alignment;
            }

            TerminalSize preferredSize = component.getPreferredSize();
            TerminalSize decidedSize = new TerminalSize(
                    Math.min(availableHorizontalSpace, preferredSize.getColumns()),
                    Math.min(remainingVerticalSpace, preferredSize.getRows()));
            if(alignment == Alignment.Fill) {
                decidedSize = decidedSize.withColumns(availableHorizontalSpace);
                alignment = Alignment.Beginning;
            }

            TerminalPosition position = component.getPosition();
            position = position.withRow(area.getRows() - remainingVerticalSpace);
            switch(alignment) {
                case End:
                    position = position.withColumn(availableHorizontalSpace - decidedSize.getColumns());
                    break;
                case Center:
                    position = position.withColumn((availableHorizontalSpace - decidedSize.getColumns()) / 2);
                    break;
                case Beginning:
                default:
                    position = position.withColumn(0);
                    break;
            }
            component.setPosition(position);
            component.setSize(component.getSize().with(decidedSize));
            remainingVerticalSpace -= decidedSize.getRows() + spacing;
        }
    }
}
 
Example 19
Source File: TextBox.java    From lanterna with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Creates a new empty {@code TextBox} with a specific size
 * @param preferredSize Size of the {@code TextBox}
 */
public TextBox(TerminalSize preferredSize) {
    this(preferredSize, (preferredSize != null && preferredSize.getRows() > 1) ? Style.MULTI_LINE : Style.SINGLE_LINE);
}
 
Example 20
Source File: TextBox.java    From lanterna with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Creates a new empty {@code TextBox} with a specific size and initial content
 * @param preferredSize Size of the {@code TextBox}
 * @param initialContent Initial content of the {@code TextBox}
 */
public TextBox(TerminalSize preferredSize, String initialContent) {
    this(preferredSize, initialContent, (preferredSize != null && preferredSize.getRows() > 1) || initialContent.contains("\n") ? Style.MULTI_LINE : Style.SINGLE_LINE);
}