Interface Terminal

  • All Superinterfaces:
    java.lang.AutoCloseable, java.io.Closeable, java.io.Flushable
    All Known Subinterfaces:
    TerminalExt
    All Known Implementing Classes:
    AbstractPosixTerminal, AbstractTerminal, AbstractWindowsTerminal, DumbTerminal, ExternalTerminal, LineDisciplineTerminal, NativeWinSysTerminal, PosixPtyTerminal, PosixSysTerminal

    public interface Terminal
    extends java.io.Closeable, java.io.Flushable
    A terminal representing a virtual terminal on the computer.

    The Terminal interface is the central abstraction in JLine, providing access to the terminal's capabilities, input/output streams, and control functions. It abstracts the differences between various terminal types and operating systems, allowing applications to work consistently across environments.

    Terminal Capabilities

    Terminals provide access to their capabilities through the getStringCapability(Capability), getBooleanCapability(Capability), and getNumericCapability(Capability) methods. These capabilities represent the terminal's features and are defined in the terminfo database.

    Input and Output

    Terminal input can be read using the reader() method, which returns a non-blocking reader. Output can be written using the writer() method, which returns a print writer. For raw access to the underlying streams, use input() and output().

    Terminal Attributes

    Terminal attributes control the behavior of the terminal, such as echo mode, canonical mode, etc. These can be accessed and modified using getAttributes() and setAttributes(Attributes).

    Signal Handling

    Terminals can handle various signals, such as CTRL+C (INT), CTRL+\ (QUIT), etc. Signal handlers can be registered using handle(Signal, SignalHandler).

    Signal handling allows terminal applications to respond appropriately to these events, such as gracefully terminating when the user presses Ctrl+C, or adjusting the display when the terminal window is resized.

    Example usage:

     Terminal terminal = TerminalBuilder.terminal();
    
     // Handle interrupt signal (Ctrl+C)
     terminal.handle(Signal.INT, signal -> {
         terminal.writer().println("\nInterrupted! Press Enter to exit.");
         terminal.flush();
     });
     

    Mouse Support

    Some terminals support mouse tracking, which can be enabled using trackMouse(MouseTracking). Mouse events can then be read using readMouseEvent().

    Lifecycle

    Terminals should be closed by calling the Closeable.close() method when they are no longer needed in order to restore their original state. Failure to close a terminal may leave the terminal in an inconsistent state.

    Creating Terminals

    Terminals are typically created using the TerminalBuilder class, which provides a fluent API for configuring and creating terminal instances.

    See Also:
    TerminalBuilder, Attributes, Size, Cursor, MouseEvent
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String TYPE_DUMB
      Type identifier for dumb terminals with minimal capabilities.
      static java.lang.String TYPE_DUMB_COLOR
      Type identifier for dumb terminals with basic color support.
    • Method Summary

      All Methods Instance Methods Abstract Methods Default Methods 
      Modifier and Type Method Description
      boolean canPauseResume()
      Whether this terminal supports pause() and resume() calls.
      boolean echo()
      Returns whether the terminal is currently echoing input characters.
      boolean echo​(boolean echo)
      Enables or disables echoing of input characters.
      java.nio.charset.Charset encoding()
      Returns the Charset that should be used to encode characters for input() and output().
      Attributes enterRawMode()
      Puts the terminal into raw mode.
      void flush()
      Flushes any buffered output to the terminal.
      Attributes getAttributes()
      Returns the current terminal attributes.
      boolean getBooleanCapability​(InfoCmp.Capability capability)
      Returns whether the terminal supports the specified boolean capability.
      default Size getBufferSize()
      Retrieve the size of the window buffer.
      Terminal.MouseTracking getCurrentMouseTracking()
      Returns the current mouse tracking mode.
      Cursor getCursorPosition​(java.util.function.IntConsumer discarded)
      Query the terminal to report the cursor position.
      default int getDefaultBackgroundColor()
      Returns the terminal's default background color as an RGB value.
      default int getDefaultForegroundColor()
      Returns the terminal's default foreground color as an RGB value.
      default int getHeight()
      Returns the height (number of rows) of the terminal.
      java.lang.String getName()
      Returns the name of this terminal.
      java.lang.Integer getNumericCapability​(InfoCmp.Capability capability)
      Returns the value of the specified numeric capability for this terminal.
      ColorPalette getPalette()
      Returns the color palette for this terminal.
      Size getSize()
      Retrieve the size of the visible window
      java.lang.String getStringCapability​(InfoCmp.Capability capability)
      Returns the string value of the specified capability for this terminal.
      java.lang.String getType()
      Returns the type of this terminal.
      default int getWidth()
      Returns the width (number of columns) of the terminal.
      Terminal.SignalHandler handle​(Terminal.Signal signal, Terminal.SignalHandler handler)
      Registers a handler for the given Terminal.Signal.
      boolean hasFocusSupport()
      Returns whether the terminal has support for focus tracking.
      boolean hasMouseSupport()
      Returns whether the terminal has support for mouse tracking.
      java.io.InputStream input()
      Retrieve the input stream for this terminal.
      java.io.OutputStream output()
      Retrieve the output stream for this terminal.
      void pause()
      Temporarily stops reading the input stream.
      void pause​(boolean wait)
      Stop reading the input stream and optionally wait for the underlying threads to finish.
      boolean paused()
      Check whether the terminal is currently reading the input stream or not.
      boolean puts​(InfoCmp.Capability capability, java.lang.Object... params)
      Outputs a terminal control string for the specified capability.
      void raise​(Terminal.Signal signal)
      Raises the specified signal, triggering any registered handlers.
      NonBlockingReader reader()
      Retrieve the Reader for this terminal.
      MouseEvent readMouseEvent()
      Read a MouseEvent from the terminal input stream.
      MouseEvent readMouseEvent​(java.lang.String prefix)
      Reads and decodes a mouse event with a specified prefix that has already been consumed.
      MouseEvent readMouseEvent​(java.util.function.IntSupplier reader)
      Reads and decodes a mouse event using the provided input supplier.
      MouseEvent readMouseEvent​(java.util.function.IntSupplier reader, java.lang.String prefix)
      Reads and decodes a mouse event using the provided input supplier with a specified prefix that has already been consumed.
      void resume()
      Resumes reading the input stream after it has been paused.
      void setAttributes​(Attributes attr)
      Sets the terminal attributes to the specified values.
      void setSize​(Size size)
      Sets the size of the terminal.
      default java.nio.charset.Charset stderrEncoding()
      Returns the Charset that should be used to encode characters for standard error.
      default java.nio.charset.Charset stdinEncoding()
      Returns the Charset that should be used to decode characters from standard input (input()).
      default java.nio.charset.Charset stdoutEncoding()
      Returns the Charset that should be used to encode characters for standard output (output()).
      boolean trackFocus​(boolean tracking)
      Enables or disables focus tracking mode.
      boolean trackMouse​(Terminal.MouseTracking tracking)
      Enables or disables mouse tracking with the specified mode.
      java.io.PrintWriter writer()
      Retrieve the Writer for this terminal.
      • Methods inherited from interface java.io.Closeable

        close
    • Field Detail

      • TYPE_DUMB

        static final java.lang.String TYPE_DUMB
        Type identifier for dumb terminals with minimal capabilities.

        A dumb terminal has minimal capabilities and typically does not support cursor movement, colors, or other advanced features. It's often used as a fallback when a more capable terminal is not available.

        See Also:
        Constant Field Values
      • TYPE_DUMB_COLOR

        static final java.lang.String TYPE_DUMB_COLOR
        Type identifier for dumb terminals with basic color support.

        A dumb-color terminal has minimal capabilities like a dumb terminal, but does support basic color output. It still lacks support for cursor movement and other advanced features.

        See Also:
        Constant Field Values
    • Method Detail

      • getName

        java.lang.String getName()
        Returns the name of this terminal.

        The terminal name is typically a descriptive identifier that can be used for logging or debugging purposes. It may reflect the terminal type, connection method, or other distinguishing characteristics.

        Returns:
        the terminal name
      • handle

        Terminal.SignalHandler handle​(Terminal.Signal signal,
                                      Terminal.SignalHandler handler)
        Registers a handler for the given Terminal.Signal.

        This method allows the application to specify custom behavior when a particular signal is raised. The handler's Terminal.SignalHandler.handle(Signal) method will be called whenever the specified signal is raised.

        Note that the JVM does not easily allow catching the Terminal.Signal.QUIT signal (Ctrl+\), which typically causes a thread dump to be displayed. This signal handling is mainly effective when connecting through an SSH socket to a virtual terminal.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Handle window resize events
         terminal.handle(Signal.WINCH, signal -> {
             Size size = terminal.getSize();
             terminal.writer().println("\nTerminal resized to " +
                                      size.getColumns() + "x" + size.getRows());
             terminal.flush();
         });
        
         // Ignore interrupt signal
         terminal.handle(Signal.INT, SignalHandler.SIG_IGN);
         
        Parameters:
        signal - the signal to register a handler for
        handler - the handler to be called when the signal is raised
        Returns:
        the previous signal handler that was registered for this signal
        See Also:
        Terminal.Signal, Terminal.SignalHandler, raise(Signal)
      • reader

        NonBlockingReader reader()
        Retrieve the Reader for this terminal. This is the standard way to read input from this terminal. The reader is non blocking.
        Returns:
        The non blocking reader
      • writer

        java.io.PrintWriter writer()
        Retrieve the Writer for this terminal. This is the standard way to write to this terminal.
        Returns:
        The writer
      • stdinEncoding

        default java.nio.charset.Charset stdinEncoding()
        Returns the Charset that should be used to decode characters from standard input (input()).

        This method returns the encoding specifically for standard input. If no specific stdin encoding was configured, it falls back to the general encoding from encoding().

        Returns:
        The standard input encoding
        See Also:
        encoding()
      • stdoutEncoding

        default java.nio.charset.Charset stdoutEncoding()
        Returns the Charset that should be used to encode characters for standard output (output()).

        This method returns the encoding specifically for standard output. If no specific stdout encoding was configured, it falls back to the general encoding from encoding().

        Returns:
        The standard output encoding
        See Also:
        encoding()
      • stderrEncoding

        default java.nio.charset.Charset stderrEncoding()
        Returns the Charset that should be used to encode characters for standard error.

        This method returns the encoding specifically for standard error. If no specific stderr encoding was configured, it falls back to the general encoding from encoding().

        Returns:
        The standard error encoding
        See Also:
        encoding()
      • input

        java.io.InputStream input()
        Retrieve the input stream for this terminal. In some rare cases, there may be a need to access the terminal input stream directly. In the usual cases, use the reader() instead.
        Returns:
        The input stream
        See Also:
        reader()
      • output

        java.io.OutputStream output()
        Retrieve the output stream for this terminal. In some rare cases, there may be a need to access the terminal output stream directly. In the usual cases, use the writer() instead.
        Returns:
        The output stream
        See Also:
        writer()
      • pause

        void pause()
        Temporarily stops reading the input stream.

        This method pauses the terminal's input processing, which can be useful when transferring control to a subprocess or when the terminal needs to be in a specific state for certain operations. While paused, the terminal will not process input or handle signals that would normally be triggered by special characters in the input stream.

        This method returns immediately without waiting for the terminal to actually pause. To wait until the terminal has fully paused, use pause(boolean) with a value of true.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Pause terminal input processing before running a subprocess
         terminal.pause();
        
         // Run subprocess that takes control of the terminal
         Process process = new ProcessBuilder("vim").inheritIO().start();
         process.waitFor();
        
         // Resume terminal input processing
         terminal.resume();
         
        See Also:
        resume(), pause(boolean), paused(), canPauseResume()
      • pause

        void pause​(boolean wait)
            throws java.lang.InterruptedException
        Stop reading the input stream and optionally wait for the underlying threads to finish.
        Parameters:
        wait - true to wait until the terminal is actually paused
        Throws:
        java.lang.InterruptedException - if the call has been interrupted
      • resume

        void resume()
        Resumes reading the input stream after it has been paused.

        This method restarts the terminal's input processing after it has been temporarily stopped using pause() or pause(boolean). Once resumed, the terminal will continue to process input and handle signals triggered by special characters in the input stream.

        Calling this method when the terminal is not paused has no effect.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Pause terminal input processing
         terminal.pause();
        
         // Perform operations while terminal input is paused...
        
         // Resume terminal input processing
         terminal.resume();
         
        See Also:
        pause(), pause(boolean), paused(), canPauseResume()
      • paused

        boolean paused()
        Check whether the terminal is currently reading the input stream or not. In order to process signal as quickly as possible, the terminal need to read the input stream and buffer it internally so that it can detect specific characters in the input stream (Ctrl+C, Ctrl+D, etc...) and raise the appropriate signals. However, there are some cases where this processing should be disabled, for example when handing the terminal control to a subprocess.
        Returns:
        whether the terminal is currently reading the input stream or not
        See Also:
        pause(), resume()
      • enterRawMode

        Attributes enterRawMode()
        Puts the terminal into raw mode.

        In raw mode, input is available character by character, terminal-generated signals are disabled, and special character processing is disabled. This mode is typically used for full-screen interactive applications like text editors.

        This method modifies the terminal attributes to configure raw mode and returns the original attributes, which can be used to restore the terminal to its previous state.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
         Attributes originalAttributes = terminal.enterRawMode();
        
         // Use terminal in raw mode...
        
         // Restore original attributes when done
         terminal.setAttributes(originalAttributes);
         
        Returns:
        the original terminal attributes before entering raw mode
        See Also:
        setAttributes(Attributes)
      • echo

        boolean echo()
        Returns whether the terminal is currently echoing input characters.

        When echo is enabled, characters typed by the user are automatically displayed on the screen. When echo is disabled, input characters are not displayed, which is useful for password input or other sensitive information.

        Returns:
        true if echo is enabled, false otherwise
        See Also:
        echo(boolean)
      • echo

        boolean echo​(boolean echo)
        Enables or disables echoing of input characters.

        When echo is enabled, characters typed by the user are automatically displayed on the screen. When echo is disabled, input characters are not displayed, which is useful for password input or other sensitive information.

        Example usage for password input:

         Terminal terminal = TerminalBuilder.terminal();
         boolean oldEcho = terminal.echo(false); // Disable echo
         String password = readPassword(terminal);
         terminal.echo(oldEcho); // Restore previous echo state
         
        Parameters:
        echo - true to enable echo, false to disable it
        Returns:
        the previous echo state
      • getAttributes

        Attributes getAttributes()
        Returns the current terminal attributes.

        Terminal attributes control various aspects of terminal behavior, including:

        • Input processing - How input characters are processed (e.g., character mapping, parity checking)
        • Output processing - How output characters are processed (e.g., newline translation)
        • Control settings - Hardware settings like baud rate and character size
        • Local settings - Terminal behavior settings like echo, canonical mode, and signal generation
        • Control characters - Special characters like EOF, interrupt, and erase

        The returned Attributes object is a copy of the terminal's current attributes and can be safely modified without affecting the terminal until it is applied using setAttributes(Attributes). This allows for making multiple changes to the attributes before applying them all at once.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Get current attributes
         Attributes attrs = terminal.getAttributes();
        
         // Modify attributes
         attrs.setLocalFlag(LocalFlag.ECHO, false);      // Disable echo
         attrs.setInputFlag(InputFlag.ICRNL, false);     // Disable CR to NL mapping
         attrs.setControlChar(ControlChar.VMIN, 1);      // Set minimum input to 1 character
         attrs.setControlChar(ControlChar.VTIME, 0);     // Set timeout to 0 deciseconds
        
         // Apply modified attributes
         terminal.setAttributes(attrs);
         
        Returns:
        a copy of the terminal's current attributes
        See Also:
        setAttributes(Attributes), Attributes, enterRawMode()
      • setAttributes

        void setAttributes​(Attributes attr)
        Sets the terminal attributes to the specified values.

        This method applies the specified attributes to the terminal, changing its behavior according to the settings in the Attributes object. The terminal makes a copy of the provided attributes, so further modifications to the attr object will not affect the terminal until this method is called again.

        Terminal attributes control various aspects of terminal behavior, including input and output processing, control settings, local settings, and special control characters. Changing these attributes allows for fine-grained control over how the terminal processes input and output.

        Common attribute modifications include:

        • Disabling echo for password input
        • Enabling/disabling canonical mode for line-by-line or character-by-character input
        • Disabling signal generation for custom handling of Ctrl+C and other control sequences
        • Changing control characters like the interrupt character or end-of-file character

        For convenience, the enterRawMode() method provides a pre-configured set of attributes suitable for full-screen interactive applications.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Save original attributes for later restoration
         Attributes originalAttrs = terminal.getAttributes();
        
         try {
             // Create and configure new attributes
             Attributes attrs = new Attributes(originalAttrs);
             attrs.setLocalFlag(LocalFlag.ECHO, false);      // Disable echo for password input
             attrs.setLocalFlag(LocalFlag.ICANON, false);    // Disable canonical mode
        
             // Apply the new attributes
             terminal.setAttributes(attrs);
        
             // Use terminal with modified attributes...
         } finally {
             // Restore original attributes
             terminal.setAttributes(originalAttrs);
         }
         
        Parameters:
        attr - the attributes to apply to the terminal
        See Also:
        getAttributes(), Attributes, enterRawMode()
      • getSize

        Size getSize()
        Retrieve the size of the visible window
        Returns:
        the visible terminal size
        See Also:
        getBufferSize()
      • setSize

        void setSize​(Size size)
        Sets the size of the terminal.

        This method attempts to resize the terminal to the specified dimensions. Note that not all terminals support resizing, and the actual size after this operation may differ from the requested size depending on terminal capabilities and constraints.

        For virtual terminals or terminal emulators, this may update the internal size representation. For physical terminals, this may send appropriate escape sequences to adjust the viewable area.

        Parameters:
        size - the new terminal size (columns and rows)
        See Also:
        getSize()
      • getWidth

        default int getWidth()
        Returns the width (number of columns) of the terminal.

        This is a convenience method equivalent to getSize().getColumns().

        Returns:
        the number of columns in the terminal
        See Also:
        getSize()
      • getHeight

        default int getHeight()
        Returns the height (number of rows) of the terminal.

        This is a convenience method equivalent to getSize().getRows().

        Returns:
        the number of rows in the terminal
        See Also:
        getSize()
      • getBufferSize

        default Size getBufferSize()
        Retrieve the size of the window buffer. Some terminals can be configured to have a buffer size larger than the visible window size and provide scroll bars. In such cases, this method should attempt to return the size of the whole buffer. The getBufferSize() method can be used to avoid wrapping when using the terminal in a line editing mode, while the getSize() method should be used when using full screen mode.
        Returns:
        the terminal buffer size
        See Also:
        getSize()
      • flush

        void flush()
        Flushes any buffered output to the terminal.

        Terminal implementations may buffer output for efficiency. This method ensures that any buffered data is written to the terminal immediately. It's important to call this method when immediate display of output is required, such as when prompting for user input or updating status information.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
         terminal.writer().print("Enter your name: ");
         terminal.flush(); // Ensure the prompt is displayed before reading input
         String name = terminal.reader().readLine();
         
        Specified by:
        flush in interface java.io.Flushable
      • getType

        java.lang.String getType()
        Returns the type of this terminal.

        The terminal type is a string identifier that describes the terminal's capabilities and behavior. Common terminal types include "xterm", "vt100", "ansi", and "dumb". This type is often used to look up terminal capabilities in the terminfo database.

        Special terminal types include:

        • TYPE_DUMB - A terminal with minimal capabilities, typically not supporting cursor movement or colors
        • TYPE_DUMB_COLOR - A dumb terminal that supports basic color output
        Returns:
        the terminal type identifier
        See Also:
        TYPE_DUMB, TYPE_DUMB_COLOR
      • puts

        boolean puts​(InfoCmp.Capability capability,
                     java.lang.Object... params)
        Outputs a terminal control string for the specified capability.

        This method formats and outputs a control sequence for the specified terminal capability, with the given parameters. It's used to perform terminal operations such as cursor movement, screen clearing, color changes, and other terminal-specific functions.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Clear the screen
         terminal.puts(Capability.clear_screen);
        
         // Move cursor to position (10, 20)
         terminal.puts(Capability.cursor_address, 20, 10);
        
         // Set foreground color to red
         terminal.puts(Capability.set_a_foreground, 1);
         
        Parameters:
        capability - the terminal capability to use
        params - the parameters for the capability
        Returns:
        true if the capability is supported and was output, false otherwise
        See Also:
        getStringCapability(Capability)
      • getBooleanCapability

        boolean getBooleanCapability​(InfoCmp.Capability capability)
        Returns whether the terminal supports the specified boolean capability.

        Boolean capabilities indicate whether the terminal supports specific features, such as color support, automatic margins, or status line support.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Check if terminal supports colors
         if (terminal.getBooleanCapability(Capability.colors)) {
             // Use color output
         } else {
             // Use monochrome output
         }
         
        Parameters:
        capability - the boolean capability to check
        Returns:
        true if the terminal supports the capability, false otherwise
      • getNumericCapability

        java.lang.Integer getNumericCapability​(InfoCmp.Capability capability)
        Returns the value of the specified numeric capability for this terminal.

        Numeric capabilities represent terminal properties with numeric values, such as the maximum number of colors supported, the number of function keys, or timing parameters for certain operations.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Get the number of colors supported by the terminal
         Integer colors = terminal.getNumericCapability(Capability.max_colors);
         if (colors != null && colors >= 256) {
             // Terminal supports 256 colors
         }
         
        Parameters:
        capability - the numeric capability to retrieve
        Returns:
        the value of the capability, or null if the capability is not supported
      • getStringCapability

        java.lang.String getStringCapability​(InfoCmp.Capability capability)
        Returns the string value of the specified capability for this terminal.

        String capabilities represent terminal control sequences that can be used to perform various operations, such as moving the cursor, changing colors, clearing the screen, or ringing the bell. These sequences can be parameterized using the puts(Capability, Object...) method.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Get the control sequence for clearing the screen
         String clearScreen = terminal.getStringCapability(Capability.clear_screen);
         if (clearScreen != null) {
             // Use the sequence directly
             terminal.writer().print(clearScreen);
             terminal.flush();
         }
         
        Parameters:
        capability - the string capability to retrieve
        Returns:
        the string value of the capability, or null if the capability is not supported
        See Also:
        puts(Capability, Object...)
      • getCursorPosition

        Cursor getCursorPosition​(java.util.function.IntConsumer discarded)
        Query the terminal to report the cursor position. As the response is read from the input stream, some characters may be read before the cursor position is actually read. Those characters can be given back using org.jline.keymap.BindingReader#runMacro(String)
        Parameters:
        discarded - a consumer receiving discarded characters
        Returns:
        null if cursor position reporting is not supported or a valid cursor position
      • hasMouseSupport

        boolean hasMouseSupport()
        Returns whether the terminal has support for mouse tracking.

        Mouse support allows the terminal to report mouse events such as clicks, movement, and wheel scrolling. Not all terminals support mouse tracking, so this method should be called before attempting to enable mouse tracking with trackMouse(MouseTracking).

        Common terminal emulators that support mouse tracking include xterm, iTerm2, and modern versions of GNOME Terminal and Konsole. Terminal multiplexers like tmux and screen may also support mouse tracking depending on their configuration and the capabilities of the underlying terminal.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         if (terminal.hasMouseSupport()) {
             // Enable mouse tracking
             terminal.trackMouse(MouseTracking.Normal);
        
             // Process mouse events
             // ...
         } else {
             System.out.println("Mouse tracking not supported by this terminal");
         }
         
        Returns:
        true if the terminal supports mouse tracking, false otherwise
        See Also:
        trackMouse(MouseTracking), readMouseEvent()
      • trackMouse

        boolean trackMouse​(Terminal.MouseTracking tracking)
        Enables or disables mouse tracking with the specified mode.

        This method configures the terminal to report mouse events according to the specified tracking mode. When mouse tracking is enabled, the terminal will send special escape sequences to the input stream whenever mouse events occur. These sequences begin with the InfoCmp.Capability.key_mouse sequence, followed by data that describes the specific mouse event.

        The tracking mode determines which mouse events are reported:

        To process mouse events, applications should:

        1. Enable mouse tracking by calling this method with the desired mode
        2. Monitor the input stream for the InfoCmp.Capability.key_mouse sequence
        3. When this sequence is detected, call readMouseEvent() to decode the event
        4. Process the returned MouseEvent as needed

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         if (terminal.hasMouseSupport()) {
             // Enable tracking of all mouse events
             boolean supported = terminal.trackMouse(MouseTracking.Any);
        
             if (supported) {
                 System.out.println("Mouse tracking enabled");
                 // Set up input processing to detect and handle mouse events
             }
         }
         
        Parameters:
        tracking - the mouse tracking mode to enable, or Terminal.MouseTracking.Off to disable tracking
        Returns:
        true if the requested mouse tracking mode is supported, false otherwise
        See Also:
        Terminal.MouseTracking, hasMouseSupport(), readMouseEvent()
      • readMouseEvent

        MouseEvent readMouseEvent()
        Read a MouseEvent from the terminal input stream. Such an event must have been detected by scanning the terminal's InfoCmp.Capability.key_mouse in the stream immediately before reading the event.

        This method should be called after detecting the terminal's InfoCmp.Capability.key_mouse sequence in the input stream, which indicates that a mouse event has occurred. The method reads the necessary data from the input stream and decodes it into a MouseEvent object containing information about the event type, button, modifiers, and coordinates.

        Before calling this method, mouse tracking must be enabled using trackMouse(MouseTracking) with an appropriate tracking mode.

        The typical pattern for handling mouse events is:

        1. Enable mouse tracking with trackMouse(MouseTracking)
        2. Read input from the terminal
        3. When the InfoCmp.Capability.key_mouse sequence is detected, call this method
        4. Process the returned MouseEvent

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         if (terminal.hasMouseSupport()) {
             terminal.trackMouse(MouseTracking.Normal);
        
             // Read input and look for mouse events
             String keyMouse = terminal.getStringCapability(Capability.key_mouse);
             // When keyMouse sequence is detected in the input:
             MouseEvent event = terminal.readMouseEvent();
             System.out.println("Mouse event: " + event.getType() +
                               " at " + event.getX() + "," + event.getY());
         }
         
        Returns:
        the decoded mouse event containing event type, button, modifiers, and coordinates
        See Also:
        trackMouse(MouseTracking), hasMouseSupport(), MouseEvent
      • readMouseEvent

        MouseEvent readMouseEvent​(java.util.function.IntSupplier reader)
        Reads and decodes a mouse event using the provided input supplier.

        This method is similar to readMouseEvent(), but allows reading mouse event data from a custom input source rather than the terminal's default input stream. This can be useful in situations where input is being processed through a different channel or when implementing custom input handling.

        The input supplier should provide the raw bytes of the mouse event data as integers. The method will read the necessary data from the supplier and decode it into a MouseEvent object containing information about the event type, button, modifiers, and coordinates.

        This method is primarily intended for advanced use cases where the standard readMouseEvent() method is not sufficient.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         // Create a custom input supplier
         IntSupplier customReader = new IntSupplier() {
             private byte[] data = ...; // Mouse event data
             private int index = 0;
        
             public int getAsInt() {
                 return (index < data.length) ? data[index++] & 0xFF : -1;
             }
         };
        
         // Read mouse event using the custom supplier
         MouseEvent event = terminal.readMouseEvent(customReader);
         
        Parameters:
        reader - the input supplier that provides the raw bytes of the mouse event data
        Returns:
        the decoded mouse event containing event type, button, modifiers, and coordinates
        See Also:
        readMouseEvent(), MouseEvent
      • readMouseEvent

        MouseEvent readMouseEvent​(java.lang.String prefix)
        Reads and decodes a mouse event with a specified prefix that has already been consumed.

        This method is similar to readMouseEvent(), but it allows specifying a prefix that has already been consumed. This is useful when the mouse event prefix (e.g., "\033[<" or "\033[M") has been consumed by the key binding detection, and we need to continue parsing from the current position.

        This method is primarily intended for advanced use cases where the standard readMouseEvent() method is not sufficient, particularly when dealing with key binding systems that may consume part of the mouse event sequence.

        Parameters:
        prefix - the prefix that has already been consumed, or null if none
        Returns:
        the decoded mouse event containing event type, button, modifiers, and coordinates
        Since:
        3.30.0
        See Also:
        readMouseEvent(), MouseEvent
      • readMouseEvent

        MouseEvent readMouseEvent​(java.util.function.IntSupplier reader,
                                  java.lang.String prefix)
        Reads and decodes a mouse event using the provided input supplier with a specified prefix that has already been consumed.

        This method combines the functionality of readMouseEvent(IntSupplier) and readMouseEvent(String), allowing both a custom input supplier and a prefix to be specified. This is useful for advanced input handling scenarios where both customization of the input source and handling of partially consumed sequences are needed.

        Parameters:
        reader - the input supplier that provides the raw bytes of the mouse event data
        prefix - the prefix that has already been consumed, or null if none
        Returns:
        the decoded mouse event containing event type, button, modifiers, and coordinates
        Since:
        3.30.0
        See Also:
        readMouseEvent(), readMouseEvent(IntSupplier), readMouseEvent(String), MouseEvent
      • hasFocusSupport

        boolean hasFocusSupport()
        Returns whether the terminal has support for focus tracking.

        Focus tracking allows the terminal to report when it gains or loses focus. This can be useful for applications that need to change their behavior or appearance based on whether they are currently in focus.

        Not all terminals support focus tracking, so this method should be called before attempting to enable focus tracking with trackFocus(boolean).

        When focus tracking is enabled and supported, the terminal will send special escape sequences to the input stream when focus is gained ("\33[I") or lost ("\33[O"). Applications can detect these sequences to respond to focus changes.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         if (terminal.hasFocusSupport()) {
             // Enable focus tracking
             terminal.trackFocus(true);
        
             // Now the application can detect focus changes
             // by looking for "\33[I" and "\33[O" in the input stream
         } else {
             System.out.println("Focus tracking not supported by this terminal");
         }
         
        Returns:
        true if the terminal supports focus tracking, false otherwise
        See Also:
        trackFocus(boolean)
      • trackFocus

        boolean trackFocus​(boolean tracking)
        Enables or disables focus tracking mode.

        Focus tracking allows applications to detect when the terminal window gains or loses focus. When focus tracking is enabled, the terminal will send special escape sequences to the input stream whenever the focus state changes:

        • When the terminal gains focus: "\33[I" (ESC [ I)
        • When the terminal loses focus: "\33[O" (ESC [ O)

        Applications can monitor the input stream for these sequences to detect focus changes and respond accordingly, such as by changing the cursor appearance, pausing animations, or adjusting the display.

        Not all terminals support focus tracking. Use hasFocusSupport() to check whether focus tracking is supported before enabling it.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
        
         if (terminal.hasFocusSupport()) {
             // Enable focus tracking
             boolean enabled = terminal.trackFocus(true);
        
             if (enabled) {
                 System.out.println("Focus tracking enabled");
                 // Set up input processing to detect focus change sequences
             }
         }
         
        Parameters:
        tracking - true to enable focus tracking, false to disable it
        Returns:
        true if focus tracking is supported and the operation succeeded, false otherwise
        See Also:
        hasFocusSupport()
      • getPalette

        ColorPalette getPalette()
        Returns the color palette for this terminal.

        The color palette provides access to the terminal's color capabilities, allowing for customization and mapping of colors to terminal-specific values. This is particularly useful for terminals that support different color modes (8-color, 256-color, or true color).

        The palette allows mapping between color values and their RGB representations, and provides methods for color conversion and manipulation.

        Example usage:

         Terminal terminal = TerminalBuilder.terminal();
         ColorPalette palette = terminal.getPalette();
        
         // Get RGB values for a specific color
         int[] rgb = palette.toRgb(AttributedStyle.RED);
         
        Returns:
        the terminal's color palette
        See Also:
        ColorPalette
      • getDefaultForegroundColor

        default int getDefaultForegroundColor()
        Returns the terminal's default foreground color as an RGB value.

        This method provides access to the terminal's default text color, which can be useful for creating color schemes that complement the terminal's default colors. The color is returned as a packed RGB integer value (0xRRGGBB).

        If the terminal does not support color detection or the default color cannot be determined, this method returns -1.

        Returns:
        the RGB value (0xRRGGBB) of the default foreground color, or -1 if not available
        Since:
        3.30.0
        See Also:
        getDefaultBackgroundColor(), getPalette()
      • getDefaultBackgroundColor

        default int getDefaultBackgroundColor()
        Returns the terminal's default background color as an RGB value.

        This method provides access to the terminal's default background color, which can be useful for creating color schemes that complement the terminal's default colors. The color is returned as a packed RGB integer value (0xRRGGBB).

        If the terminal does not support color detection or the default color cannot be determined, this method returns -1.

        Returns:
        the RGB value (0xRRGGBB) of the default background color, or -1 if not available
        Since:
        3.30.0
        See Also:
        getDefaultForegroundColor(), getPalette()