Search in sources :

Example 1 with TextGraphics

use of com.googlecode.lanterna.graphics.TextGraphics in project java-docs-samples by GoogleCloudPlatform.

the class MqttCommandsDemo method startGui.

public static void startGui(Screen screen, TextColor theColor) throws IOException {
    try {
        /*
      You can use the DefaultTerminalFactory to create a Screen, this will generally give you the
      TerminalScreen implementation that is probably what you want to use. Please see
      VirtualScreen for more details on a separate implementation that allows you to create a
      terminal surface that is bigger than the physical size of the terminal emulator the software
      is running in. Just to demonstrate that a Screen sits on top of a Terminal,
      we are going to create one manually instead of using DefaultTerminalFactory.
       */
        /*
      Screens will only work in private mode and while you can call methods to mutate its state,
      before you can make any of these changes visible, you'll need to call startScreen()
      which will prepare and setup the terminal.
       */
        screen.startScreen();
        System.out.println("Starting the terminal...");
        /*
      Let's turn off the cursor for this tutorial
       */
        screen.setCursorPosition(null);
        /*
      Now let's draw some random content in the screen buffer
       */
        TerminalSize terminalSize = screen.getTerminalSize();
        for (int column = 0; column < terminalSize.getColumns(); column++) {
            for (int row = 0; row < terminalSize.getRows(); row++) {
                screen.setCharacter(column, row, new TextCharacter(' ', TextColor.ANSI.DEFAULT, // This will pick a random background color
                theColor));
            }
        }
        /*
      So at this point, we've only modified the back buffer in the screen, nothing is visible yet.
      In order to move the content from the back buffer to the front buffer and refresh the
      screen, we need to call refresh()
       */
        screen.refresh();
        System.out.println("Starting the terminal...");
        /*
      Ok, now we loop and keep modifying the screen until the user exits by pressing escape on
      the keyboard or the input stream is closed. When using the Swing/AWT bundled emulator,
      if the user closes the window this will result in an EOF KeyStroke.
       */
        while (true) {
            KeyStroke keyStroke = screen.pollInput();
            if (keyStroke != null && (keyStroke.getKeyType() == KeyType.Escape || keyStroke.getKeyType() == KeyType.EOF)) {
                break;
            }
            /*
        Screens will automatically listen and record size changes, but you have to let the Screen
        know when is a good time to update its internal buffers. Usually you should do this at the
        start of your "drawing" loop, if you have one. This ensures that the dimensions of the
        buffers stays constant and doesn't change while you are drawing content. The method
        doReizeIfNecessary() will check if the terminal has been resized since last time it
        was called (or since the screen was created if this is the first time calling) and
        update the buffer dimensions accordingly. It returns null if the terminal
        has not changed size since last time.
         */
            TerminalSize newSize = screen.doResizeIfNecessary();
            if (newSize != null) {
                terminalSize = newSize;
            }
            /*
        Just like with Terminal, it's probably easier to draw using TextGraphics.
        Let's do that to put a little box with information on the size of the terminal window
         */
            String sizeLabel = "Terminal Size: " + terminalSize;
            TerminalPosition labelBoxTopLeft = new TerminalPosition(1, 1);
            TerminalSize labelBoxSize = new TerminalSize(sizeLabel.length() + 2, 3);
            TerminalPosition labelBoxTopRightCorner = labelBoxTopLeft.withRelativeColumn(labelBoxSize.getColumns() - 1);
            TextGraphics textGraphics = screen.newTextGraphics();
            // This isn't really needed as we are overwriting everything below anyway, but just for
            // demonstrative purpose
            textGraphics.fillRectangle(labelBoxTopLeft, labelBoxSize, ' ');
            /*
        Draw horizontal lines, first upper then lower
         */
            textGraphics.drawLine(labelBoxTopLeft.withRelativeColumn(1), labelBoxTopLeft.withRelativeColumn(labelBoxSize.getColumns() - 2), Symbols.DOUBLE_LINE_HORIZONTAL);
            textGraphics.drawLine(labelBoxTopLeft.withRelativeRow(2).withRelativeColumn(1), labelBoxTopLeft.withRelativeRow(2).withRelativeColumn(labelBoxSize.getColumns() - 2), Symbols.DOUBLE_LINE_HORIZONTAL);
            /*
        Manually do the edges and (since it's only one) the vertical lines,
        first on the left then on the right
         */
            textGraphics.setCharacter(labelBoxTopLeft, Symbols.DOUBLE_LINE_TOP_LEFT_CORNER);
            textGraphics.setCharacter(labelBoxTopLeft.withRelativeRow(1), Symbols.DOUBLE_LINE_VERTICAL);
            textGraphics.setCharacter(labelBoxTopLeft.withRelativeRow(2), Symbols.DOUBLE_LINE_BOTTOM_LEFT_CORNER);
            textGraphics.setCharacter(labelBoxTopRightCorner, Symbols.DOUBLE_LINE_TOP_RIGHT_CORNER);
            textGraphics.setCharacter(labelBoxTopRightCorner.withRelativeRow(1), Symbols.DOUBLE_LINE_VERTICAL);
            textGraphics.setCharacter(labelBoxTopRightCorner.withRelativeRow(2), Symbols.DOUBLE_LINE_BOTTOM_RIGHT_CORNER);
            /*
        Finally put the text inside the box
         */
            textGraphics.putString(labelBoxTopLeft.withRelative(1, 1), sizeLabel);
            /*
        Ok, we are done and can display the change. Let's also be nice and allow the OS
        to schedule other threads so we don't clog up the core completely.
         */
            screen.refresh();
            Thread.yield();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (screen != null) {
            try {
                /*
          The close() call here will restore the terminal by exiting from private mode which
          was done in the call to startScreen()
           */
                screen.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    screen.stopScreen();
}
Also used : TextCharacter(com.googlecode.lanterna.TextCharacter) TextGraphics(com.googlecode.lanterna.graphics.TextGraphics) KeyStroke(com.googlecode.lanterna.input.KeyStroke) TerminalSize(com.googlecode.lanterna.TerminalSize) TerminalPosition(com.googlecode.lanterna.TerminalPosition) IOException(java.io.IOException)

Example 2 with TextGraphics

use of com.googlecode.lanterna.graphics.TextGraphics in project claro-lang by JasonSteving99.

the class ReplTerminal method runTerminal.

public void runTerminal() {
    DefaultTerminalFactory defaultTerminalFactory = new DefaultTerminalFactory();
    UnixTerminal terminal = null;
    try {
        terminal = new UnixTerminal(System.in, System.out, StandardCharsets.UTF_8, CtrlCBehaviour.CTRL_C_KILLS_APPLICATION);
        terminal.clearScreen();
        terminal.setCursorVisible(true);
        final TextGraphics textGraphics = terminal.newTextGraphics();
        // Change to a background/foreground color combo that pops more.
        textGraphics.setForegroundColor(TextColor.ANSI.WHITE);
        textGraphics.setBackgroundColor(TextColor.ANSI.BLACK);
        textGraphics.putString(2, 0, String.format("ClaroLang %s - Press ESC/Ctr-C to exit", claroVersion), SGR.BOLD);
        // Change back to the default background/foreground colors.
        textGraphics.setForegroundColor(TextColor.ANSI.DEFAULT);
        textGraphics.setBackgroundColor(TextColor.ANSI.DEFAULT);
        final String PROMPT = ">>> ";
        textGraphics.putString(0, 1, PROMPT, SGR.BOLD);
        // Need to flush for changes to become visible.
        terminal.flush();
        // Setup the control vars that'll track the current user position and state as they use the terminal.
        StringBuilder currInstruction = new StringBuilder();
        Stack<String> prevInstructions = new Stack<>();
        int instructionIndex = 0;
        int currLine = 1;
        int currPromptCol = 0;
        KeyStroke keyStroke = terminal.readInput();
        while (keyStroke.getKeyType() != KeyType.Escape) {
            switch(keyStroke.getKeyType()) {
                case Character:
                    Character currKeyStrokeCharacter = keyStroke.getCharacter();
                    currInstruction.insert(currPromptCol, keyStroke.getCharacter().charValue());
                    currPromptCol++;
                    break;
                case ArrowUp:
                    if (instructionIndex == 0) {
                        terminal.bell();
                    } else {
                        textGraphics.putString(0, currLine, PROMPT + getSpacesStringOfLength(currInstruction.length()));
                        currInstruction.delete(0, currInstruction.length());
                        currInstruction.append(prevInstructions.elementAt(--instructionIndex));
                        currPromptCol = currInstruction.length();
                    }
                    break;
                case ArrowDown:
                    if (instructionIndex == prevInstructions.size() - 1) {
                        // Moving down after the last instruction, should just clear everything.
                        textGraphics.putString(0, currLine, PROMPT + getSpacesStringOfLength(currInstruction.length()));
                        currInstruction.delete(0, currInstruction.length());
                        instructionIndex++;
                        currPromptCol = 0;
                    } else if (instructionIndex >= prevInstructions.size()) {
                        terminal.bell();
                    } else {
                        textGraphics.putString(0, currLine, PROMPT + getSpacesStringOfLength(currInstruction.length()));
                        currInstruction.delete(0, currInstruction.length());
                        currInstruction.append(prevInstructions.elementAt(++instructionIndex));
                        currPromptCol = currInstruction.length();
                    }
                    break;
                case ArrowRight:
                    if (currPromptCol < currInstruction.length()) {
                        currPromptCol++;
                    } else {
                        terminal.bell();
                    }
                    break;
                case ArrowLeft:
                    if (currPromptCol > 0) {
                        currPromptCol--;
                    } else {
                        terminal.bell();
                    }
                    break;
                case Backspace:
                    if (currPromptCol > 0) {
                        // Overwrite the buffer so that after modifying the currInstruction, the terminal will show the correctly
                        // edited instruction.
                        textGraphics.putString(0, currLine, getSpacesStringOfLength(PROMPT.length() + currInstruction.length()));
                        currInstruction.deleteCharAt(currPromptCol - 1);
                        currPromptCol--;
                    } else {
                        terminal.bell();
                    }
                    break;
                case Enter:
                    if (currInstruction.length() > 0) {
                        prevInstructions.push(currInstruction.toString());
                        instructionIndex = prevInstructions.size();
                        currInstruction.delete(0, currInstruction.length());
                        // Setup the cursor for potential output from inputHandler.
                        if (++currLine >= terminal.getTerminalSize().getRows()) {
                            terminal.scrollLines(0, currLine - 1, 1);
                        }
                        terminal.setCursorPosition(0, currLine);
                        inputHandler.apply(prevInstructions.peek());
                        currLine = terminal.getCursorPosition().getRow();
                    } else {
                        currLine++;
                    }
                    if (currLine >= terminal.getTerminalSize().getRows()) {
                        /*
               Note that currLine is potentially pointing ahead of the last row shown in the terminal
               currently because the inputHandler may have output multiple lines. In this case, this
               scrollLines method is being told to scroll lines that are currently below the fold, but
               it appears that it handles this well.
              */
                        terminal.scrollLines(0, currLine, 1);
                    }
                    currPromptCol = 0;
                    break;
            }
            // Print the currInstruction in two parts to leave the cursor exactly where the user expects it.
            textGraphics.putString(0, currLine, PROMPT + currInstruction.toString(), SGR.BOLD);
            textGraphics.putString(0, currLine, PROMPT + currInstruction.substring(0, currPromptCol));
            terminal.flush();
            keyStroke = terminal.readInput();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (terminal != null) {
            try {
                terminal.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory) UnixTerminal(com.googlecode.lanterna.terminal.ansi.UnixTerminal) TextGraphics(com.googlecode.lanterna.graphics.TextGraphics) KeyStroke(com.googlecode.lanterna.input.KeyStroke) IOException(java.io.IOException) Stack(java.util.Stack)

Example 3 with TextGraphics

use of com.googlecode.lanterna.graphics.TextGraphics in project security-lib by ncsa.

the class GUIDemo method mytest.

protected static void mytest() throws IOException {
    // Note UnixTerminal is supported BUT will freee the IDE because of
    // how it uses standard out. Write everything letting Lanterna decide
    // what works then switch when running in xterm.
    // Next three are required to start pretty much anything
    DefaultTerminalFactory factory = new DefaultTerminalFactory();
    // All this to set the background color of the terminal...
    TerminalEmulatorPalette myPallette = new TerminalEmulatorPalette(// sets default
    Color.WHITE, // sets default Bright
    Color.RED, // sets background. This is the only reason for this constructor
    Color.BLUE, Color.black, Color.BLACK, Color.red, Color.RED, Color.green, Color.GREEN, Color.yellow, Color.YELLOW, Color.blue, Color.BLUE, Color.magenta, Color.MAGENTA, Color.cyan, Color.CYAN, Color.white, Color.WHITE);
    // TerminalEmulatorPalette palette = new TerminalEmulatorPalette()
    TerminalEmulatorColorConfiguration colorConfig = TerminalEmulatorColorConfiguration.newInstance(myPallette);
    factory.setTerminalEmulatorColorConfiguration(colorConfig);
    Terminal terminal = factory.createTerminal();
    System.out.println("terminal is " + terminal.getClass().getSimpleName());
    Screen screen = new TerminalScreen(terminal);
    // sets up a resize listener in case the user changes the size.
    /*      terminal.addResizeListener((terminal1, newSize) -> {
                  // Be careful here though, this is likely running on a separate thread. Lanterna is threadsafe in
                  // a best-effort way so while it shouldn't blow up if you call terminal methods on multiple threads,
                  // it might have unexpected behavior if you don't do any external synchronization
                  textGraphics.drawLine(5, 3, newSize.getColumns() - 1, 3, ' ');
                  textGraphics.putString(5, 3, "Terminal Size: ", SGR.BOLD);
                  textGraphics.putString(5 + "Terminal Size: ".length(), 3, newSize.toString());
                  try {
                      terminal1.flush();
                  } catch (IOException e) {
                      // Not much we can do here
                      throw new RuntimeException(e);
                  }
              });*/
    TextGraphics textGraphics = screen.newTextGraphics();
    // textGraphics.setForegroundColor(TextColor.ANSI.YELLOW);
    screen.startScreen();
    // clear out any cruft in object properly.
    screen.refresh();
    // textGraphics.
    // Only one of these should be uncommented at any time since they are separate demos.
    // showStuff(textGraphics);
    // terminal.flush();
    // helloWorld(screen);
    // userInput2(terminal, screen, textGraphics);
    // testBox(screen);
    terminalInput(terminal, screen, textGraphics);
    screen.stopScreen();
}
Also used : TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory) TerminalEmulatorColorConfiguration(com.googlecode.lanterna.terminal.swing.TerminalEmulatorColorConfiguration) Screen(com.googlecode.lanterna.screen.Screen) TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) TextGraphics(com.googlecode.lanterna.graphics.TextGraphics) TerminalEmulatorPalette(com.googlecode.lanterna.terminal.swing.TerminalEmulatorPalette) Terminal(com.googlecode.lanterna.terminal.Terminal)

Aggregations

TextGraphics (com.googlecode.lanterna.graphics.TextGraphics)3 KeyStroke (com.googlecode.lanterna.input.KeyStroke)2 DefaultTerminalFactory (com.googlecode.lanterna.terminal.DefaultTerminalFactory)2 IOException (java.io.IOException)2 TerminalPosition (com.googlecode.lanterna.TerminalPosition)1 TerminalSize (com.googlecode.lanterna.TerminalSize)1 TextCharacter (com.googlecode.lanterna.TextCharacter)1 Screen (com.googlecode.lanterna.screen.Screen)1 TerminalScreen (com.googlecode.lanterna.screen.TerminalScreen)1 Terminal (com.googlecode.lanterna.terminal.Terminal)1 UnixTerminal (com.googlecode.lanterna.terminal.ansi.UnixTerminal)1 TerminalEmulatorColorConfiguration (com.googlecode.lanterna.terminal.swing.TerminalEmulatorColorConfiguration)1 TerminalEmulatorPalette (com.googlecode.lanterna.terminal.swing.TerminalEmulatorPalette)1 Stack (java.util.Stack)1