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

The following examples show how to use com.googlecode.lanterna.TerminalSize#getColumns() . 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: GridLayout.java    From lanterna with GNU Lesser General Public License v3.0 6 votes vote down vote up
private int shrinkWidthToFitArea(TerminalSize area, int[] columnWidths) {
    int totalWidth = 0;
    for(int width: columnWidths) {
        totalWidth += width;
    }
    if(totalWidth > area.getColumns()) {
        int columnOffset = 0;
        do {
            if(columnWidths[columnOffset] > 0) {
                columnWidths[columnOffset]--;
                totalWidth--;
            }
            if(++columnOffset == columnWidths.length) {
                columnOffset = 0;
            }
        }
        while(totalWidth > area.getColumns());
    }
    return totalWidth;
}
 
Example 2
Source File: MenuBar.java    From lanterna with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void drawComponent(TextGUIGraphics graphics, MenuBar menuBar) {
    // Reset the area
    graphics.applyThemeStyle(getThemeDefinition().getNormal());
    graphics.fill(' ');

    int leftPosition = EXTRA_PADDING;
    TerminalSize size = graphics.getSize();
    int remainingSpace = size.getColumns() - EXTRA_PADDING;
    for (int i = 0; i < menuBar.getMenuCount() && remainingSpace > 0; i++) {
        Menu menu = menuBar.getMenu(i);
        TerminalSize preferredSize = menu.getPreferredSize();
        menu.setPosition(menu.getPosition()
                .withColumn(leftPosition)
                .withRow(0));
        int finalWidth = Math.min(preferredSize.getColumns(), remainingSpace);
        menu.setSize(menu.getSize()
                        .withColumns(finalWidth)
                        .withRows(size.getRows()));
        remainingSpace -= finalWidth + EXTRA_PADDING;
        leftPosition += finalWidth + EXTRA_PADDING;
        TextGUIGraphics componentGraphics = graphics.newTextGraphics(menu.getPosition(), menu.getSize());
        menu.draw(componentGraphics);
    }
}
 
Example 3
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 4
Source File: GridLayout.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
private int grabExtraHorizontalSpace(TerminalSize area, int[] columnWidths, Set<Integer> expandableColumns, int totalWidth) {
    for(int columnIndex: expandableColumns) {
        columnWidths[columnIndex]++;
        totalWidth++;
        if(area.getColumns() == totalWidth) {
            break;
        }
    }
    return totalWidth;
}
 
Example 5
Source File: GridLayout.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
private int grabExtraVerticalSpace(TerminalSize area, int[] rowHeights, Set<Integer> expandableRows, int totalHeight) {
    for(int rowIndex: expandableRows) {
        rowHeights[rowIndex]++;
        totalHeight++;
        if(area.getColumns() == totalHeight) {
            break;
        }
    }
    return totalHeight;
}
 
Example 6
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 7
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 8
Source File: Button.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
private int getLabelShift(Button button, TerminalSize size) {
    int availableSpace = size.getColumns() - 2;
    if(availableSpace <= 0) {
        return 0;
    }
    int labelShift = 0;
    int widthInColumns = TerminalTextUtils.getColumnWidth(button.getLabel());
    if(availableSpace > widthInColumns) {
        labelShift = (size.getColumns() - 2 - widthInColumns) / 2;
    }
    return labelShift;
}
 
Example 9
Source File: DefaultWindowManager.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onAdded(WindowBasedTextGUI textGUI, Window window, List<Window> allWindows) {
    WindowDecorationRenderer decorationRenderer = getWindowDecorationRenderer(window);
    TerminalSize expectedDecoratedSize = decorationRenderer.getDecoratedSize(window, window.getPreferredSize());
    window.setDecoratedSize(expectedDecoratedSize);

    //noinspection StatementWithEmptyBody
    if(window.getHints().contains(Window.Hint.FIXED_POSITION)) {
        //Don't place the window, assume the position is already set
    }
    else if(allWindows.isEmpty()) {
        window.setPosition(TerminalPosition.OFFSET_1x1);
    }
    else if(window.getHints().contains(Window.Hint.CENTERED)) {
        int left = (lastKnownScreenSize.getColumns() - expectedDecoratedSize.getColumns()) / 2;
        int top = (lastKnownScreenSize.getRows() - expectedDecoratedSize.getRows()) / 2;
        window.setPosition(new TerminalPosition(left, top));
    }
    else {
        TerminalPosition nextPosition = allWindows.get(allWindows.size() - 1).getPosition().withRelative(2, 1);
        if(nextPosition.getColumn() + expectedDecoratedSize.getColumns() > lastKnownScreenSize.getColumns() ||
                nextPosition.getRow() + expectedDecoratedSize.getRows() > lastKnownScreenSize.getRows()) {
            nextPosition = TerminalPosition.OFFSET_1x1;
        }
        window.setPosition(nextPosition);
    }

    // Finally, run through the usual calculations so the window manager's usual prepare method can have it's say
    prepareWindow(lastKnownScreenSize, window);
}
 
