edu.wisc.ssec.mcidasv.jython
Class Console

java.lang.Object
  extended by edu.wisc.ssec.mcidasv.jython.Console
All Implemented Interfaces:
KeyListener, Runnable, EventListener

public class Console
extends Object
implements Runnable, KeyListener


Nested Class Summary
static class Console.Actions
          Maps a "jython action" to a keystroke.
static class Console.HistoryEntry
           
static class Console.HistoryType
           
private  class Console.PopupListener
           
 
Field Summary
private static int[] BAD_OFFSETS
          Offset array used when actual offsets cannot be determined.
private static String BANNER
          Not used yet.
private  ConsoleCallback callback
          A hook that allows external classes to respond to events.
private  Document document
          textPane's internal representation.
private static Font FONT
          All text will appear in this font.
private  List<String> jythonHistory
          Jython statements entered by the user.
private  Runner jythonRunner
          Thread that handles Jython command execution.
private static org.slf4j.Logger logger
          Logger object for Jython consoles.
private  MenuWrangler menuWrangler
           
private  JPanel panel
          Panel that holds textPane.
private static String PS1
          Normal jython prompt.
private static String PS2
          Prompt that indicates more input is needed.
private  JTextPane textPane
          Where the user interacts with the Jython interpreter.
protected static Color TXT_ERROR
          Color of text coming from "stderr".
protected static Color TXT_GOOD
          Color of text coming from "stdout".
protected static Color TXT_NORMAL
          Color of the Jython text as it is being entered.
protected static Color TXT_WARN
          Not used just yet...
private static String WHITESPACE
          Actual String of whitespace to insert for blocks and whatnot.
private  String windowTitle
          Title of the console window.
 
Constructor Summary
Console()
          Build a console with no initial commands.
Console(List<String> initialCommands)
          Builds a console and executes a list of Jython statements.
 
Method Summary
 void addPretendHistory(String line)
           
private  boolean canInsertAt(int position)
          Determines whether or not position is an acceptable place to insert text.
 void ejectObject(org.python.core.PyObject pyObject)
           
 void ejectObjectByName(String name)
           
protected  void endln(Color color)
          Inserts a newline character at the end of the input.
 void error(String text)
          Displays an error.
 void generatedError(String text)
          Displays error output.
 void generatedOutput(String text)
          Displays non-error output that was not the result of an "associated" Command.
static int getBlockDepth(String line, String whitespace)
          Returns the "block depth" of a given line of Jython.
 int getCaretLine()
           
 List<String> getHistory()
          Returns the Jython statements as entered by the user, ordered from first to last.
 Map<String,Object> getJavaInstances()
          Returns a subset of Jython's local namespace containing only variables that are "pure" Java objects.
 org.python.core.PyObject getJythonObject(String var)
          Retrieves the specified Jython variable from the interpreters local namespace.
 Set<String> getJythonReferencesTo(Object obj)
           
 int getLineCount()
           
 String getLineJython(int lineNumber)
          Returns the line of Jython that occupies a specified line number.
 int getLineOffsetEnd(int lineNumber)
           
 int[] getLineOffsets(int lineNumber)
           
 int getLineOffsetStart(int lineNumber)
           
 String getLineText(int lineNumber)
          Returns the line of text that occupies the specified line number.
 Map<String,org.python.core.PyObject> getLocalNamespace()
          Returns a copy of Jython's local namespace.
 int getOffsetLine(int offset)
          Returns the line number that contains the specified offset.
 JPanel getPanel()
          Returns the panel containing the various UI components.
static int getPromptLength(String line)
          Returns the length of PS1 or PS2 depending on the contents of the specified line.
protected  JTextPane getTextPane()
          Returns the JTextPane used by the console.
static String getUserPath(String[] args)
           
 void handleDelete()
           
 void handleDown()
           
 void handleEnd()
          Moves the caret to the end of the line it is currently on, rather than the end of the document.
 void handleEnter()
          Handles the user pressing enter by basically grabbing the line of jython under the caret.
 void handleHome()
          Handles the user hitting the Home key.
 void handlePaste()
           
 void handleTab()
          Inserts the contents of WHITESPACE wherever the cursor is located.
 void handleUp()
           
private static boolean hasAction(JTextPane jtp, KeyEvent e)
           
 void injectObject(String name, Object object)
          Inserts the specified object into Jython's local namespace using the specified name.
protected  void insert(Color color, String text)
          Does the actual work of displaying color-coded messages in textPane.
protected  void insertAtCaret(Color color, String text)
           
 void keyPressed(KeyEvent e)
          Noop.
 void keyReleased(KeyEvent e)
          Noop.
 void keyTyped(KeyEvent e)
           
private  int[] locateLastLine()
          Returns the offsets of the beginning and end of the last line.
static void main(String[] args)
           
 void moreInput()
          Shows the prompt that indicates more input is needed.
 void moreInput(int blockLevel)
           
