Class AbstractTerminal
- java.lang.Object
-
- org.jline.terminal.impl.AbstractTerminal
-
- All Implemented Interfaces:
java.io.Closeable,java.io.Flushable,java.lang.AutoCloseable,TerminalExt,Terminal
- Direct Known Subclasses:
AbstractPosixTerminal,AbstractWindowsTerminal,DumbTerminal,LineDisciplineTerminal
public abstract class AbstractTerminal extends java.lang.Object implements TerminalExt
Base implementation of the Terminal interface.This abstract class provides a common foundation for terminal implementations, handling many of the core terminal functions such as signal handling, attribute management, and capability lookup. It implements most of the methods defined in the
Terminalinterface, leaving only a few abstract methods to be implemented by concrete subclasses.Terminal implementations typically extend this class and provide implementations for the abstract methods related to their specific platform or environment. This class handles the common functionality, allowing subclasses to focus on platform-specific details.
Key features provided by this class include:
- Signal handling infrastructure
- Terminal attribute management
- Terminal capability lookup and caching
- Size and cursor position handling
- Mouse and focus tracking support
- See Also:
Terminal,TerminalExt
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from interface org.jline.terminal.Terminal
Terminal.MouseTracking, Terminal.Signal, Terminal.SignalHandler
-
-
Field Summary
Fields Modifier and Type Field Description protected java.util.Set<InfoCmp.Capability>boolsprotected booleanclosedprotected Terminal.MouseTrackingcurrentMouseTrackingprotected java.nio.charset.Charsetencodingprotected java.util.Map<Terminal.Signal,Terminal.SignalHandler>handlersprotected java.nio.charset.CharsetinputEncodingprotected java.util.Map<InfoCmp.Capability,java.lang.Integer>intsprotected java.lang.Stringnameprotected java.lang.RunnableonCloseprotected java.nio.charset.CharsetoutputEncodingprotected ColorPalettepaletteprotected Statusstatusprotected java.util.Map<InfoCmp.Capability,java.lang.String>stringsprotected java.lang.Stringtype-
Fields inherited from interface org.jline.terminal.Terminal
TYPE_DUMB, TYPE_DUMB_COLOR
-
-
Constructor Summary
Constructors Constructor Description AbstractTerminal(java.lang.String name, java.lang.String type)AbstractTerminal(java.lang.String name, java.lang.String type, java.nio.charset.Charset encoding, java.nio.charset.Charset inputEncoding, java.nio.charset.Charset outputEncoding, Terminal.SignalHandler signalHandler)AbstractTerminal(java.lang.String name, java.lang.String type, java.nio.charset.Charset encoding, Terminal.SignalHandler signalHandler)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleancanPauseResume()Whether this terminal supportsTerminal.pause()andTerminal.resume()calls.protected voidcheckClosed()Checks if this terminal has been closed and throws an exception if it has.protected voidcheckInterrupted()voidclose()protected voiddoClose()booleanecho()Returns whether the terminal is currently echoing input characters.booleanecho(boolean echo)Enables or disables echoing of input characters.protected voidechoSignal(Terminal.Signal signal)java.nio.charset.Charsetencoding()Returns theCharsetthat should be used to encode characters forTerminal.input()andTerminal.output().AttributesenterRawMode()Puts the terminal into raw mode.voidflush()Flushes any buffered output to the terminal.booleangetBooleanCapability(InfoCmp.Capability capability)Returns whether the terminal supports the specified boolean capability.Terminal.MouseTrackinggetCurrentMouseTracking()Returns the current mouse tracking mode.CursorgetCursorPosition(java.util.function.IntConsumer discarded)Query the terminal to report the cursor position.intgetDefaultBackgroundColor()Get the terminal's default background color.intgetDefaultForegroundColor()Get the terminal's default foreground color.java.lang.StringgetKind()java.lang.StringgetName()Returns the name of this terminal.java.lang.IntegergetNumericCapability(InfoCmp.Capability capability)Returns the value of the specified numeric capability for this terminal.ColorPalettegetPalette()Returns the color palette for this terminal.StatusgetStatus()StatusgetStatus(boolean create)java.lang.StringgetStringCapability(InfoCmp.Capability capability)Returns the string value of the specified capability for this terminal.java.lang.StringgetType()Returns the type of this terminal.Terminal.SignalHandlerhandle(Terminal.Signal signal, Terminal.SignalHandler handler)Registers a handler for the givenTerminal.Signal.booleanhasFocusSupport()Returns whether the terminal has support for focus tracking.booleanhasMouseSupport()Returns whether the terminal has support for mouse tracking.java.nio.charset.CharsetinputEncoding()Returns theCharsetthat should be used to decode characters from the terminal input (Terminal.input()).java.nio.charset.CharsetoutputEncoding()Returns theCharsetthat should be used to encode characters for the terminal output (Terminal.output()).protected voidparseInfoCmp()voidpause()Temporarily stops reading the input stream.voidpause(boolean wait)Stop reading the input stream and optionally wait for the underlying threads to finish.booleanpaused()Check whether the terminal is currently reading the input stream or not.booleanputs(InfoCmp.Capability capability, java.lang.Object... params)Outputs a terminal control string for the specified capability.voidraise(Terminal.Signal signal)Raises the specified signal, triggering any registered handlers.MouseEventreadMouseEvent()Read a MouseEvent from the terminal input stream.MouseEventreadMouseEvent(java.lang.String prefix)Reads and decodes a mouse event with a specified prefix that has already been consumed.MouseEventreadMouseEvent(java.util.function.IntSupplier reader)Reads and decodes a mouse event using the provided input supplier.MouseEventreadMouseEvent(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.voidresume()Resumes reading the input stream after it has been paused.voidsetOnClose(java.lang.Runnable onClose)java.lang.StringtoString()booleantrackFocus(boolean tracking)Enables or disables focus tracking mode.booleantrackMouse(Terminal.MouseTracking tracking)Enables or disables mouse tracking with the specified mode.-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.jline.terminal.Terminal
getAttributes, getBufferSize, getHeight, getSize, getWidth, input, output, reader, setAttributes, setSize, stderrEncoding, stdinEncoding, stdoutEncoding, writer
-
Methods inherited from interface org.jline.terminal.spi.TerminalExt
getProvider, getSystemStream
-
-
-
-
Field Detail
-
name
protected final java.lang.String name
-
type
protected final java.lang.String type
-
encoding
protected final java.nio.charset.Charset encoding
-
inputEncoding
protected final java.nio.charset.Charset inputEncoding
-
outputEncoding
protected final java.nio.charset.Charset outputEncoding
-
handlers
protected final java.util.Map<Terminal.Signal,Terminal.SignalHandler> handlers
-
bools
protected final java.util.Set<InfoCmp.Capability> bools
-
ints
protected final java.util.Map<InfoCmp.Capability,java.lang.Integer> ints
-
strings
protected final java.util.Map<InfoCmp.Capability,java.lang.String> strings
-
palette
protected final ColorPalette palette
-
status
protected Status status
-
onClose
protected java.lang.Runnable onClose
-
currentMouseTracking
protected Terminal.MouseTracking currentMouseTracking
-
closed
protected volatile boolean closed
-
-
Constructor Detail
-
AbstractTerminal
public AbstractTerminal(java.lang.String name, java.lang.String type) throws java.io.IOException- Throws:
java.io.IOException
-
AbstractTerminal
public AbstractTerminal(java.lang.String name, java.lang.String type, java.nio.charset.Charset encoding, Terminal.SignalHandler signalHandler) throws java.io.IOException- Throws:
java.io.IOException
-
AbstractTerminal
public AbstractTerminal(java.lang.String name, java.lang.String type, java.nio.charset.Charset encoding, java.nio.charset.Charset inputEncoding, java.nio.charset.Charset outputEncoding, Terminal.SignalHandler signalHandler) throws java.io.IOException- Throws:
java.io.IOException
-
-
Method Detail
-
setOnClose
public void setOnClose(java.lang.Runnable onClose)
-
getStatus
public Status getStatus()
-
getStatus
public Status getStatus(boolean create)
-
checkClosed
protected void checkClosed()
Checks if this terminal has been closed and throws an exception if it has.This method provides a centralized check for terminal closure, ensuring consistent error handling across all terminal operations.
- Throws:
java.lang.IllegalStateException- if this terminal has been closed
-
handle
public Terminal.SignalHandler handle(Terminal.Signal signal, Terminal.SignalHandler handler)
Description copied from interface:TerminalRegisters a handler for the givenTerminal.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.QUITsignal (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:
handlein interfaceTerminal- Parameters:
signal- the signal to register a handler forhandler- 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)
-
raise
public void raise(Terminal.Signal signal)
Description copied from interface:TerminalRaises the specified signal, triggering any registered handlers.This method manually triggers a signal, causing any registered handler for that signal to be called. This is typically not a method that application code would call directly, but is used internally by terminal implementations.
When accessing a terminal through an SSH or Telnet connection, signals may be conveyed by the protocol and need to be raised when they reach the terminal code. Terminal implementations automatically raise signals when the input stream receives characters mapped to special control characters:
Attributes.ControlChar.VINTR(typically Ctrl+C) - RaisesTerminal.Signal.INTAttributes.ControlChar.VQUIT(typically Ctrl+\) - RaisesTerminal.Signal.QUITAttributes.ControlChar.VSUSP(typically Ctrl+Z) - RaisesTerminal.Signal.TSTP
In some cases, application code might want to programmatically raise signals to trigger specific behaviors, such as simulating a window resize event by raising
Terminal.Signal.WINCH.- Specified by:
raisein interfaceTerminal- Parameters:
signal- the signal to raise- See Also:
Terminal.Signal,Terminal.handle(Signal, SignalHandler),Attributes.ControlChar
-
close
public final void close() throws java.io.IOException- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Throws:
java.io.IOException
-
doClose
protected void doClose() throws java.io.IOException- Throws:
java.io.IOException
-
echoSignal
protected void echoSignal(Terminal.Signal signal)
-
enterRawMode
public Attributes enterRawMode()
Description copied from interface:TerminalPuts 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);
- Specified by:
enterRawModein interfaceTerminal- Returns:
- the original terminal attributes before entering raw mode
- See Also:
Terminal.setAttributes(Attributes)
-
echo
public boolean echo()
Description copied from interface:TerminalReturns 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.
- Specified by:
echoin interfaceTerminal- Returns:
trueif echo is enabled,falseotherwise- See Also:
Terminal.echo(boolean)
-
echo
public boolean echo(boolean echo)
Description copied from interface:TerminalEnables 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
-
getName
public java.lang.String getName()
Description copied from interface:TerminalReturns 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.
-
getType
public java.lang.String getType()
Description copied from interface:TerminalReturns 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:
Terminal.TYPE_DUMB- A terminal with minimal capabilities, typically not supporting cursor movement or colorsTerminal.TYPE_DUMB_COLOR- A dumb terminal that supports basic color output
- Specified by:
getTypein interfaceTerminal- Returns:
- the terminal type identifier
- See Also:
Terminal.TYPE_DUMB,Terminal.TYPE_DUMB_COLOR
-
getKind
public java.lang.String getKind()
-
encoding
public java.nio.charset.Charset encoding()
Description copied from interface:TerminalReturns theCharsetthat should be used to encode characters forTerminal.input()andTerminal.output().This method returns a general encoding that can be used for both input and output. For stream-specific encodings, use
Terminal.inputEncoding()andTerminal.outputEncoding().- Specified by:
encodingin interfaceTerminal- Returns:
- The terminal encoding
- See Also:
Terminal.inputEncoding(),Terminal.outputEncoding()
-
inputEncoding
public java.nio.charset.Charset inputEncoding()
Description copied from interface:TerminalReturns theCharsetthat should be used to decode characters from the terminal input (Terminal.input()).This method returns the encoding specifically for terminal input. If no specific input encoding was configured, it falls back to the general encoding from
Terminal.encoding().- Specified by:
inputEncodingin interfaceTerminal- Returns:
- The terminal input encoding
- See Also:
Terminal.encoding()
-
outputEncoding
public java.nio.charset.Charset outputEncoding()
Description copied from interface:TerminalReturns theCharsetthat should be used to encode characters for the terminal output (Terminal.output()).This method returns the encoding specifically for terminal output. The encoding used depends on the system stream associated with this terminal: if the terminal is bound to standard error, it uses the stderr encoding; otherwise, it uses the stdout encoding. If no specific output encoding was configured, it falls back to the general encoding from
Terminal.encoding().- Specified by:
outputEncodingin interfaceTerminal- Returns:
- The terminal output encoding
- See Also:
Terminal.encoding()
-
flush
public void flush()
Description copied from interface:TerminalFlushes 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();
-
puts
public boolean puts(InfoCmp.Capability capability, java.lang.Object... params)
Description copied from interface:TerminalOutputs 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);
- Specified by:
putsin interfaceTerminal- Parameters:
capability- the terminal capability to useparams- the parameters for the capability- Returns:
trueif the capability is supported and was output,falseotherwise- See Also:
Terminal.getStringCapability(Capability)
-
getBooleanCapability
public boolean getBooleanCapability(InfoCmp.Capability capability)
Description copied from interface:TerminalReturns 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 }- Specified by:
getBooleanCapabilityin interfaceTerminal- Parameters:
capability- the boolean capability to check- Returns:
trueif the terminal supports the capability,falseotherwise
-
getNumericCapability
public java.lang.Integer getNumericCapability(InfoCmp.Capability capability)
Description copied from interface:TerminalReturns 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 }- Specified by:
getNumericCapabilityin interfaceTerminal- Parameters:
capability- the numeric capability to retrieve- Returns:
- the value of the capability, or
nullif the capability is not supported
-
getStringCapability
public java.lang.String getStringCapability(InfoCmp.Capability capability)
Description copied from interface:TerminalReturns 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
Terminal.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(); }- Specified by:
getStringCapabilityin interfaceTerminal- Parameters:
capability- the string capability to retrieve- Returns:
- the string value of the capability, or
nullif the capability is not supported - See Also:
Terminal.puts(Capability, Object...)
-
parseInfoCmp
protected void parseInfoCmp()
-
getCursorPosition
public Cursor getCursorPosition(java.util.function.IntConsumer discarded)
Description copied from interface:TerminalQuery 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 usingorg.jline.keymap.BindingReader#runMacro(String)- Specified by:
getCursorPositionin interfaceTerminal- Parameters:
discarded- a consumer receiving discarded characters- Returns:
nullif cursor position reporting is not supported or a valid cursor position
-
hasMouseSupport
public boolean hasMouseSupport()
Description copied from interface:TerminalReturns 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
Terminal.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"); }- Specified by:
hasMouseSupportin interfaceTerminal- Returns:
trueif the terminal supports mouse tracking,falseotherwise- See Also:
Terminal.trackMouse(MouseTracking),Terminal.readMouseEvent()
-
getCurrentMouseTracking
public Terminal.MouseTracking getCurrentMouseTracking()
Description copied from interface:TerminalReturns the current mouse tracking mode.- Specified by:
getCurrentMouseTrackingin interfaceTerminal- See Also:
Terminal.trackMouse(MouseTracking)
-
trackMouse
public boolean trackMouse(Terminal.MouseTracking tracking)
Description copied from interface:TerminalEnables 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_mousesequence, followed by data that describes the specific mouse event.The tracking mode determines which mouse events are reported:
Terminal.MouseTracking.Off- Disables mouse trackingTerminal.MouseTracking.Normal- Reports button press and release eventsTerminal.MouseTracking.Button- Reports button press, release, and motion events while buttons are pressedTerminal.MouseTracking.Any- Reports all mouse events, including movement without buttons pressed
To process mouse events, applications should:
- Enable mouse tracking by calling this method with the desired mode
- Monitor the input stream for the
InfoCmp.Capability.key_mousesequence - When this sequence is detected, call
Terminal.readMouseEvent()to decode the event - Process the returned
MouseEventas 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 } }- Specified by:
trackMousein interfaceTerminal- Parameters:
tracking- the mouse tracking mode to enable, orTerminal.MouseTracking.Offto disable tracking- Returns:
trueif the requested mouse tracking mode is supported,falseotherwise- See Also:
Terminal.MouseTracking,Terminal.hasMouseSupport(),Terminal.readMouseEvent()
-
readMouseEvent
public MouseEvent readMouseEvent()
Description copied from interface:TerminalRead a MouseEvent from the terminal input stream. Such an event must have been detected by scanning the terminal'sInfoCmp.Capability.key_mousein the stream immediately before reading the event.This method should be called after detecting the terminal's
InfoCmp.Capability.key_mousesequence 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 aMouseEventobject containing information about the event type, button, modifiers, and coordinates.Before calling this method, mouse tracking must be enabled using
Terminal.trackMouse(MouseTracking)with an appropriate tracking mode.The typical pattern for handling mouse events is:
- Enable mouse tracking with
Terminal.trackMouse(MouseTracking) - Read input from the terminal
- When the
InfoCmp.Capability.key_mousesequence is detected, call this method - 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()); }- Specified by:
readMouseEventin interfaceTerminal- Returns:
- the decoded mouse event containing event type, button, modifiers, and coordinates
- See Also:
Terminal.trackMouse(MouseTracking),Terminal.hasMouseSupport(),MouseEvent
- Enable mouse tracking with
-
readMouseEvent
public MouseEvent readMouseEvent(java.util.function.IntSupplier reader)
Description copied from interface:TerminalReads and decodes a mouse event using the provided input supplier.This method is similar to
Terminal.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
MouseEventobject containing information about the event type, button, modifiers, and coordinates.This method is primarily intended for advanced use cases where the standard
Terminal.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);- Specified by:
readMouseEventin interfaceTerminal- 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:
Terminal.readMouseEvent(),MouseEvent
-
readMouseEvent
public MouseEvent readMouseEvent(java.lang.String prefix)
Description copied from interface:TerminalReads and decodes a mouse event with a specified prefix that has already been consumed.This method is similar to
Terminal.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
Terminal.readMouseEvent()method is not sufficient, particularly when dealing with key binding systems that may consume part of the mouse event sequence.- Specified by:
readMouseEventin interfaceTerminal- 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
- See Also:
Terminal.readMouseEvent(),MouseEvent
-
readMouseEvent
public MouseEvent readMouseEvent(java.util.function.IntSupplier reader, java.lang.String prefix)
Description copied from interface:TerminalReads 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
Terminal.readMouseEvent(IntSupplier)andTerminal.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.- Specified by:
readMouseEventin interfaceTerminal- Parameters:
reader- the input supplier that provides the raw bytes of the mouse event dataprefix- the prefix that has already been consumed, or null if none- Returns:
- the decoded mouse event containing event type, button, modifiers, and coordinates
- See Also:
Terminal.readMouseEvent(),Terminal.readMouseEvent(IntSupplier),Terminal.readMouseEvent(String),MouseEvent
-
hasFocusSupport
public boolean hasFocusSupport()
Description copied from interface:TerminalReturns 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
Terminal.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"); }- Specified by:
hasFocusSupportin interfaceTerminal- Returns:
trueif the terminal supports focus tracking,falseotherwise- See Also:
Terminal.trackFocus(boolean)
-
trackFocus
public boolean trackFocus(boolean tracking)
Description copied from interface:TerminalEnables 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
Terminal.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 } }- Specified by:
trackFocusin interfaceTerminal- Parameters:
tracking-trueto enable focus tracking,falseto disable it- Returns:
trueif focus tracking is supported and the operation succeeded,falseotherwise- See Also:
Terminal.hasFocusSupport()
-
checkInterrupted
protected void checkInterrupted() throws java.io.InterruptedIOException- Throws:
java.io.InterruptedIOException
-
canPauseResume
public boolean canPauseResume()
Description copied from interface:TerminalWhether this terminal supportsTerminal.pause()andTerminal.resume()calls.- Specified by:
canPauseResumein interfaceTerminal- Returns:
- whether this terminal supports
Terminal.pause()andTerminal.resume()calls. - See Also:
Terminal.paused(),Terminal.pause(),Terminal.resume()
-
pause
public void pause()
Description copied from interface:TerminalTemporarily 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
Terminal.pause(boolean)with a value oftrue.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();- Specified by:
pausein interfaceTerminal- See Also:
Terminal.resume(),Terminal.pause(boolean),Terminal.paused(),Terminal.canPauseResume()
-
pause
public void pause(boolean wait) throws java.lang.InterruptedExceptionDescription copied from interface:TerminalStop reading the input stream and optionally wait for the underlying threads to finish.
-
resume
public void resume()
Description copied from interface:TerminalResumes reading the input stream after it has been paused.This method restarts the terminal's input processing after it has been temporarily stopped using
Terminal.pause()orTerminal.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();
- Specified by:
resumein interfaceTerminal- See Also:
Terminal.pause(),Terminal.pause(boolean),Terminal.paused(),Terminal.canPauseResume()
-
paused
public boolean paused()
Description copied from interface:TerminalCheck 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.- Specified by:
pausedin interfaceTerminal- Returns:
- whether the terminal is currently reading the input stream or not
- See Also:
Terminal.pause(),Terminal.resume()
-
getPalette
public ColorPalette getPalette()
Description copied from interface:TerminalReturns 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);
- Specified by:
getPalettein interfaceTerminal- Returns:
- the terminal's color palette
- See Also:
ColorPalette
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
getDefaultForegroundColor
public int getDefaultForegroundColor()
Get the terminal's default foreground color. This method should be overridden by concrete implementations.- Specified by:
getDefaultForegroundColorin interfaceTerminal- Returns:
- the RGB value of the default foreground color, or -1 if not available
- See Also:
Terminal.getDefaultBackgroundColor(),Terminal.getPalette()
-
getDefaultBackgroundColor
public int getDefaultBackgroundColor()
Get the terminal's default background color. This method should be overridden by concrete implementations.- Specified by:
getDefaultBackgroundColorin interfaceTerminal- Returns:
- the RGB value of the default background color, or -1 if not available
- See Also:
Terminal.getDefaultForegroundColor(),Terminal.getPalette()
-
-