org.gjt.btools.gui.component
Class ConsolePane

java.lang.Object
  |
  +--java.awt.Component
        |
        +--java.awt.Container
              |
              +--javax.swing.JComponent
                    |
                    +--javax.swing.text.JTextComponent
                          |
                          +--javax.swing.JEditorPane
                                |
                                +--javax.swing.JTextPane
                                      |
                                      +--org.gjt.btools.gui.component.ConsolePane
All Implemented Interfaces:
javax.accessibility.Accessible, java.awt.image.ImageObserver, java.awt.MenuContainer, javax.swing.Scrollable, java.io.Serializable
Direct Known Subclasses:
EchoConsole

public abstract class ConsolePane
extends javax.swing.JTextPane

Component that provides a text I/O console with advanced line editing and various other intelligent features. The user enters input one line at a time. The console will process each line as it is received and produce any corresponding output if required. Thus interaction with the console runs on a line-in, line-out cycle. If multiple lines are entered at once (such as if a paste operation is performed), the input will be separated into individual lines and processed and displayed as if the individual lines had been entered in turn.

The actual details of the processing required are left to subclasses of ConsolePane, which are required to implement the abstract method processInput(). Processing will be done in a separate thread, so if processing is slow then any intermediate output will be displayed to the console as it is produced. Routine preProcess() can also be overridden to do preliminary processing when the console is first started.

Before the console is offered to the user for interaction, startConsole() must be called. When the console is ready to receive input from the user, it is said to be in input mode. When it is processing a line of input and producing the corresponding output it is said to be not in input mode. Once startConsole() has been called, the console will be in input mode ready for its first input line.

Note that output may be sent to the console before it is started.

The console should never be closed while processing is still taking place! The recommended solution is to catch the frame close event and notify the user with an error if isProcessing() indicates that processing is still happening.

When processing starts and stops, a property change event will be fired for property "processing".

See Also:
processInput(java.lang.String), preProcess(), startConsole(), startConsole(java.lang.String), isProcessing(), Serialized Form

Field Summary
static java.lang.String DEFAULT_PROMPT
          The default prompt to present to the user each time input is required.
static java.lang.String TAB_EXPANSION
          The string of spaces that a tab expands to.
 
Fields inherited from class javax.swing.JEditorPane
 
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Container
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
ConsolePane()
          Creates a new console.
 
Method Summary
 void cancelProcessing()
          Cancel any current input processing that is taking place.
 javax.swing.text.AttributeSet getConsoleInputAttributes()
          Returns the attributes used for displaying user input.
 javax.swing.text.AttributeSet getConsoleOutputAttributes()
          Returns the attributes used for displaying console output.
 javax.swing.text.AttributeSet getConsolePromptAttributes()
          Returns the attributes used for displaying the console prompt.
 java.io.OutputStream getOutputStream()
          Returns an output stream that writes output to the console.
 java.lang.String getPrompt()
          Returns the prompt to be presented to the user each time input is required.
protected  void internalCancelProcessing(java.lang.Thread t)
          Calls any custom code needed to cancel input processing.
 boolean isInputEnabled()
          Returns whether the console is currently enabled for user input.
 boolean isProcessing()
          Is this console currently processing user input?
 boolean isProcessingCancelled()
          Has the input processing been cancelled?
 void oops()
          Notifies the user that an illegal action has been attempted.
 void outputLine()
          Outputs a blank line to the console.
 void outputLine(java.lang.String line)
          Outputs the given line to the console.
 void outputMessage(java.lang.String message)
          Outputs the given message to the console.
protected  void preProcess()
          Does any preliminary processing required before the console is started.
protected abstract  java.lang.String processInput(java.lang.String line)
          Processes the given line of input and produces whatever corresponding output is required.
 void sendInputLine(java.lang.String line)
          Erases any text currently on the input line, places the given string there instead and then processes the input as if return had been pressed.
 void setConsoleInputAttributes(javax.swing.text.AttributeSet set)
          Sets the attributes to be used for displaying user input.
 void setConsoleOutputAttributes(javax.swing.text.AttributeSet set)
          Sets the attributes to be used for displaying console output.
 void setConsolePromptAttributes(javax.swing.text.AttributeSet set)
          Sets the attributes to be used for displaying the console prompt.
 void setInputEnabled(boolean enabled)
          Enables or disables input to the console.
 void setPrompt(java.lang.String prompt)
          Sets the prompt to be presented to the user each time input is required.
 void startConsole()
          Readies the console for action.
 void startConsole(java.lang.String greeting)
          Readies the console for action.
 void waitForProcessing()
          Causes this thread to wait until input processing is finished.
 void writeContentsToFile(java.io.File file)
          Writes the entire contents of this console, up to but not including the current input prompt, to the given file.
 
