class ReportByPointPanelReport(FormPanel): def __init__(self): FormPanel.__init__( self, gvsig.getResource(__file__, "reportbypointpanelreport.xml")) i18Swing = ToolsSwingLocator.getToolsSwingManager() self.setPreferredSize(400, 300) self.txt = JTextPane() self.txt.setEditable(False) self.txt.setCaretPosition(0) i18Swing.setDefaultPopupMenu(self.txt) self.txt.setContentType("text/html") self.pane = JScrollPane(self.txt) #self.setInitHorizontalScroll() self.pane.setVerticalScrollBarPolicy( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) #self.setInitHorizontalScroll() #self.pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) #self.setInitHorizontalScroll() self.jplReport.setLayout(BorderLayout()) self.jplReport.add(self.pane, BorderLayout.CENTER) self.setInitHorizontalScroll() def setHTMLText(self, text): self.txt.setText(text) self.setInitHorizontalScroll() self.txt.setCaretPosition(0) def setInitHorizontalScroll(self): self.pane.getHorizontalScrollBar().setValue(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)
class OutputPane(object): def __init__(self): self.textpane = JTextPane() self.doc = self.textpane.getStyledDocument() self.textpane.editable = False default_style = StyleContext.getDefaultStyleContext().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, Color.BLUE) error_style = self.doc.addStyle("error", parent_style) StyleConstants.setForeground(error_style, Color.RED) def addtext(self, text, style="input", ensure_newline=False): doclen = self.doc.length if ensure_newline and 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)
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
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
class Console(object): PS1 = sys.ps1 PS2 = sys.ps2 def __init__(self, burp, namespace=None): self.burp = burp self.log = burp.log self._locals = dict(Burp=burp) self._buffer = [] self.history = History(self) if namespace is not None: self._locals.update(namespace) self.interp = JythonInterpreter(self, self._locals) self.textpane = JTextPane(keyTyped=self.keyTyped, keyPressed=self.keyPressed) self.textpane.setFont(Font('Monospaced', Font.PLAIN, 11)) self.burp.customizeUiComponent(self.textpane) self.initKeyMap() self.document.remove(0, self.document.getLength()) self.write('Burp Extender Jython Shell', prefix='') self.write(self.PS1) self.textpane.requestFocus() burp.log.info('Interactive interpreter ready...') @property def document(self): return self.textpane.document def resetbuffer(self): self._buffer = [] def keyTyped(self, event=None): if not self.inLastLine(): event.consume() def keyPressed(self, event): if event.keyCode in (KeyEvent.VK_BACK_SPACE, KeyEvent.VK_LEFT): self.backspaceListener(event) def getText(self): start, end = self.__getLastLineOffsets() text = self.document.getText(start, end - start) return text.rstrip() def insertText(self, data): position = self.textpane.getCaretPosition() self.textpane.select(position, position) self.textpane.replaceSelection(data) self.textpane.setCaretPosition(position + len(data)) def replaceText(self, data): start, end = self.__getLastLineOffsets() self.textpane.select(start, end) self.textpane.replaceSelection(data) self.textpane.setCaretPosition(start + len(data)) def write(self, data, color=Color.black, prefix='\n'): style = SimpleAttributeSet() if color is not None: style.addAttribute(StyleConstants.Foreground, color) self.document.insertString(self.document.getLength(), prefix + data, style) self.textpane.caretPosition = self.document.getLength() def enterAction(self, event=None): text = self.getText() self._buffer.append(text) source = '\n'.join(self._buffer) more = self.interp.runsource(source) if more: self.write(self.PS2, color=Color.black) else: self.resetbuffer() self.write(self.PS1) self.history.append(text) def deleteAction(self, event=None): if self.inLastLine(): if self.textpane.getSelectedText(): self.document.remove(self.textpane.getSelectionStart(), self.textpane.getSelectionEnd() - self.textpane.getSelectionStart()) elif self.textpane.getCaretPosition() < self.document.getLength(): self.document.remove(self.textpane.getCaretPosition(), 1) def deleteEndLineAction(self, event=None): if self.inLastLine(): position = self.textpane.getCaretPosition() self.textpane.setSelectionStart(position) _, end = self.__getLastLineOffsets() self.textpane.setSelectionEnd(end - 1) self.textpane.cut() def homeAction(self, event=None): if self.inLastLine(): start, end = self.__getLastLineOffsets() self.textpane.caretPosition = start def endAction(self, event=None): if self.inLastLine(): start, end = self.__getLastLineOffsets() self.textpane.caretPosition = end - 1 def pasteAction(self, event=None): if self.inLastLine(): clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() clipboard.getContents(self.textpane) contents = clipboard.getData(DataFlavor.stringFlavor) lines = contents.splitlines() for i, line in enumerate(lines): self.insertText(line) if i < len(lines) - 1: self.enterAction() def keyboardInterruptAction(self, event=None): self.interp.runsource('raise KeyboardInterrupt\n') self.resetbuffer() self.write(self.PS1) def backspaceListener(self, event=None): start, end = self.__getLastLineOffsets() if self.textpane.getCaretPosition() <= start and \ not self.textpane.getSelectedText(): event.consume() def initKeyMap(self): import platform os_name = platform.java_ver()[-1][0] if os_name.startswith('Win'): exit_key = KeyEvent.VK_Z interrupt_key = KeyEvent.VK_PAUSE else: exit_key = KeyEvent.VK_D interrupt_key = KeyEvent.VK_C bindings = [ (KeyEvent.VK_ENTER, 0, 'jython.enter', self.enterAction), (KeyEvent.VK_DELETE, 0, 'jython.delete', self.deleteAction), (KeyEvent.VK_HOME, 0, 'jython.home', self.homeAction), (KeyEvent.VK_LEFT, InputEvent.META_DOWN_MASK, 'jython.home', self.homeAction), (KeyEvent.VK_END, 0, 'jython.end', self.endAction), (KeyEvent.VK_RIGHT, InputEvent.META_DOWN_MASK, 'jython.end', self.endAction), (KeyEvent.VK_UP, 0, 'jython.up', self.history.historyUp), (KeyEvent.VK_DOWN, 0, 'jython.down', self.history.historyDown), (KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), 'jython.paste', self.pasteAction), (KeyEvent.VK_A, InputEvent.CTRL_MASK, 'jython.home', self.homeAction), (KeyEvent.VK_E, InputEvent.CTRL_MASK, 'jython.end', self.endAction), (KeyEvent.VK_K, InputEvent.CTRL_MASK, 'jython.deleteEndLine', self.deleteEndLineAction), (KeyEvent.VK_Y, InputEvent.CTRL_MASK, 'jython.paste', self.pasteAction), #(interrupt_key, InputEvent.CTRL_MASK, 'jython.keyboardInterrupt', self.keyboardInterruptAction), ] keymap = JTextComponent.addKeymap('jython', self.textpane.getKeymap()) for key, modifier, name, function in bindings: keymap.addActionForKeyStroke( KeyStroke.getKeyStroke(key, modifier), ActionDelegator(name, function)) self.textpane.keymap = keymap def inLastLine(self, include=True): start, end = self.__getLastLineOffsets() if self.textpane.getSelectedText(): position = self.textpane.getSelectionStart() else: position = self.textpane.getCaretPosition() if include is True: return start <= position <= end return start < position <= end def __getLastLineOffsets(self): firstElement = self.document.getRootElements()[0] lines = firstElement.getElementCount() start = firstElement.getElement(lines - 1).getStartOffset() end = firstElement.getElement(lines - 1).getEndOffset() line = self.document.getText(start, end - start) if len(line) >= 4 and (line[0:4] == self.PS1 or line[0:4] == self.PS2): return start + 4, end return start, end
class ChatClient(JFrame): ## Constructor method, receives the variables from the ChatApp class as parameters def __init__(self, name, greeting, tn): '''Constructor, initialises base class & assigns variables ''' # Call to the super method to take care of the base class(es) super(ChatClient, self).__init__() # Assign the relevent variable names self.username=name self.greeting=greeting self.tn = tn self.no_users=[] # Initiate the Threaded function for receiving messages t1=Thread(target=self.recvFunction) # Set to daemon t1.daemon=True t1.start() #Call the main UI uI=self.clientUI() ## Main GUI building function def clientUI(self): '''ClientUI and Widget creation ''' # Colours foreground_colour = Color(30,57,68) background_colour = Color(247,246,242) window_background = Color(145,190,210) # Borders self.border2=BorderFactory.createLineBorder(foreground_colour,1, True) # Fonts self.font= Font("Ubuntu Light", Font.BOLD, 20) self.label_font= Font("Ubuntu Light", Font.BOLD, 17) self.label_2_font= Font( "Ubuntu Light",Font.BOLD, 12) self.btn_font=Font("Ubuntu Light", Font.BOLD, 15) # Set the layout parameters self.client_layout=GroupLayout(self.getContentPane()) self.getContentPane().setLayout(self.client_layout) self.getContentPane().setBackground(window_background) self.client_layout.setAutoCreateGaps(True) self.client_layout.setAutoCreateContainerGaps(True) self.setPreferredSize(Dimension(400, 450)) # Create widgets and assemble the GUI # Main display area self.main_content=JTextPane() self.main_content.setBackground(background_colour) #self.main_content.setForeground(foreground_colour) self.main_content.setEditable(False) # Message entry area self.message=JTextArea( 2,2, border=self.border2, font=self.label_font, keyPressed=self.returnKeyPress) self.message.requestFocusInWindow() self.message.setBackground(background_colour) self.message.setForeground(foreground_colour) self.message.setLineWrap(True) self.message.setWrapStyleWord(True) self.message.setBorder(BorderFactory.createEmptyBorder(3,3,3,3)) self.message.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), self.returnKeyPress) # BUttons quit_btn=JButton("Quit!", actionPerformed=ChatApp().closeEvent, border=self.border2, font=self.btn_font) go_btn=JButton("Send", actionPerformed=self.grabText, border=self.border2, font=self.btn_font) quit_btn.setBackground(background_colour) go_btn.setBackground(background_colour) quit_btn.setForeground(foreground_colour) go_btn.setForeground(foreground_colour) # Make scrollable self.scroll_content=JScrollPane(self.main_content) self.scroll_content.setPreferredSize(Dimension(150,275)) self.scroll_content.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) self.scroll_content.setViewportView(self.main_content) self.scroll_content.setBackground(Color.WHITE) self.scroll_message=JScrollPane(self.message) self.scroll_message.setPreferredSize(Dimension(150,20)) self.scroll_message.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) # Test user label, still not updating after first round of messages self.user_label=JLabel(" Users online : %s "%(str(len(self.no_users))),JLabel.RIGHT, font=self.label_2_font) # Assemble the components # Horizontal layout self.client_layout.setHorizontalGroup(self.client_layout.createParallelGroup() .addComponent(self.scroll_content) .addGroup(self.client_layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(self.scroll_message)) .addGroup(self.client_layout.createSequentialGroup() .addComponent(quit_btn) .addComponent(go_btn).addGap(20)) .addGroup(self.client_layout.createParallelGroup() .addComponent(self.user_label)) ) # Vertical layout self.client_layout.setVerticalGroup(self.client_layout.createSequentialGroup() .addGroup(self.client_layout.createParallelGroup() .addComponent(self.scroll_content)) .addComponent(self.scroll_message) .addGroup(self.client_layout.createParallelGroup() .addComponent(quit_btn) .addComponent(go_btn)) .addGroup(self.client_layout.createParallelGroup() .addComponent(self.user_label)) ) # Finalise the GUI self.client_layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn, self.user_label]) self.pack() self.message.requestFocusInWindow() self.setTitle(">>> Client %s <<<"%self.username) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True) # Display the server greeting self.appendText('\n'+self.greeting+'\n') ## Function responsible for receiving and processing new messages def recvFunction(self): '''A function to control the receiving of data from the connection ''' # While the connection is available while self.tn: # Try to receive data using "<<<" as the delimiter try: message = self.tn.read_until('<<<') # If a message is received if message: garb, message=message.split('>>>') message, garb = message.split('<<<') message = ('\n'+message+'\n') # Call the append text function self.appendText(message) # Except if there is no data available except: #print('No message') pass ## Event driven function to retrieve and send data to the server def grabText(self, event): '''Function to repeatedly grab new messages entered into the text area and display them in the main text area. Resets the entry area ''' # Grab the text from the text area text=self.message.getText() # Don't allow an empty string through if text=='': return text=text.strip() # Call the append text function self.appendText('\nYou : '+text+'\n', self.username) # Reset the text to be empty and grab focus so that it is ready for new text input self.message.requestFocusInWindow() self.message.setText('') # Send the message to the server data=text.encode() self.tn.write(data+'\r\n') ## Function to handle appending of messages def appendText(self, message, user=None): '''This function takes care of appending any new messages to the content area ''' message_label=JTextArea(message,2,3, font=self.label_2_font) # If this is a message from the grab text function, create a new label, assign it's colours if user!=None: message_label.setBackground(Color(240,240,240)) message_label.setForeground(Color(129,129,129)) # Otherwise set the format for receive function (no user passed in) else: message_label.setBackground(Color(215,215,215)) message_label.setForeground(Color(40,153,153)) # Format and style options for the new message labels message_label.setEditable(False) message_label.setLineWrap(True) message_label.setWrapStyleWord(True) message_label.setBorder(BorderFactory.createLineBorder( Color(247,246,242),4)) # Sets the positioning of messages self.main_content.setCaretPosition(self.main_content.getDocument().getLength()) doc = self.main_content.getStyledDocument() attr=SimpleAttributeSet() self.main_content.insertComponent(message_label) # Essential for jtextarea to be able to stack message doc.insertString( self.main_content.getDocument().getLength(),'\n ', attr) # Not sure if needed self.main_content.repaint() ### This is a late edit so it isn't included in the documentation. Basically trying to dynamically update the number ### of users label at runtime. Works for incrementing the value but not decrementing it. print(message) # Only split the message if there are enough values to split (greeting messages differ in format to chat messages) try: user, text=message.split(' : ') except: return #print('Split values are %s %s'%(user, text)) user=str(user.strip()) #print(self.no_users) #print(user+' : '+text) # If the user already in the list, pass if user in self.no_users: if text == ('User %s amach sa teach !'%user): self.no_users.remove(user) print('User % removed'%user) else: #print('User %s not in list'%user) if str(user) == 'You': #print('User is equal to "You"') return self.no_users.append(user) print('User appended') self.number_users=len(self.no_users) #print('Length of user list is '+str(self.number_users)) self.user_label2=JLabel(" Users online : %s "%str(len(self.no_users)),JLabel.RIGHT, font=self.label_2_font) #print('Label created') #print('Attempt to replace label') self.client_layout.replace(self.user_label, self.user_label2) self.user_label = self.user_label2 self.user_label.repaint() self.user_label.revalidate() print('Label updated') ## Function to control return button press in message field def returnKeyPress(self,event): '''This function creates an object for return key press when inside the message entry area, creates an object of KeyAdapter and tests keycode for a match, responds with grab text callback ''' key_object=Key() key_value=key_object.keyPressed(event) if key_value == 10: self.grabText(event)