Search in sources :

Example 1 with DefaultTerminalFactory

use of com.googlecode.lanterna.terminal.DefaultTerminalFactory in project jbang-catalog by quintesse.

the class lanterna method main.

public static void main(String[] args) {
    DefaultTerminalFactory terminalFactory = new DefaultTerminalFactory().setMouseCaptureMode(MouseCaptureMode.CLICK_RELEASE);
    try (Screen screen = terminalFactory.createScreen()) {
        screen.startScreen();
        List<String> timezonesAsStrings = new ArrayList<>(Arrays.asList(TimeZone.getAvailableIDs()));
        final WindowBasedTextGUI textGUI = new MultiWindowTextGUI(screen);
        final Window window = new BasicWindow("My Root Window");
        Panel contentPanel = new Panel().setLayoutManager(new GridLayout(2).setHorizontalSpacing(3)).addComponent(new Label("This is a label that spans two columns").setLayoutData(GridLayout.createLayoutData(// Horizontal alignment in the grid cell if the cell
        GridLayout.Alignment.BEGINNING, // Vertical alignment in the grid cell if the cell
        GridLayout.Alignment.BEGINNING, // Give the component extra horizontal space if available
        true, // Give the component extra vertical space if available
        false, // Horizontal span
        2, // Vertical span
        1))).addComponent(new Label("Text Box (aligned)")).addComponent(new TextBox().setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.BEGINNING, GridLayout.Alignment.CENTER))).addComponent(new Label("Password Box (right aligned)")).addComponent(new TextBox().setMask('*').setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.END, GridLayout.Alignment.CENTER))).addComponent(new Label("Read-only Combo Box (forced size)")).addComponent(new ComboBox<>(timezonesAsStrings).setReadOnly(true).setPreferredSize(new TerminalSize(20, 1))).addComponent(new Label("Editable Combo Box (filled)")).addComponent(new ComboBox<>("Item #1", "Item #2", "Item #3", "Item #4").setReadOnly(false).setLayoutData(GridLayout.createHorizontallyFilledLayoutData(1))).addComponent(new Label("Button (centered)")).addComponent(new Button("Button", () -> MessageDialog.showMessageDialog(textGUI, "MessageBox", "This is a message box", MessageDialogButton.OK)).setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.CENTER, GridLayout.Alignment.CENTER))).addComponent(new EmptySpace().setLayoutData(GridLayout.createHorizontallyFilledLayoutData(2))).addComponent(new Separator(Direction.HORIZONTAL).setLayoutData(GridLayout.createHorizontallyFilledLayoutData(2))).addComponent(new Button("Close", window::close).setLayoutData(GridLayout.createHorizontallyEndAlignedLayoutData(2)));
        window.setComponent(contentPanel);
        window.addWindowListener(new WindowListenerAdapter() {

            public void onUnhandledInput(Window basePane, KeyStroke keyStroke, AtomicBoolean hasBeenHandled) {
                if (keyStroke.getKeyType() == KeyType.Escape) {
                    window.close();
                }
            }
        });
        textGUI.addWindowAndWait(window);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : Screen(com.googlecode.lanterna.screen.Screen) ArrayList(java.util.ArrayList) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory) MessageDialogButton(com.googlecode.lanterna.gui2.dialogs.MessageDialogButton) KeyStroke(com.googlecode.lanterna.input.KeyStroke) TerminalSize(com.googlecode.lanterna.TerminalSize)

Example 2 with DefaultTerminalFactory

use of com.googlecode.lanterna.terminal.DefaultTerminalFactory in project security-lib by ncsa.

the class QDLGUIWorkspace method setupTerminal.

protected void setupTerminal() throws IOException {
    DefaultTerminalFactory factory = new DefaultTerminalFactory();
    terminal = factory.createTerminal();
    screen = new TerminalScreen(terminal);
    textGraphics = screen.newTextGraphics();
    screen.startScreen();
    screen.refresh();
    // String is of form # RGB where each color is a hex number 0 - 255 aka x0 - xFF
    // terminal.setForegroundColor(TextColor.RGB.Factory.fromString("#0000FF"));
    terminal.setForegroundColor(TextColor.ANSI.WHITE);
    terminal.setCursorVisible(true);
    terminal.setCursorPosition(0, 0);
    terminal.exitPrivateMode();
    terminal.enableSGR(SGR.BOLD);
    // terminal.flush();
    ioInterface = new LanternaIO(terminal, screen);
}
Also used : TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory)

Example 3 with DefaultTerminalFactory

use of com.googlecode.lanterna.terminal.DefaultTerminalFactory in project java-docs-samples by GoogleCloudPlatform.

the class ManagerIT method testTerminal.