Example 10
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 11
Source File: FileDialog.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onBeforeDrawing() {
    TerminalSize area = getSize();
    String absolutePath = directory.getAbsolutePath();
    int absolutePathLengthInColumns = TerminalTextUtils.getColumnWidth(absolutePath);
    if(area.getColumns() < absolutePathLengthInColumns) {
        absolutePath = absolutePath.substring(absolutePathLengthInColumns - area.getColumns());
        absolutePath = "..." + absolutePath.substring(Math.min(absolutePathLengthInColumns, 3));
    }
    setText(absolutePath);
}
 
Example 12
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 13
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 14
Source File: ProgressBar.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void drawComponent(TextGUIGraphics graphics, ProgressBar component) {
    TerminalSize size = graphics.getSize();
    if(size.getRows() == 0 || size.getColumns() == 0) {
        return;
    }
    ThemeDefinition themeDefinition = component.getThemeDefinition();
    int columnOfProgress = (int)(component.getProgress() * size.getColumns());
    String label = component.getFormattedLabel();
    int labelRow = size.getRows() / 2;

    // Adjust label so it fits inside the component
    int labelWidth = TerminalTextUtils.getColumnWidth(label);

    // Can't be too smart about this, because of CJK characters
    if(labelWidth > size.getColumns()) {
        boolean tail = true;
        while (labelWidth > size.getColumns()) {
            if(tail) {
                label = label.substring(0, label.length() - 1);
            }
            else {
                label = label.substring(1);
            }
            tail = !tail;
            labelWidth = TerminalTextUtils.getColumnWidth(label);
        }
    }
    int labelStartPosition = (size.getColumns() - labelWidth) / 2;

    for(int row = 0; row < size.getRows(); row++) {
        graphics.applyThemeStyle(themeDefinition.getActive());
        for(int column = 0; column < size.getColumns(); column++) {
            if(column == columnOfProgress) {
                graphics.applyThemeStyle(themeDefinition.getNormal());
            }
            if(row == labelRow && column >= labelStartPosition && column < labelStartPosition + labelWidth) {
                char character = label.charAt(TerminalTextUtils.getStringCharacterIndex(label, column - labelStartPosition));
                graphics.setCharacter(column, row, character);
                if(TerminalTextUtils.isCharDoubleWidth(character)) {
                    column++;
                    if(column == columnOfProgress) {
                        graphics.applyThemeStyle(themeDefinition.getNormal());
                    }
                }
            }
            else {
                graphics.setCharacter(column, row, themeDefinition.getCharacter("FILLER", ' '));
            }
        }
    }
}
 
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: 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 17
Source File: InteractableLookupMap.java    From lanterna with GNU Lesser General Public License v3.0 4 votes vote down vote up
private Interactable findNextLeftOrRight(Interactable interactable, boolean isRight) {
    int directionTerm = isRight ? 1 : -1;
    TerminalPosition startPosition = interactable.getCursorLocation();
    if(startPosition == null) {
        // If the currently active interactable component is not showing the cursor, use the top-left position
        // instead if we're going left, or the top-right position if we're going right
        if(isRight) {
            startPosition = new TerminalPosition(interactable.getSize().getColumns() - 1, 0);
        }
        else {
            startPosition = TerminalPosition.TOP_LEFT_CORNER;
        }
    }
    else {
        //Adjust position so that it's on the left-most side if we're going left or right-most side if we're going
        //right. Otherwise the lookup might product odd results in certain cases
        if(isRight) {
            startPosition = startPosition.withColumn(interactable.getSize().getColumns() - 1);
        }
        else {
            startPosition = startPosition.withColumn(0);
        }
    }
    startPosition = interactable.toBasePane(startPosition);
    if(startPosition == null) {
        // The structure has changed, our interactable is no longer inside the base pane!
        return null;
    }
    Set<Interactable> disqualified = getDisqualifiedInteractables(startPosition, false);
    TerminalSize size = getSize();
    int maxShiftUp = interactable.toBasePane(TerminalPosition.TOP_LEFT_CORNER).getRow();
    maxShiftUp = Math.max(maxShiftUp, 0);
    int maxShiftDown = interactable.toBasePane(new TerminalPosition(0, interactable.getSize().getRows() - 1)).getRow();
    maxShiftDown = Math.min(maxShiftDown, size.getRows() - 1);
    int maxShift = Math.max(startPosition.getRow() - maxShiftUp, maxShiftDown - startPosition.getRow());
    for(int searchColumn = startPosition.getColumn() + directionTerm;
        searchColumn >= 0 && searchColumn < size.getColumns();
        searchColumn += directionTerm) {

        for(int yShift = 0; yShift <= maxShift; yShift++) {
            for(int modifier: new int[] { 1, -1 }) {
                if(yShift == 0 && modifier == -1) {
                    break;
                }
                int searchRow = startPosition.getRow() + (yShift * modifier);
                if(searchRow < maxShiftUp || searchRow > maxShiftDown) {
                    continue;
                }
                int index = lookupMap[searchRow][searchColumn];
                if (index != -1 && !disqualified.contains(interactables.get(index))) {
                    return interactables.get(index);
                }
            }
        }
    }
    return null;
}
 
Example 18
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 19
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 20
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();
}