Class GraphicalTerminalImplementation
- All Implemented Interfaces:
InputProvider, IOSafeTerminal, Terminal, Closeable, AutoCloseable
- Direct Known Subclasses:
AWTTerminalImplementation, SwingTerminalImplementation
AWTTerminal and SwingTerminal. It maintains
most of the external terminal state and also the main back buffer that is copied to the components area on draw
operations.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static classprotected classClass that translates AWT key events into LanternaKeyStrokeprotected class -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate BufferedImageprivate booleanprivate booleanprivate Timerprivate final TerminalEmulatorColorConfigurationprivate BufferedImageprivate booleanprivate final TerminalEmulatorDeviceConfigurationprivate final GraphicalTerminalImplementation.DirtyCellsLookupTableprivate booleanprivate final Stringprivate booleanprivate final BlockingQueue<KeyStroke> private intprivate intprivate intprivate TerminalPositionprivate booleanprivate final TerminalScrollController////////private final DefaultVirtualTerminal -
Constructor Summary
ConstructorsConstructorDescriptionGraphicalTerminalImplementation(TerminalSize initialTerminalSize, TerminalEmulatorDeviceConfiguration deviceConfiguration, TerminalEmulatorColorConfiguration colorConfiguration, TerminalScrollController scrollController) Creates a new GraphicalTerminalImplementation component using custom settings and a custom scroll controller. -
Method Summary
Modifier and TypeMethodDescription(package private) voidvoidaddResizeListener(TerminalResizeListener listener) Adds aTerminalResizeListenerto be called when the terminal has changed size.voidbell()Prints 0x7 to the terminal, which will make the terminal (emulator) ring a bell (or more likely beep).private voidbuildDirtyCellsLookupTable(int firstRowOffset, int lastRowOffset) private voidClears out the back buffer and the resets the visual state so next paint operation will do a full repaint of everythingvoidRemoves all the characters, colors and graphics from the screen and leaves you with a big empty space.voidclose()Closes the terminal, if applicable.private ColorderiveTrueBackgroundColor(TextCharacter character, boolean atCursorLocation) private ColorderiveTrueForegroundColor(TextCharacter character, boolean atCursorLocation) voiddisableSGR(SGR sgr) Deactivates anSGR(Selected Graphic Rendition) code which has previously been activated throughenableSGR(..).private voiddrawCharacter(Graphics g, TextCharacter character, int columnIndex, int rowIndex, Color foregroundColor, Color backgroundColor, int fontWidth, int fontHeight, int characterWidth, int scrollingOffsetInPixels, boolean drawCursor) voidActivates anSGR(Selected Graphic Rendition) code.byte[]enquireTerminal(int timeout, TimeUnit timeoutUnit) Retrieves optional information from the terminal by printing the ENQ (\u005) character.private voidvoidCalling this method will, where supported, give your terminal a private area to use, separate from what was there before.voidIf you have previously entered private mode, this method will exit this and, depending on implementation, maybe restore what the terminal looked like before private mode was entered.voidflush()Callsflush()on the underlyingOutputStreamobject, or whatever other implementation this terminal is built around.(package private) TerminalEmulatorColorConfigurationReturns the position of the cursor, as reported by the terminal.(package private) TerminalEmulatorDeviceConfiguration(package private) abstract FontgetFontForCharacter(TextCharacter character) Returning the AWT font to use for the specific character.(package private) abstract intUsed to find out the font height, in pixels(package private) abstract intUsed to find out the font width, in pixels(package private) abstract intUsed when requiring the total height of the terminal component, in pixels(package private) DimensionCalculates the preferred size of this terminalReturns the size of the terminal, expressed as aTerminalSizeobject.(package private) abstract intgetWidth()Used when requiring the total width of the terminal component, in pixelsprivate voidinjectStringAsKeyStrokes(String string) (package private) abstract booleanReturnstrueif anti-aliasing is enabled,falseotherwiseCreates a new TextGraphics object that uses this Terminal directly when outputting.(package private) void(package private) void(package private) voidpaintComponent(Graphics componentGraphics) Updates the back buffer (if necessary) and draws it to the component's surfaceprivate voidprivate void////////voidputCharacter(char c) Prints one character to the terminal at the current cursor location.voidPrints a string to the terminal at the current cursor location.Returns the nextKeyoff the input queue or blocks until one is available.voidremoveResizeListener(TerminalResizeListener listener) Removes aTerminalResizeListenerfrom the list of listeners to be notified when the terminal has changed size(package private) abstract voidrepaint()Called by theGraphicalTerminalImplementationwhen it would like the OS to schedule a repaint of the windowvoidRemoves all currently active SGR codes and sets foreground and background colors back to default.voidsetBackgroundColor(TextColor color) Changes the background color for all the following characters put to the terminal.voidsetCursorPosition(int x, int y) Moves the text cursor to a new location on the terminal.voidsetCursorPosition(TerminalPosition position) Same as callingsetCursorPosition(position.getColumn(), position.getRow())voidsetCursorVisible(boolean visible) Hides or shows the text cursor, but not all terminal (-emulators) supports this.voidsetForegroundColor(TextColor color) Changes the foreground color for all the following characters put to the terminal.(package private) voidStart the timer that triggers blinking(package private) voidStops the timer the triggers blinkingprivate voidupdateBackBuffer(int scrollOffsetFromTopInPixels)
-
Field Details
-
deviceConfiguration
-
colorConfiguration
-
virtualTerminal
-
keyQueue
-
scrollController
-
dirtyCellsLookupTable
-
enquiryString
-
cursorIsVisible
private boolean cursorIsVisible -
enableInput
private boolean enableInput -
blinkTimer
-
hasBlinkingText
private boolean hasBlinkingText -
blinkOn
private boolean blinkOn -
bellOn
private boolean bellOn -
needFullRedraw
private boolean needFullRedraw -
lastDrawnCursorPosition
-
lastBufferUpdateScrollPosition
private int lastBufferUpdateScrollPosition -
lastComponentWidth
private int lastComponentWidth -
lastComponentHeight
private int lastComponentHeight -
backbuffer
-
copybuffer
-
TYPED_KEYS_TO_IGNORE
-
-
Constructor Details
-
GraphicalTerminalImplementation
GraphicalTerminalImplementation(TerminalSize initialTerminalSize, TerminalEmulatorDeviceConfiguration deviceConfiguration, TerminalEmulatorColorConfiguration colorConfiguration, TerminalScrollController scrollController) Creates a new GraphicalTerminalImplementation component using custom settings and a custom scroll controller. The scrolling controller will be notified when the terminal's history size grows and will be called when this class needs to figure out the current scrolling position.- Parameters:
initialTerminalSize- Initial size of the terminal, which will be used when calculating the preferred size of the component. If null, it will default to 80x25. If the AWT layout manager forces the component to a different size, the value of this parameter won't have any meaningdeviceConfiguration- Device configuration to use for this SwingTerminalcolorConfiguration- Color configuration to use for this SwingTerminalscrollController- Controller to use for scrolling, the object passed in will be notified whenever the scrollable area has changed
-
-
Method Details
-
getDeviceConfiguration
TerminalEmulatorDeviceConfiguration getDeviceConfiguration() -
getColorConfiguration
TerminalEmulatorColorConfiguration getColorConfiguration() -
getFontHeight
abstract int getFontHeight()Used to find out the font height, in pixels- Returns:
- Terminal font height in pixels
-
getFontWidth
abstract int getFontWidth()Used to find out the font width, in pixels- Returns:
- Terminal font width in pixels
-
getHeight
abstract int getHeight()Used when requiring the total height of the terminal component, in pixels- Returns:
- Height of the terminal component, in pixels
-
getWidth
abstract int getWidth()Used when requiring the total width of the terminal component, in pixels- Returns:
- Width of the terminal component, in pixels
-
getFontForCharacter
Returning the AWT font to use for the specific character. This might not always be the same, in case a we are trying to draw an unusual character (probably CJK) which isn't contained in the standard terminal font.- Parameters:
character- Character to get the font for- Returns:
- Font to be used for this character
-
isTextAntiAliased
abstract boolean isTextAntiAliased()Returnstrueif anti-aliasing is enabled,falseotherwise- Returns:
trueif anti-aliasing is enabled,falseotherwise
-
repaint
abstract void repaint()Called by theGraphicalTerminalImplementationwhen it would like the OS to schedule a repaint of the window -
onCreated
void onCreated() -
onDestroyed
void onDestroyed() -
startBlinkTimer
void startBlinkTimer()Start the timer that triggers blinking -
stopBlinkTimer
void stopBlinkTimer()Stops the timer the triggers blinking -
getPreferredSize
Dimension getPreferredSize()Calculates the preferred size of this terminal- Returns:
- Preferred size of this terminal
-
paintComponent
Updates the back buffer (if necessary) and draws it to the component's surface- Parameters:
componentGraphics- Object to use when drawing to the component's surface
-
updateBackBuffer
private void updateBackBuffer(int scrollOffsetFromTopInPixels) -
buildDirtyCellsLookupTable
private void buildDirtyCellsLookupTable(int firstRowOffset, int lastRowOffset) -
ensureGraphicBufferHasRightSize
private void ensureGraphicBufferHasRightSize() -
drawCharacter
private void drawCharacter(Graphics g, TextCharacter character, int columnIndex, int rowIndex, Color foregroundColor, Color backgroundColor, int fontWidth, int fontHeight, int characterWidth, int scrollingOffsetInPixels, boolean drawCursor) -
deriveTrueForegroundColor
-
deriveTrueBackgroundColor
-
addInput
-
pollInput
////////- Specified by:
pollInputin interfaceInputProvider- Specified by:
pollInputin interfaceIOSafeTerminal- Returns:
- Key object which represents a keystroke coming in through the input stream
-
readInput
Description copied from interface:InputProviderReturns the nextKeyoff the input queue or blocks until one is available. NOTE: In previous versions of Lanterna, this method was not blocking. From lanterna 3, it is blocking and you can callpollInput()for the non-blocking version.- Specified by:
readInputin interfaceInputProvider- Specified by:
readInputin interfaceIOSafeTerminal- Returns:
- Key object which represents a keystroke coming in through the input stream
-
enterPrivateMode
public void enterPrivateMode()Description copied from interface:TerminalCalling this method will, where supported, give your terminal a private area to use, separate from what was there before. Some terminal emulators will preserve the terminal history and restore it when you exit private mode. Some terminals will just clear the screen and put the cursor in the top-left corner. Typically, if you terminal supports scrolling, going into private mode will disable the scrolling and leave you with a fixed screen, which can be useful if you don't want to deal with what the terminal buffer will look like if the user scrolls up.- Specified by:
enterPrivateModein interfaceIOSafeTerminal- Specified by:
enterPrivateModein interfaceTerminal
-
exitPrivateMode
public void exitPrivateMode()Description copied from interface:TerminalIf you have previously entered private mode, this method will exit this and, depending on implementation, maybe restore what the terminal looked like before private mode was entered. If the terminal doesn't support a secondary buffer for private mode, it will probably make a new line below the private mode and place the cursor there.- Specified by:
exitPrivateModein interfaceIOSafeTerminal- Specified by:
exitPrivateModein interfaceTerminal
-
clearScreen
public void clearScreen()Description copied from interface:TerminalRemoves all the characters, colors and graphics from the screen and leaves you with a big empty space. Text cursor position is undefined after this call (depends on platform and terminal) so you should always callmoveCursornext. Some terminal implementations doesn't reset color and modifier state so it's also good practise to callresetColorAndSGR()after this.- Specified by:
clearScreenin interfaceIOSafeTerminal- Specified by:
clearScreenin interfaceTerminal
-
clearBackBuffer
private void clearBackBuffer()Clears out the back buffer and the resets the visual state so next paint operation will do a full repaint of everything -
setCursorPosition
public void setCursorPosition(int x, int y) Description copied from interface:TerminalMoves the text cursor to a new location on the terminal. The top-left corner has coordinates 0 x 0 and the bottom- right corner has coordinates terminal_width-1 x terminal_height-1. You can retrieve the size of the terminal by calling getTerminalSize().- Specified by:
setCursorPositionin interfaceIOSafeTerminal- Specified by:
setCursorPositionin interfaceTerminal- Parameters:
x- The 0-indexed column to place the cursor aty- The 0-indexed row to place the cursor at
-
setCursorPosition
Description copied from interface:TerminalSame as callingsetCursorPosition(position.getColumn(), position.getRow())- Specified by:
setCursorPositionin interfaceIOSafeTerminal- Specified by:
setCursorPositionin interfaceTerminal- Parameters:
position- Position to place the cursor at
-
getCursorPosition
Description copied from interface:TerminalReturns the position of the cursor, as reported by the terminal. The top-left corner has coordinates 0 x 0 and the bottom-right corner has coordinates terminal_width-1 x terminal_height-1.- Specified by:
getCursorPositionin interfaceIOSafeTerminal- Specified by:
getCursorPositionin interfaceTerminal- Returns:
- Position of the cursor
-
setCursorVisible
public void setCursorVisible(boolean visible) Description copied from interface:TerminalHides or shows the text cursor, but not all terminal (-emulators) supports this. The text cursor is normally a text block or an underscore, sometimes blinking, which shows the user where keyboard-entered text is supposed to show up.- Specified by:
setCursorVisiblein interfaceIOSafeTerminal- Specified by:
setCursorVisiblein interfaceTerminal- Parameters:
visible- Hides the text cursor iffalseand shows it iftrue
-
putCharacter
public void putCharacter(char c) Description copied from interface:TerminalPrints one character to the terminal at the current cursor location. Please note that the cursor will then move one column to the right, so multiple calls toputCharacterwill print out a text string without the need to reposition the text cursor. If you reach the end of the line while putting characters using this method, you can expect the text cursor to move to the beginning of the next line.You can output CJK (Chinese, Japanese, Korean) characters (as well as other regional scripts) but remember that the terminal that the user is using might not have the required font to render it. Also worth noticing is that CJK (and some others) characters tend to take up 2 columns per character, simply because they are a square in their construction as opposed to the somewhat rectangular shape we fit latin characters in. As it's very difficult to create a monospace font for CJK with a 2:1 height-width proportion, it seems like the implementers back in the days simply gave up and made each character take 2 column. It causes issues for the random terminal programmer because you can't really trust 1 character = 1 column, but I suppose it's "しょうがない". If you try to print non-printable control characters, the terminal is likely to ignore them (all
Terminalimplementations bundled with Lanterna will).- Specified by:
putCharacterin interfaceIOSafeTerminal- Specified by:
putCharacterin interfaceTerminal- Parameters:
c- Character to place on the terminal
-
putString
Description copied from interface:TerminalPrints a string to the terminal at the current cursor location. Please note that the cursor will then move one column to the right, so multiple calls toputStringwill print out a text string without the need to reposition the text cursor. If you reach the end of the line while putting characters using this method, you can expect the text cursor to move to the beginning of the next line.You can output CJK (Chinese, Japanese, Korean) characters (as well as other regional scripts) but remember that the terminal that the user is using might not have the required font to render it. Also worth noticing is that CJK (and some others) characters tend to take up 2 columns per character, simply because they are a square in their construction as opposed to the somewhat rectangular shape we fit latin characters in. As it's very difficult to create a monospace font for CJK with a 2:1 height-width proportion, it seems like the implementers back in the days simply gave up and made each character take 2 column. It causes issues for the random terminal programmer because you can't really trust 1 character = 1 column, but I suppose it's "しょうがない".
If you try to print non-printable control characters, the terminal is likely to ignore them (all
Terminalimplementations bundled with Lanterna will).You can use this method to place emoji characters on the terminal, since they take up more than one char with Java's built-in UTF16 encoding.
- Specified by:
putStringin interfaceIOSafeTerminal- Specified by:
putStringin interfaceTerminal- Parameters:
string- String to place on the terminal
-
newTextGraphics
Description copied from interface:TerminalCreates a new TextGraphics object that uses this Terminal directly when outputting. Keep in mind that you are probably better off to switch to a Screen to make advanced text graphics more efficient. Also, this TextGraphics implementation will not call.flush()after any operation, so you'll need to do that on your own.- Specified by:
newTextGraphicsin interfaceTerminal- Returns:
- TextGraphics implementation that draws directly using this Terminal interface
-
enableSGR
Description copied from interface:TerminalActivates anSGR(Selected Graphic Rendition) code. This code modifies a state inside the terminal that will apply to all characters written afterwards, such as bold, italic, blinking code and so on.- Specified by:
enableSGRin interfaceIOSafeTerminal- Specified by:
enableSGRin interfaceTerminal- Parameters:
sgr- SGR code to apply- See Also:
-
disableSGR
Description copied from interface:TerminalDeactivates anSGR(Selected Graphic Rendition) code which has previously been activated throughenableSGR(..).- Specified by:
disableSGRin interfaceIOSafeTerminal- Specified by:
disableSGRin interfaceTerminal- Parameters:
sgr- SGR code to apply- See Also:
-
resetColorAndSGR
public void resetColorAndSGR()Description copied from interface:TerminalRemoves all currently active SGR codes and sets foreground and background colors back to default.- Specified by:
resetColorAndSGRin interfaceIOSafeTerminal- Specified by:
resetColorAndSGRin interfaceTerminal- See Also:
-
setForegroundColor
Description copied from interface:TerminalChanges the foreground color for all the following characters put to the terminal. The foreground color is what color to draw the text in, as opposed to the background color which is the color surrounding the characters.This overload is using the TextColor class to define a color, which is a layer of abstraction above the three different color formats supported (ANSI, indexed and RGB). The other setForegroundColor(..) overloads gives you direct access to set one of those three.
Note to implementers of this interface, just make this method call color.applyAsForeground(this);
- Specified by:
setForegroundColorin interfaceIOSafeTerminal- Specified by:
setForegroundColorin interfaceTerminal- Parameters:
color- Color to use for foreground
-
setBackgroundColor
Description copied from interface:TerminalChanges the background color for all the following characters put to the terminal. The background color is the color surrounding the text being printed.This overload is using the TextColor class to define a color, which is a layer of abstraction above the three different color formats supported (ANSI, indexed and RGB). The other setBackgroundColor(..) overloads gives you direct access to set one of those three.
Note to implementers of this interface, just make this method call color.applyAsBackground(this);
- Specified by:
setBackgroundColorin interfaceIOSafeTerminal- Specified by:
setBackgroundColorin interfaceTerminal- Parameters:
color- Color to use for the background
-
getTerminalSize
Description copied from interface:TerminalReturns the size of the terminal, expressed as aTerminalSizeobject. Please bear in mind that depending on theTerminalimplementation, this may or may not be accurate. See the implementing classes for more information. Most commonly, calling getTerminalSize() will involve some kind of hack to retrieve the size of the terminal, like moving the cursor to position 5000x5000 and then read back the location, unless the terminal implementation has a more smooth way of getting this data. Keep this in mind and see if you can avoid calling this method too often. There is a helper class, SimpleTerminalResizeListener, that you can use to cache the size and update it only when resize events are received (which depends on if a resize is detectable, which they are not on all platforms).- Specified by:
getTerminalSizein interfaceIOSafeTerminal- Specified by:
getTerminalSizein interfaceTerminal- Returns:
- Size of the terminal
-
enquireTerminal
Description copied from interface:TerminalRetrieves optional information from the terminal by printing the ENQ (\u005) character. Terminals and terminal emulators may or may not respond to this command, sometimes it's configurable.- Specified by:
enquireTerminalin interfaceIOSafeTerminal- Specified by:
enquireTerminalin interfaceTerminal- Parameters:
timeout- How long to wait for the talk-back message, if there's nothing immediately available on the input stream, you should probably set this to a somewhat small value to prevent unnecessary blockage on the input stream but large enough to accommodate a round-trip to the user's terminal (~300 ms if you are connection across the globe).timeoutUnit- What unit to use when interpreting thetimeoutparameter- Returns:
- Answer-back message from the terminal or empty if there was nothing
-
bell
public void bell()Description copied from interface:TerminalPrints 0x7 to the terminal, which will make the terminal (emulator) ring a bell (or more likely beep). Not all terminals implements this. Wikipedia has more details.- Specified by:
bellin interfaceIOSafeTerminal- Specified by:
bellin interfaceTerminal
-
flush
public void flush()Description copied from interface:TerminalCallsflush()on the underlyingOutputStreamobject, or whatever other implementation this terminal is built around. Some implementing classes of this interface (like SwingTerminal) doesn't do anything as it doesn't really apply to them.- Specified by:
flushin interfaceIOSafeTerminal- Specified by:
flushin interfaceTerminal
-
close
public void close()Description copied from interface:TerminalCloses the terminal, if applicable. If the implementation doesn't support closing the terminal, this will do nothing. The Swing/AWT emulator implementations will translate this into a dispose() call on the UI resources, the telnet implementation will hang out the connection.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Specified by:
closein interfaceIOSafeTerminal- Specified by:
closein interfaceTerminal
-
addResizeListener
Description copied from interface:TerminalAdds aTerminalResizeListenerto be called when the terminal has changed size. There is no guarantee that this listener will really be invoked when the terminal has changed size, at all depends on the terminal emulator implementation. Normally on Unix systems the WINCH signal will be sent to the process and lanterna can intercept this.There are no guarantees on what thread the call will be made on, so please be careful with what kind of operation you perform in this callback. You should probably not take too long to return.
- Specified by:
addResizeListenerin interfaceTerminal- Parameters:
listener- Listener object to be called when the terminal has been changed- See Also:
-
removeResizeListener
Description copied from interface:TerminalRemoves aTerminalResizeListenerfrom the list of listeners to be notified when the terminal has changed size- Specified by:
removeResizeListenerin interfaceTerminal- Parameters:
listener- Listener object to remove- See Also:
-
pasteClipboardContent
private void pasteClipboardContent() -
pasteSelectionContent
private void pasteSelectionContent() -
injectStringAsKeyStrokes
-