@Test
public void testTerminal() throws Exception {
    // Set up
    Screen screen = null;
    DefaultTerminalFactory defaultTerminalFactory = new DefaultTerminalFactory();
    Terminal terminal = defaultTerminalFactory.createTerminal();
    screen = new TerminalScreen(terminal);
    Screen finalScreen = screen;
    Thread deviceThread = new Thread(() -> {
        try {
            MqttCommandsDemo.startGui(finalScreen, new TextColor.RGB(255, 255, 255));
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    deviceThread.join(3000);
    System.out.println(terminal.getTerminalSize().toString());
    // Assertions
    Assert.assertTrue(terminal.getTerminalSize().toString().contains("x"));
    Assert.assertTrue(terminal.getTerminalSize().toString().contains("{"));
    Assert.assertTrue(terminal.getTerminalSize().toString().contains("}"));
}
Also used : TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory) Screen(com.googlecode.lanterna.screen.Screen) TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) TextColor(com.googlecode.lanterna.TextColor) IOException(java.io.IOException) Terminal(com.googlecode.lanterna.terminal.Terminal) Test(org.junit.Test)

Example 4 with DefaultTerminalFactory

use of com.googlecode.lanterna.terminal.DefaultTerminalFactory in project java-docs-samples by GoogleCloudPlatform.

the class MqttCommandsDemo method mqttDeviceDemo.

public static void mqttDeviceDemo(String projectId, String cloudRegion, String registryId, String deviceId, String privateKeyFile, String algorithm, String mqttBridgeHostname, short mqttBridgePort, String messageType, int waitTime) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, MqttException, InterruptedException {
    // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
    // connections are accepted. For server authentication, the JVM's root certificates
    // are used.
    final String mqttServerAddress = String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);
    // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
    // Google Cloud IoT Core, it must be in the format below.
    final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryId, deviceId);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
    // explictly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    Properties sslProps = new Properties();
    sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
    connectOptions.setSSLProperties(sslProps);
    // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
    // Paho client library to send the password field. The password field is used to transmit a JWT
    // to authorize the device.
    connectOptions.setUserName("unused");
    DateTime iat = new DateTime();
    if (algorithm.equals("RS256")) {
        connectOptions.setPassword(createJwtRsa(projectId, privateKeyFile).toCharArray());
    } else if (algorithm.equals("ES256")) {
        connectOptions.setPassword(createJwtEs(projectId, privateKeyFile).toCharArray());
    } else {
        throw new IllegalArgumentException("Invalid algorithm " + algorithm + ". Should be one of 'RS256' or 'ES256'.");
    }
    // [START iot_mqtt_publish]
    // Create a client, and connect to the Google MQTT bridge.
    MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
    // Both connect and publish operations may fail. If they do, allow retries but with an
    // exponential backoff time period.
    long initialConnectIntervalMillis = 500L;
    long maxConnectIntervalMillis = 6000L;
    long maxConnectRetryTimeElapsedMillis = 900000L;
    float intervalMultiplier = 1.5f;
    long retryIntervalMs = initialConnectIntervalMillis;
    long totalRetryTimeMs = 0;
    while (!client.isConnected() && totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) {
        try {
            client.connect(connectOptions);
        } catch (MqttException e) {
            int reason = e.getReasonCode();
            // If the connection is lost or if the server cannot be connected, allow retries, but with
            // exponential backoff.
            System.out.println("An error occurred: " + e.getMessage());
            if (reason == MqttException.REASON_CODE_CONNECTION_LOST || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
                System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
                Thread.sleep(retryIntervalMs);
                totalRetryTimeMs += retryIntervalMs;
                retryIntervalMs *= intervalMultiplier;
                if (retryIntervalMs > maxConnectIntervalMillis) {
                    retryIntervalMs = maxConnectIntervalMillis;
                }
            } else {
                throw e;
            }
        }
    }
    // Publish to the events or state topic based on the flag.
    String subTopic = messageType.equals("event") ? "events" : messageType;
    // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
    // required to be in the format below. Note that this is not the same as the device registry's
    // Cloud Pub/Sub topic.
    String mqttTopic = String.format("/devices/%s/%s", deviceId, subTopic);
    DefaultTerminalFactory defaultTerminalFactory = new DefaultTerminalFactory();
    Screen screen = null;
    Terminal terminal = defaultTerminalFactory.createTerminal();
    screen = new TerminalScreen(terminal);
    attachCallback(client, deviceId, screen);
    // Wait for commands to arrive for about two minutes.
    for (int i = 1; i <= waitTime; ++i) {
        System.out.print(".");
        Thread.sleep(1000);
    }
    System.out.println("");
    // Disconnect the client if still connected, and finish the run.
    if (client.isConnected()) {
        client.disconnect();
    }
    System.out.println("Finished loop successfully. Goodbye!");
    client.close();
    System.exit(0);
// [END iot_mqtt_publish]
}
Also used : MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) Screen(com.googlecode.lanterna.screen.Screen) TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) Properties(java.util.Properties) Terminal(com.googlecode.lanterna.terminal.Terminal) DateTime(org.joda.time.DateTime) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttException(org.eclipse.paho.client.mqttv3.MqttException)

Example 5 with DefaultTerminalFactory

use of com.googlecode.lanterna.terminal.DefaultTerminalFactory 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)

Aggregations

DefaultTerminalFactory (com.googlecode.lanterna.terminal.DefaultTerminalFactory)9 TerminalScreen (com.googlecode.lanterna.screen.TerminalScreen)7 Screen (com.googlecode.lanterna.screen.Screen)6 Terminal (com.googlecode.lanterna.terminal.Terminal)5 IOException (java.io.IOException)4 TerminalSize (com.googlecode.lanterna.TerminalSize)2 TextGraphics (com.googlecode.lanterna.graphics.TextGraphics)2 KeyStroke (com.googlecode.lanterna.input.KeyStroke)2 TerminalEmulatorColorConfiguration (com.googlecode.lanterna.terminal.swing.TerminalEmulatorColorConfiguration)2 TerminalEmulatorPalette (com.googlecode.lanterna.terminal.swing.TerminalEmulatorPalette)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 TextColor (com.googlecode.lanterna.TextColor)1 MessageDialogButton (com.googlecode.lanterna.gui2.dialogs.MessageDialogButton)1 VirtualScreen (com.googlecode.lanterna.screen.VirtualScreen)1 UnixTerminal (com.googlecode.lanterna.terminal.ansi.UnixTerminal)1 EOFException (java.io.EOFException)1 ArrayList (java.util.ArrayList)1 Properties (java.util.Properties)1 Stack (java.util.Stack)1 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)1