Exemplo n.º 1
0
class OutputPane(object):
    
    """Pane for outpout of interactive session"""
    
    def __init__(self):
        self.textpane = JTextPane()
        self.doc = self.textpane.getStyledDocument()
        self.textpane.editable = False
        style_context = StyleContext.getDefaultStyleContext()
        default_style = style_context.getStyle(StyleContext.DEFAULT_STYLE)
        parent_style = self.doc.addStyle("parent", default_style)
        StyleConstants.setFontFamily(parent_style, "Monospaced")
        input_style = self.doc.addStyle("input", parent_style)
        output_style = self.doc.addStyle("output", parent_style)
        StyleConstants.setForeground(output_style, awtColor.BLUE)
        error_style = self.doc.addStyle("error", parent_style)
        StyleConstants.setForeground(error_style, awtColor.RED)
        
        # Do a dance to set tab size
        font = Font("Monospaced", Font.PLAIN, 12)
        self.textpane.setFont(font)
        fm = self.textpane.getFontMetrics(font)
        tabw = float(fm.stringWidth(" "*4))
        tabs = [
            TabStop(tabw*i, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE)
            for i in xrange(1, 51)
        ]
        attr_set = style_context.addAttribute(
            SimpleAttributeSet.EMPTY,
            StyleConstants.TabSet,
            TabSet(tabs)
        )
        self.textpane.setParagraphAttributes(attr_set, False)
        #Dance done!
        
    def addtext(self, text, style="input", ensure_newline=False):
        doclen = self.doc.length
        if ensure_newline and doclen:
            if self.doc.getText(doclen - 1, 1) != '\n':
                text = '\n' + text
        self.doc.insertString(self.doc.length, text, self.doc.getStyle(style))
        # Scroll down
        self.textpane.setCaretPosition(self.doc.length)

    def clear(self):
        """Remove all text"""
        self.doc.remove(0, self.doc.length)
Exemplo n.º 2
0
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]

    include_single_underscore_methods = False
    include_double_underscore_methods = False

    def __init__(self, namespace=None):
        """
            Create a Jython Console.
            namespace is an optional and should be a dictionary or Map
        """
        self.history = History(self)

        if namespace != None:
            self.locals = namespace
        else:
            self.locals = {}

        self.buffer = []  # buffer for multi-line commands

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        self.text_pane = JTextPane(keyTyped=self.keyTyped,
                                   keyPressed=self.keyPressed)
        self.__initKeyMap()

        self.doc = self.text_pane.document
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length - 1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.text_pane)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.text_pane.getFontMetrics(self.text_pane.getFont())
        self.dotWidth = metrics.charWidth('.')
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals['console'] = self

    def insertText(self, text):
        """insert text at the current caret position"""
        # seems like there should be a better way to do this....
        # might be better as a method on the text component?
        caretPosition = self.text_pane.getCaretPosition()
        self.text_pane.select(caretPosition, caretPosition)
        self.text_pane.replaceSelection(text)
        self.text_pane.setCaretPosition(caretPosition + len(text))

    def getText(self):
        """get text from last line of console"""
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1] - offsets[0])
        return text.rstrip()

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.text_pane.getLocationOnScreen()
        caretPoint = self.text_pane.caret.getMagicCaretPosition()

        # BUG: sometimes caretPoint is None
        # To duplicate type "java.aw" and hit '.' to complete selection while popup is visible

        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        self.insertText(')')

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()

        line = self.getText()

        self.insertText('(')

        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)

        if tip:
            self.tip.showTip(tip, displayPoint)

    def showPopup(self, event=None):
        """show code completion popup"""

        try:
            line = self.getText()
            list = jintrospect.getAutoCompleteList(
                line,
                self.locals,
                includeSingle=self.include_single_underscore_methods,
                includeDouble=self.include_double_underscore_methods)
            if len(list) > 0:
                self.popup.showMethodCompletionList(list,
                                                    self.getDisplayPoint())

        except Exception, e:
            print >> sys.stderr, "Error getting completion list: ", e