private  boolean onLastLine()
          Determines whether or not the caret is on the last line.
 void prompt()
          Shows the normal Jython prompt.
 void queueBatch(String name, List<String> commands)
          Sends a batch of Jython commands to the interpreter.
 void queueLine(String line)
          Sends a line of Jython to the interpreter via jythonRunner and saves it to the history.
 void result(String text)
          Displays non-error output.
 void run()
          Puts together the GUI once EventQueue has processed all other pending events.
 void runFile(String name, String path)
          Runs the file specified by path in the Interpreter.
 void setCallbackHandler(ConsoleCallback newHandler)
          Registers a new callback handler with the console.
private  void showBanner()
          Will eventually display an initial greeting to the user.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

TXT_NORMAL

protected static final Color TXT_NORMAL
Color of the Jython text as it is being entered.


TXT_GOOD

protected static final Color TXT_GOOD
Color of text coming from "stdout".


TXT_WARN

protected static final Color TXT_WARN
Not used just yet...


TXT_ERROR

protected static final Color TXT_ERROR
Color of text coming from "stderr".


logger

private static final org.slf4j.Logger logger
Logger object for Jython consoles.


BAD_OFFSETS

private static final int[] BAD_OFFSETS
Offset array used when actual offsets cannot be determined.


PS1

private static final String PS1
Normal jython prompt.

See Also:
Constant Field Values

PS2

private static final String PS2
Prompt that indicates more input is needed.

See Also:
Constant Field Values

WHITESPACE

private static final String WHITESPACE
Actual String of whitespace to insert for blocks and whatnot.

See Also:
Constant Field Values

BANNER

private static final String BANNER
Not used yet.


FONT

private static final Font FONT
All text will appear in this font.


jythonHistory

private final List<String> jythonHistory
Jython statements entered by the user.


jythonRunner

private Runner jythonRunner
Thread that handles Jython command execution.


callback

private ConsoleCallback callback
A hook that allows external classes to respond to events.


textPane

private JTextPane textPane
Where the user interacts with the Jython interpreter.


document

private Document document
textPane's internal representation.


panel

private JPanel panel
Panel that holds textPane.


windowTitle

private String windowTitle
Title of the console window.


menuWrangler

private MenuWrangler menuWrangler
Constructor Detail

Console

public Console()
Build a console with no initial commands.


Console

public Console(List<String> initialCommands)
Builds a console and executes a list of Jython statements. It's been useful for dirty tricks needed during setup.

Parameters:
initialCommands - Jython statements to execute.
Method Detail

getPanel

public JPanel getPanel()
Returns the panel containing the various UI components.


getTextPane

protected JTextPane getTextPane()
Returns the JTextPane used by the console.


injectObject

public void injectObject(String name,
                         Object object)
Inserts the specified object into Jython's local namespace using the specified name.

Example:
console.injectObject("test", new PyJavaInstance("a test"))
Allows the interpreter to refer to the String "a test" as test.

Parameters:
name - Object name as it will appear within the interpreter.
object - Object to place in the interpreter's local namespace.

ejectObjectByName

public void ejectObjectByName(String name)

ejectObject

public void ejectObject(org.python.core.PyObject pyObject)

runFile

public void runFile(String name,
                    String path)
Runs the file specified by path in the Interpreter.

Parameters:
name - __name__ attribute to use for loading path.
path - The path to the Jython file.

result

public void result(String text)
Displays non-error output.

Parameters:
text - The message to display.

error

public void error(String text)
Displays an error.

Parameters:
text - The error message.

prompt

public void prompt()
Shows the normal Jython prompt.


generatedOutput

public void generatedOutput(String text)
Displays non-error output that was not the result of an "associated" Command.

Parameters:
text - The text to display.
See Also:
generatedError(String)

generatedError

public void generatedError(String text)
Displays error output. Differs from error(String) in that this is intended for output not "associated" with a Command.

Example: say you fire off a background thread. If it generates an error somehow, this is the method you want.

Parameters:
text - The error message.

moreInput

public void moreInput()
Shows the prompt that indicates more input is needed.


moreInput

public void moreInput(int blockLevel)

showBanner

private void showBanner()
                 throws BadLocationException
Will eventually display an initial greeting to the user.

Throws:
BadLocationException - Upon attempting to clear out an invalid portion of the document.

endln

protected void endln(Color color)
Inserts a newline character at the end of the input.

Parameters:
color - Perhaps this should go!?

insert

protected void insert(Color color,
                      String text)
Does the actual work of displaying color-coded messages in textPane.

Parameters:
color - The color of the message.
text - The actual message.

insertAtCaret

protected void insertAtCaret(Color color,
                             String text)

canInsertAt

private boolean canInsertAt(int position)
Determines whether or not position is an acceptable place to insert text. Currently the criteria for "acceptable" means that position is located within the last (or active) line, and not within either PS1 or PS2.

Parameters:
position - Position to test. Values less than zero are not allowed.
Returns:
Whether or not text can be inserted at position.

getLineCount

public int getLineCount()
Returns:
Number of lines in the document.

getLineOffsetStart

public int getLineOffsetStart(int lineNumber)

getLineOffsetEnd

public int getLineOffsetEnd(int lineNumber)

