Search in sources :

Example 1 with Screen

use of com.googlecode.lanterna.screen.Screen 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 Screen

use of com.googlecode.lanterna.screen.Screen 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 3 with Screen

use of com.googlecode.lanterna.screen.Screen 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 4 with Screen

use of com.googlecode.lanterna.screen.Screen in project nzyme by lennartkoopmann.

the class TextGUIHID method initializeGUI.

private void initializeGUI() throws IOException {
    Terminal terminal = new DefaultTerminalFactory().setInitialTerminalSize(new TerminalSize(COLS, ROWS)).createTerminal();
    Screen screen = new TerminalScreen(terminal);
    screen.startScreen();
    BasicWindow window = new BasicWindow();
    Panel mainPanel = new Panel();
    // Top status.
    Panel statusPanel = new Panel(new GridLayout(8));
    statusPanel.addComponent(labelConnection.withBorder(Borders.singleLine("CONN")));
    statusPanel.addComponent(labelSignal.withBorder(Borders.singleLine("SIG")));
    statusPanel.addComponent(labelTrackerStatus.withBorder(Borders.singleLine("LINK DVC")));
    statusPanel.addComponent(labelWiFiStatus.withBorder(Borders.singleLine("802.11")));
    statusPanel.addComponent(labelWiFiChannels.withBorder(Borders.singleLine("CHANNEL")));
    statusPanel.addComponent(labelDesignator.withBorder(Borders.singleLine("DSGNTR")));
    statusPanel.addComponent(new EmptySpace(new TerminalSize(3, 3)));
    statusPanel.addComponent(labelTime.withBorder(Borders.singleLine("CLOCK")));
    mainPanel.addComponent(statusPanel);
    // Task.
    Panel taskPanel = new Panel(new GridLayout(6));
    taskPanel.addComponent(labelTask.withBorder(Borders.singleLine("TASK")));
    taskPanel.addComponent(labelBandit.withBorder(Borders.singleLine("BANDIT TARGET")));
    taskPanel.addComponent(labelTrack.withBorder(Borders.singleLine("TRACK")));
    taskPanel.addComponent(labelTrackSignal.withBorder(Borders.singleLine("TRACK SIG")));
    taskPanel.addComponent(labelTrackFrames.withBorder(Borders.singleLine("FRAMES")));
    taskPanel.addComponent(labelTrackContact.withBorder(Borders.singleLine("LAST CONTACT")));
    mainPanel.addComponent(taskPanel);
    // Events
    Panel eventsPanel = new Panel(new GridLayout(1));
    eventsPanel.addComponent(eventsTable.withBorder(Borders.singleLine("EVENTS")));
    eventsTable.setCellSelection(false);
    eventsTable.setSelectedRow(-1);
    eventsTable.setVisibleRows(5);
    eventsTable.setSize(new TerminalSize(COLS, 8));
    event(nzyme.getNodeID(), "Initialized tracker.");
    mainPanel.addComponent(eventsPanel);
    window.setComponent(mainPanel);
    window.setTheme(SimpleTheme.makeTheme(true, TextColor.ANSI.WHITE, TextColor.ANSI.BLACK, TextColor.ANSI.BLACK, TextColor.ANSI.BLUE, TextColor.ANSI.WHITE, TextColor.ANSI.RED, TextColor.ANSI.RED));
    window.setHints(Arrays.asList(Window.Hint.CENTERED, Window.Hint.NO_DECORATIONS));
    MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLACK));
    gui.addWindowAndWait(window);
}
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) TerminalSize(com.googlecode.lanterna.TerminalSize) Terminal(com.googlecode.lanterna.terminal.Terminal)

Example 5 with Screen

use of com.googlecode.lanterna.screen.Screen in project security-lib by ncsa.

the class FullScreenTextGUITest method main.

public static void main(String[] args) throws IOException, InterruptedException {
    DefaultTerminalFactory factory = new DefaultTerminalFactory();
    Terminal terminal = factory.createTerminal();
    // Screen screen = new TestTerminalFactory(args).setInitialTerminalSize(new TerminalSize(80, 25)).createScreen();
    Screen screen = new TerminalScreen(terminal);
    screen.startScreen();
    final AtomicBoolean stop = new AtomicBoolean(false);
    MultiWindowTextGUI textGUI = new MultiWindowTextGUI(screen);
    textGUI.addListener((textGUI1, key) -> {
        if (key.getKeyType() == KeyType.Escape) {
            stop.set(true);
            return true;
        }
        return false;
    });
    try {
        textGUI.getBackgroundPane().setComponent(new BIOS());
        while (!stop.get()) {
            if (!textGUI.getGUIThread().processEventsAndUpdate()) {
                Thread.sleep(1);
            }
        }
    } catch (EOFException ignore) {
    // Terminal closed                               Left
    } finally {
        screen.stopScreen();
    }
}
Also used : TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DefaultTerminalFactory(com.googlecode.lanterna.terminal.DefaultTerminalFactory) Screen(com.googlecode.lanterna.screen.Screen) TerminalScreen(com.googlecode.lanterna.screen.TerminalScreen) EOFException(java.io.EOFException) Terminal(com.googlecode.lanterna.terminal.Terminal)

Aggregations

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