Exemplo n.º 3
0
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]
  
    include_single_underscore_methods = False
    include_double_underscore_methods = False

    def __init__(self, namespace=None):
        """
            Create a Jython Console.
            namespace is an optional and should be a dictionary or Map
        """
        self.history = History(self)

        if namespace != None:
            self.locals = namespace
        else:
            self.locals = {}

        self.buffer = [] # buffer for multi-line commands                    

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        self.text_pane = JTextPane(keyTyped = self.keyTyped, keyPressed = self.keyPressed)
        self.__initKeyMap()

        self.doc = self.text_pane.document
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length-1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.text_pane)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.text_pane.getFontMetrics(self.text_pane.getFont())
        self.dotWidth = metrics.charWidth('.')
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals['console'] = self

    def insertText(self, text):
        """insert text at the current caret position"""
        # seems like there should be a better way to do this....
        # might be better as a method on the text component?
        caretPosition = self.text_pane.getCaretPosition()
        self.text_pane.select(caretPosition, caretPosition)
        self.text_pane.replaceSelection(text)
        self.text_pane.setCaretPosition(caretPosition + len(text))

    def getText(self):
        """get text from last line of console"""
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1]-offsets[0])
        return text.rstrip()

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.text_pane.getLocationOnScreen()
        caretPoint = self.text_pane.caret.getMagicCaretPosition()

        # BUG: sometimes caretPoint is None
        # To duplicate type "java.aw" and hit '.' to complete selection while popup is visible

        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x),int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        self.insertText(')')

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()
        
        line = self.getText()

        self.insertText('(')
        
        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)

        if tip:
            self.tip.showTip(tip, displayPoint)
            
    def showPopup(self, event=None):
        """show code completion popup"""

        try:
            line = self.getText()
            list = jintrospect.getAutoCompleteList(line, self.locals, includeSingle=self.include_single_underscore_methods, includeDouble=self.include_double_underscore_methods)
            if len(list) > 0:
                self.popup.showMethodCompletionList(list, self.getDisplayPoint())

        except Exception, e:
            print >> sys.stderr, "Error getting completion list: ", e
Exemplo n.º 4
0
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]

    def __init__(self, frame):

        self.frame = frame  # TODO do I need a reference to frame after the constructor?
        self.history = History(self)
        self.bs = 0  # what is this?

        # command buffer
        self.buffer = []
        self.locals = {"gvSIG": sys.gvSIG}

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        # create a textpane
        self.output = JTextPane(keyTyped=self.keyTyped, keyPressed=self.keyPressed)
        # TODO rename output to textpane

        # CTRL UP AND DOWN don't work
        keyBindings = [
            (KeyEvent.VK_ENTER, 0, "jython.enter", self.enter),
            (KeyEvent.VK_DELETE, 0, "jython.delete", self.delete),
            (KeyEvent.VK_HOME, 0, "jython.home", self.home),
            (KeyEvent.VK_UP, 0, "jython.up", self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, "jython.down", self.history.historyDown),
            (KeyEvent.VK_PERIOD, 0, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_ESCAPE, 0, "jython.hide", self.hide),
            ("(", 0, "jython.showTip", self.showTip),
            (")", 0, "jython.hideTip", self.hideTip),
            # (KeyEvent.VK_UP, InputEvent.CTRL_MASK, DefaultEditorKit.upAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0))),
            # (KeyEvent.VK_DOWN, InputEvent.CTRL_MASK, DefaultEditorKit.downAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)))
        ]
        # TODO rename newmap to keymap
        newmap = JTextComponent.addKeymap("jython", self.output.keymap)
        for (key, modifier, name, function) in keyBindings:
            newmap.addActionForKeyStroke(KeyStroke.getKeyStroke(key, modifier), ActionDelegator(name, function))

        self.output.keymap = newmap

        self.doc = self.output.document
        # self.panel.add(BorderLayout.CENTER, JScrollPane(self.output))
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length - 1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.output)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.output.getFontMetrics(self.output.getFont())
        self.dotWidth = metrics.charWidth(".")
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals["console"] = self

        self.caret = self.output.getCaret()

    # TODO refactor me
    def getinput(self):
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1] - offsets[0])
        return text

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.output.getLocationOnScreen()
        caretPoint = self.output.caret.getMagicCaretPosition()

        # TODO use SwingUtils to do this translation
        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        # TODO this needs to insert ')' at caret!
        self.write(")")

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()

        line = self.getinput()
        # debug("line", line)
        # Hack 'o rama
        line = line[:-1]  # remove \n
        line += "("
        # debug("line", line)

        # TODO this needs to insert '(' at caret!
        self.write("(")

        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)
        # debug("name", name)
        # debug("argspec", argspec)
        # debug("tip", tip)

        if tip:
            self.tip.setLocation(displayPoint)
            self.tip.setText(tip)
            self.tip.show()

    def showPopup(self, event=None):

        line = self.getinput()
        # this is silly, I have to add the '.' and the other code removes it.
        line = line[:-1]  # remove \n
        line = line + "."
        # print >> sys.stderr, "line:",line

        # TODO get this code into Popup
        # TODO handle errors gracefully
        try:
            list = jintrospect.getAutoCompleteList(line, self.locals)
        except Exception, e:
            # TODO handle this gracefully
            print >>sys.stderr, e
            return

        if len(list) == 0:
            # print >> sys.stderr, "list was empty"
            return

        self.popup.setLocation(self.getDisplayPoint())

        self.popup.setMethods(list)
        self.popup.show()
        self.popup.list.setSelectedIndex(0)