getLineOffsets

public int[] getLineOffsets(int lineNumber)

getOffsetLine

public int getOffsetLine(int offset)
Returns the line number that contains the specified offset.

Parameters:
offset - Offset whose line number you want.
Returns:
Line number.

locateLastLine

private int[] locateLastLine()
Returns the offsets of the beginning and end of the last line.


onLastLine

private boolean onLastLine()
Determines whether or not the caret is on the last line.


getCaretLine

public int getCaretLine()
Returns:
The line number of the caret's offset within the text.

getLineText

public String getLineText(int lineNumber)
Returns the line of text that occupies the specified line number.

Parameters:
lineNumber - Line number whose text is to be returned.
Returns:
Either the line of text or null if there was an error.

getLineJython

public String getLineJython(int lineNumber)
Returns the line of Jython that occupies a specified line number. This is different than getLineText(int) in that both PS1 and PS2 are removed from the returned line.

Parameters:
lineNumber - Line number whose text is to be returned.
Returns:
Either the line of Jython or null if there was an error.

getPromptLength

public static int getPromptLength(String line)
Returns the length of PS1 or PS2 depending on the contents of the specified line.

Parameters:
line - The line in question. Cannot be null.
Returns:
Either the prompt length or zero if there was none.
Throws:
NullPointerException - if line is null.

getBlockDepth

public static int getBlockDepth(String line,
                                String whitespace)
Returns the "block depth" of a given line of Jython.

Examples:

 "print 'x'"         -> 0
 "    print 'x'"     -> 1
 "            die()" -> 3
 

Parameters:
line - Line to test. Can't be null.
whitespace - The indent String used with line. Can't be null.
Returns:
Either the block depth (>= 0) or -1 if there was an error.

setCallbackHandler

public void setCallbackHandler(ConsoleCallback newHandler)
Registers a new callback handler with the console. Note that to maximize utility, this method also registers the same handler with jythonRunner.

Parameters:
newHandler - The new callback handler.
Throws:
NullPointerException - if the new handler is null.

getJythonReferencesTo

public Set<String> getJythonReferencesTo(Object obj)

getJavaInstances

public Map<String,Object> getJavaInstances()
Returns a subset of Jython's local namespace containing only variables that are "pure" Java objects.

Returns:
Jython variable names mapped to their Java instantiation.

getJythonObject

public org.python.core.PyObject getJythonObject(String var)
Retrieves the specified Jython variable from the interpreters local namespace.

Parameters:
var - Variable name to retrieve.
Returns:
Either the variable or null. Note that null will also be returned if Runner.copyLocals() returned null.

getLocalNamespace

public Map<String,org.python.core.PyObject> getLocalNamespace()
Returns a copy of Jython's local namespace.

Returns:
Jython variable names mapped to PyObjects.

handlePaste

public void handlePaste()

handleHome

public void handleHome()
Handles the user hitting the Home key. If the caret is on a line that begins with either PS1 or PS2, the caret will be moved to just after the prompt. This is done mostly to emulate CPython's IDLE.


handleEnd

public void handleEnd()
Moves the caret to the end of the line it is currently on, rather than the end of the document.


handleUp

public void handleUp()

handleDown

public void handleDown()

handleTab

public void handleTab()
Inserts the contents of WHITESPACE wherever the cursor is located.


handleDelete

public void handleDelete()

handleEnter

public void handleEnter()
Handles the user pressing enter by basically grabbing the line of jython under the caret. If the caret is on the last line, the line is queued for execution. Otherwise the line is reinserted at the end of the document--this lets the user preview a previous command before they rerun it.


getHistory

public List<String> getHistory()
Returns the Jython statements as entered by the user, ordered from first to last.

Returns:
User's history.

queueLine

public void queueLine(String line)
Sends a line of Jython to the interpreter via jythonRunner and saves it to the history.

Parameters:
line - Jython to queue for execution.

queueBatch

public void queueBatch(String name,
                       List<String> commands)
Sends a batch of Jython commands to the interpreter. This is different than simply calling queueLine(String) for each command; the interpreter will attempt to execute each batched command before returning "control" to the console.

This method is mostly useful for restoring Console sessions. Each command in commands will appear in the console as though the user typed it. The batch of commands will also be saved to the history.

Parameters:
name - Identifier for the batch. Doesn't need to be unique, merely non-null.
commands - The commands to execute.

addPretendHistory

public void addPretendHistory(String line)

run

public void run()
Puts together the GUI once EventQueue has processed all other pending events.

Specified by:
run in interface Runnable

keyPressed

public void keyPressed(KeyEvent e)
Noop.

Specified by:
keyPressed in interface KeyListener

keyReleased

public void keyReleased(KeyEvent e)
Noop.

Specified by:
keyReleased in interface KeyListener

keyTyped

public void keyTyped(KeyEvent e)
Specified by:
keyTyped in interface KeyListener

hasAction

private static boolean hasAction(JTextPane jtp,
                                 KeyEvent e)

getUserPath

public static String getUserPath(String[] args)

main

public static void main(String[] args)