Methods inherited from class javax.swing.JTextPane
addStyle, createDefaultEditorKit, getCharacterAttributes, getInputAttributes, getLogicalStyle, getParagraphAttributes, getStyle, getStyledDocument, getStyledEditorKit, getUIClassID, insertComponent, insertIcon, paramString, removeStyle, replaceSelection, setCharacterAttributes, setDocument, setEditorKit, setLogicalStyle, setParagraphAttributes, setStyledDocument
 
Methods inherited from class javax.swing.JEditorPane
addHyperlinkListener, createEditorKitForContentType, fireHyperlinkUpdate, getAccessibleContext, getContentType, getEditorKit, getEditorKitClassNameForContentType, getEditorKitForContentType, getHyperlinkListeners, getPage, getPreferredSize, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getStream, getText, read, registerEditorKitForContentType, registerEditorKitForContentType, removeHyperlinkListener, scrollToReference, setContentType, setEditorKitForContentType, setPage, setPage, setText
 
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getScrollableBlockIncrement, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, write
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_PROMPT

public static final java.lang.String DEFAULT_PROMPT
The default prompt to present to the user each time input is required.

See Also:
Constant Field Values

TAB_EXPANSION

public static final java.lang.String TAB_EXPANSION
The string of spaces that a tab expands to.

See Also:
Constant Field Values
Constructor Detail

ConsolePane

public ConsolePane()
Creates a new console. Note that you must call startConsole() before the console is offered to the user for interaction!

See Also:
startConsole(), startConsole(java.lang.String)
Method Detail

startConsole

public void startConsole()
Readies the console for action. The first prompt will be displayed and the console will be enabled for input and put in input mode.

Before any of this is done, preProcess() will be called to do any required preliminary processing.

See Also:
preProcess()

startConsole

public void startConsole(java.lang.String greeting)
Readies the console for action. The given greeting will be displayed followed by the first prompt. The console will be enabled for input and put in input mode. If the given greeting is null, no greeting will be displayed.

Before any of this is done, preProcess() will be called to do any required preliminary processing.

Parameters:
greeting - the greeting to present; this should include a final newline.
See Also:
preProcess()

getPrompt

public java.lang.String getPrompt()
Returns the prompt to be presented to the user each time input is required.

Returns:
the current prompt.

setPrompt

public void setPrompt(java.lang.String prompt)
Sets the prompt to be presented to the user each time input is required. This will only affect future inputs; prompts that have already been displayed will not be changed. If this routine is not called, a reasonable default will be provided.

Parameters:
prompt - the new prompt to use.

isInputEnabled

public boolean isInputEnabled()
Returns whether the console is currently enabled for user input. Input will be enabled by default. Disabling input allows the user to still browse through the console history, copy to the clipboard and so on, but no new input can be given.

Returns:
true if and only if input is enabled.

setInputEnabled

public void setInputEnabled(boolean enabled)
Enables or disables input to the console. Disabling input allows the user to still browse through the console history, copy to the clipboard and so on, but no new input can be given.

Parameters:
enabled - true to enable input or false to disable input.

getConsoleInputAttributes

public javax.swing.text.AttributeSet getConsoleInputAttributes()
Returns the attributes used for displaying user input.

Returns:
the attributes used to display user input.

setConsoleInputAttributes

public void setConsoleInputAttributes(javax.swing.text.AttributeSet set)
Sets the attributes to be used for displaying user input. Text that has already been displayed will not be changed. If this routine is not called, a reasonable default is provided.

Parameters:
set - the new attribute set to use.

getConsoleOutputAttributes

public javax.swing.text.AttributeSet getConsoleOutputAttributes()
Returns the attributes used for displaying console output.

Returns:
the attributes used to display console output.

setConsoleOutputAttributes

public void setConsoleOutputAttributes(javax.swing.text.AttributeSet set)
Sets the attributes to be used for displaying console output. Text that has already been displayed will not be changed. If this routine is not called, a reasonable default is provided.

Parameters:
set - the new attribute set to use.

getConsolePromptAttributes

public javax.swing.text.AttributeSet getConsolePromptAttributes()
Returns the attributes used for displaying the console prompt.

Returns:
the attributes used to display the console prompt.

setConsolePromptAttributes

public void setConsolePromptAttributes(javax.swing.text.AttributeSet set)
Sets the attributes to be used for displaying the console prompt. Text that has already been displayed will not be changed. If this routine is not called, a reasonable default is provided.

Parameters:
set - the new attribute set to use.

outputLine

