Class AbstractUnixSysTerminal

  • All Implemented Interfaces:
    java.io.Closeable, java.io.Flushable, java.lang.AutoCloseable, Sized, TerminalExt, Terminal

    public abstract class AbstractUnixSysTerminal
    extends AbstractTerminal
    Base class for flattened POSIX system terminals that bypass the PTY abstraction.

    Subclasses only need to implement four methods for platform-specific attribute and size operations:

    The call chain is reduced from 7 layers to 4:

       Terminal ? AbstractTerminal ? AbstractUnixSysTerminal ? subclass ? native call
     

    Important: the underlying system streams (FileDescriptor.in, FileDescriptor.out/err) are wrapped in NonCloseableInputStream / NonCloseableOutputStream. Closing the terminal will shut down the pump thread and release resources, but will not close the shared file descriptors. This prevents breaking System.in/System.out for the rest of the JVM.

    • Constructor Detail

      • AbstractUnixSysTerminal

        protected AbstractUnixSysTerminal​(TerminalProvider provider,
                                          SystemStream systemStream,
                                          java.lang.String name,
                                          java.lang.String type,
                                          java.nio.charset.Charset encoding,
                                          java.nio.charset.Charset inputEncoding,
                                          java.nio.charset.Charset outputEncoding,
                                          boolean nativeSignals,
                                          Terminal.SignalHandler signalHandler,
                                          Attributes originalAttributes)
                                   throws java.io.IOException
        Throws:
        java.io.IOException
    • Method Detail

      • handle

        public Terminal.SignalHandler handle​(Terminal.Signal signal,
                                             Terminal.SignalHandler handler)
        Description copied from interface: Terminal
        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);
         
        Specified by:
        handle in interface Terminal
        Overrides:
        handle in class AbstractTerminal
        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, Terminal.raise(Signal)
      • doGetAttributes

        protected abstract Attributes doGetAttributes()
      • doSetAttributes

        protected abstract void doSetAttributes​(Attributes attr)
      • doGetSize

        protected abstract Size doGetSize()
      • doSetSize

        protected abstract void doSetSize​(Sized size)
      • createPollFunction

        protected java.util.function.IntUnaryOperator createPollFunction()
        Creates a poll function that checks stdin for input readiness using poll(2).

        When non-null, the returned function is passed to NonBlockingInputStream.setPollFunction(IntUnaryOperator) so the pump thread can use short-timeout polls instead of an indefinite blocking read. This prevents the pump from stealing keystrokes from subprocesses that share the same tty fd (see #2219).

        Subclasses should override to provide a platform-specific binding (FFM or JNI). The default returns null, which falls back to blocking reads and preserves backward compatibility.

        Returns:
        (timeoutMs) ? poll result: positive if data is ready, 0 on timeout, negative on error; or null if poll is not available
      • hasPollSupport

        protected boolean hasPollSupport()
        Description copied from class: AbstractTerminal
        Returns true if the terminal's input stream uses poll(2) or an equivalent mechanism to enforce read timeouts.

        When poll is available, the probe code can run synchronously on the calling thread because read(timeout) will reliably return within the specified time even on PTY file descriptors. When poll is NOT available, the probe must use a daemon thread with a hard deadline to break out of potentially blocking reads (see AbstractTerminal.ensureModesProbed()).

        The default returns false. Subclasses that wire poll into their input streams should override.

        Overrides:
        hasPollSupport in class AbstractTerminal
      • getAttributes

        public Attributes getAttributes()
        Description copied from interface: Terminal
        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 Terminal.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:
        Terminal.setAttributes(Attributes), Attributes, Terminal.enterRawMode()
      • setAttributes

        public void setAttributes​(Attributes attr)
        Description copied from interface: Terminal
        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 Terminal.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:
        Terminal.getAttributes(), Attributes, Terminal.enterRawMode()
      • getSize

        public Size getSize()
        Description copied from interface: Terminal
        Retrieve the size of the visible window
        Returns:
        the visible terminal size
        See Also:
        Terminal.getBufferSize()
      • setSize

        public void setSize​(Sized size)
        Description copied from interface: Terminal
        Requests that the terminal adopt the specified window dimensions. Implementations may apply constraints or ignore the request if resizing is unsupported; callers should use Terminal.getSize() to observe the effective size after calling this method.
        Parameters:
        size - the desired terminal size (columns and rows)
        See Also:
        Terminal.getSize()
      • reader

        public NonBlockingReader reader()
        Description copied from interface: Terminal
        Retrieve the Reader for this terminal. This is the standard way to read input from this terminal. The reader is non blocking.

        The returned reader is owned by this terminal and will be closed when the terminal is closed. Callers should not close it directly.

        Returns:
        The non blocking reader
      • writer

        public java.io.PrintWriter writer()
        Description copied from interface: Terminal
        Retrieve the Writer for this terminal. This is the standard way to write to this terminal.

        The returned writer is owned by this terminal and will be closed when the terminal is closed. Callers should not close it directly.

        Returns:
        The writer
      • input

        public java.io.InputStream input()
        Description copied from interface: Terminal
        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 Terminal.reader() instead.

        The returned stream is owned by this terminal and will be closed when the terminal is closed. Callers should not close it directly.

        Returns:
        The input stream
        See Also:
        Terminal.reader()
      • output

        public java.io.OutputStream output()
        Description copied from interface: Terminal
        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 Terminal.writer() instead.

        The returned stream is owned by this terminal and will be closed when the terminal is closed. Callers should not close it directly.

        Returns:
        The output stream
        See Also:
        Terminal.writer()
      • getProvider

        public TerminalProvider getProvider()
        Description copied from interface: TerminalExt
        Returns the terminal provider that created this terminal.

        The terminal provider is responsible for creating and managing terminal instances on a specific platform. This method allows access to the provider that created this terminal, which can be useful for accessing provider-specific functionality or for creating additional terminals with the same provider.

        Returns:
        the TerminalProvider that created this terminal, or null if the terminal was created with no provider
        See Also:
        TerminalProvider
      • getSystemStream

        public SystemStream getSystemStream()
        Description copied from interface: TerminalExt
        Returns the system stream associated with this terminal, if any.

        This method indicates whether the terminal is bound to a standard system stream (standard input, standard output, or standard error). Terminals that are connected to system streams typically represent the actual terminal window or console that the application is running in.

        Returns:
        the underlying system stream, which may be SystemStream.Input, SystemStream.Output, SystemStream.Error, or null if this terminal is not bound to a system stream
        See Also:
        SystemStream
      • getCursorPosition

        public Cursor getCursorPosition​(java.util.function.IntConsumer discarded)
        Description copied from interface: Terminal
        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)
        Specified by:
        getCursorPosition in interface Terminal
        Overrides:
        getCursorPosition in class AbstractTerminal
        Parameters:
        discarded - a consumer receiving discarded characters
        Returns:
        null if cursor position reporting is not supported or a valid cursor position
      • doClose

        protected void doClose()
                        throws java.io.IOException
        Overrides:
        doClose in class AbstractTerminal
        Throws:
        java.io.IOException