Exemplo n.º 5
0
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]

    def __init__(self, frame):

        self.frame = frame  # TODO do I need a reference to frame after the constructor?
        self.history = History(self)
        self.bs = 0  # what is this?

        # command buffer
        self.buffer = []
        self.locals = {"gvSIG": sys.gvSIG}

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        # create a textpane
        self.output = JTextPane(keyTyped=self.keyTyped,
                                keyPressed=self.keyPressed)
        # TODO rename output to textpane

        # CTRL UP AND DOWN don't work
        keyBindings = [
            (KeyEvent.VK_ENTER, 0, "jython.enter", self.enter),
            (KeyEvent.VK_DELETE, 0, "jython.delete", self.delete),
            (KeyEvent.VK_HOME, 0, "jython.home", self.home),
            (KeyEvent.VK_UP, 0, "jython.up", self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, "jython.down", self.history.historyDown),
            (KeyEvent.VK_PERIOD, 0, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_ESCAPE, 0, "jython.hide", self.hide),
            ('(', 0, "jython.showTip", self.showTip),
            (')', 0, "jython.hideTip", self.hideTip),

            #(KeyEvent.VK_UP, InputEvent.CTRL_MASK, DefaultEditorKit.upAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0))),
            #(KeyEvent.VK_DOWN, InputEvent.CTRL_MASK, DefaultEditorKit.downAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)))
        ]
        # TODO rename newmap to keymap
        newmap = JTextComponent.addKeymap("jython", self.output.keymap)
        for (key, modifier, name, function) in keyBindings:
            newmap.addActionForKeyStroke(KeyStroke.getKeyStroke(key, modifier),
                                         ActionDelegator(name, function))

        self.output.keymap = newmap

        self.doc = self.output.document
        #self.panel.add(BorderLayout.CENTER, JScrollPane(self.output))
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length - 1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.output)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.output.getFontMetrics(self.output.getFont())
        self.dotWidth = metrics.charWidth('.')
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals['console'] = self

        self.caret = self.output.getCaret()

    # TODO refactor me
    def getinput(self):
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1] - offsets[0])
        return text

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.output.getLocationOnScreen()
        caretPoint = self.output.caret.getMagicCaretPosition()

        # TODO use SwingUtils to do this translation
        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        # TODO this needs to insert ')' at caret!
        self.write(')')

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()

        line = self.getinput()
        #debug("line", line)
        # Hack 'o rama
        line = line[:-1]  # remove \n
        line += '('
        #debug("line", line)

        # TODO this needs to insert '(' at caret!
        self.write('(')

        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)
        #debug("name", name)
        #debug("argspec", argspec)
        #debug("tip", tip)

        if tip:
            self.tip.setLocation(displayPoint)
            self.tip.setText(tip)
            self.tip.show()

    def showPopup(self, event=None):

        line = self.getinput()
        # this is silly, I have to add the '.' and the other code removes it.
        line = line[:-1]  # remove \n
        line = line + '.'
        #print >> sys.stderr, "line:",line

        # TODO get this code into Popup
        # TODO handle errors gracefully
        try:
            list = jintrospect.getAutoCompleteList(line, self.locals)
        except Exception, e:
            # TODO handle this gracefully
            print >> sys.stderr, e
            return

        if len(list) == 0:
            #print >> sys.stderr, "list was empty"
            return

        self.popup.setLocation(self.getDisplayPoint())

        self.popup.setMethods(list)
        self.popup.show()
        self.popup.list.setSelectedIndex(0)