public void outputLine()
Outputs a blank line to the console.

Precondition: The console is not currently in input mode.


outputLine

public void outputLine(java.lang.String line)
Outputs the given line to the console.

Precondition: The console is not currently in input mode.

Parameters:
line - the line to output; this should not include a final newline.

outputMessage

public void outputMessage(java.lang.String message)
Outputs the given message to the console. No addition newline will be appended to the given message. The caller of this routine is advised to ensure a newline is already present.

This is the routine that actually does the work of outputting a message; all other outputting routines end up calling this routine.

Precondition: The console is not currently in input mode.

Parameters:
message - the message to output.

sendInputLine

public void sendInputLine(java.lang.String line)
Erases any text currently on the input line, places the given string there instead and then processes the input as if return had been pressed.

Precondition: The console is currently in input mode.
Precondition: The given string contains no newlines.

Parameters:
line - the line of input to display and process.

processInput

protected abstract java.lang.String processInput(java.lang.String line)
Processes the given line of input and produces whatever corresponding output is required. Output can be sent to the output stream returned by getOutputStream(), in which case it will be sent directly to the console output. Furthermore, any string returned by this routine will also be sent to the console output. This returned string may be null, in which case no extra string will be output.

Processing will be done in a separate thread, so if processing is slow then any intermediate output will be displayed to the console as it is produced.

If processing is time consuming, this routine should regularly check isProcessingCancelled() to see if the user has cancelled the processing. If so, this routine should exit as soon as possible, possibly with an appropriate error message. If isProcessingCancelled() cannot be regularly checked (such as when processing is done in exteral libraries or native routines), see internalCancelProcessing() for details on what else can be done to ensure prompt cancellation.

This routine is advised to ensure that a final newline is output.

Precondition: The console is not currently in input mode.

Parameters:
line - the single line of input to process.
Returns:
any additional text to output that has not already been written to the console during this routine.
See Also:
isProcessingCancelled(), internalCancelProcessing(java.lang.Thread), processInput(java.lang.String)

preProcess

protected void preProcess()
Does any preliminary processing required before the console is started. This routine should behave similarly to processInput() and will also be run in a separate thread.

The default implementation does nothing; subclasses may override this routine to do whatever preliminary processing is necessary.

Precondition: The console has not yet been started.

See Also:
processInput(java.lang.String)

getOutputStream

public java.io.OutputStream getOutputStream()
Returns an output stream that writes output to the console. Calling this routine multiple times will return the same output stream.

Precondition: This output stream is not used while the console is in input mode.

Returns:
an output stream associated with this console.

oops

public void oops()
Notifies the user that an illegal action has been attempted.


writeContentsToFile

public void writeContentsToFile(java.io.File file)
                         throws java.io.IOException
Writes the entire contents of this console, up to but not including the current input prompt, to the given file.

Parameters:
file - the file to which to write.
Throws:
java.io.IOException - thrown if an I/O error occurs, in which case this routine will attempt to close the file before throwing the exception.

isProcessing

public final boolean isProcessing()
Is this console currently processing user input? When processing starts and stops, a property change event will be fired for property "processing".

Returns:
true if and only if this console is currently processing user input.

waitForProcessing

public final void waitForProcessing()
Causes this thread to wait until input processing is finished. If this console is not currently processing user input, this routine returns immediately.


cancelProcessing

public final void cancelProcessing()
Cancel any current input processing that is taking place. If no processing is taking place, this routine will do nothing. Otherwise the processing will be cancelled and a new input prompt will be presented. #see isProcessingCancelled


isProcessingCancelled

public final boolean isProcessingCancelled()
Has the input processing been cancelled? Note that processing is cancelled through the use of cancelProcessing().

Returns:
true if and only if input processing is still taking place and the user has requested that the processing be cancelled.
See Also:
cancelProcessing()

internalCancelProcessing

protected void internalCancelProcessing(java.lang.Thread t)
Calls any custom code needed to cancel input processing. This will be called from inside cancelProcessing() if there is any processing actually taking place.

Generally this routine should do nothing; the processing routine should instead call isProcessingCancelled() regularly and exit if appropriate. However, if large amounts of processing are done in external libraries or native routines, you will need some way to ask these external routines to stop. This can be done by overriding internalCancelProcessing() to take whatever additional action is necessary.

The default implementation of this routine does nothing, and in most cases that should be sufficient.

Parameters:
t - the thread in which input processing is taking place. This thread should not simply be killed; it does important cleaning up for the console after processing is done.


Copyright © 1998-2001, Ben Burton
This software is released under the GNU Public License.
For further information, or to submit a bug or other problem, please contact Ben Burton (bab@debian.org).