def getControlPanel(): global controlPanel controlPanel = JPanel() controlPanel.setLayout(BoxLayout(controlPanel, BoxLayout.Y_AXIS)) for row in keyLayout: rowPanel = JPanel() rowPanel.setLayout(BoxLayout(rowPanel, BoxLayout.X_AXIS)) controlPanel.add(rowPanel) for key in row: button = JButton(key[0], actionPerformed=handleKeyButton) button.setActionCommand(key[1]) rowPanel.add(button) global terminalResult terminalResult = JTextArea() scroller = JScrollPane(terminalResult) terminalResult.setLineWrap(True) scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) controlPanel.add(scroller) global terminalInput termInputPanel = JPanel() termInputPanel.setLayout(BoxLayout(termInputPanel, BoxLayout.X_AXIS)) termInputLabel = JLabel("Command") termInputPanel.add(termInputLabel) terminalInput = JTextField(actionPerformed=handleTerminalInput) minimumSize = terminalInput.getMinimumSize() maximumSize = terminalInput.getMaximumSize() terminalInput.setMaximumSize(Dimension(maximumSize.width, minimumSize.height)) termInputPanel.add(terminalInput) controlPanel.add(termInputPanel) return controlPanel
def initial(): global f ##文件 global txt global number_of_occurrence reload(sys) sys.setdefaultencoding('utf-8') ctr.init() ctr.set_value('flag', 0) ctr.set_value('reload_check', 0) ctr.set_value('world_boss_check', 0) ctr.set_value('raid_check', 0) #ctr.set_value('raid_check',None) number_of_occurrence = 0 ctr.set_value('max_level_check', None) ctr.set_value('return_check', 0) ticks = time.time() date = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(ticks)) + '_日誌' f = open(date + '.txt', 'w', 0) frame = JFrame("Log") txt = JTextArea(19, 55) scrollPane = JScrollPane(txt) ##frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(2000, 100) frame.setSize(480, 450) frame.setLayout(FlowLayout()) ##label = JLabel('記錄:') scrollPane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) ##frame.add(label) frame.add(scrollPane) frame.setVisible(True)
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab, IHttpListener, IMessageEditorController, AbstractTableModel): def registerExtenderCallbacks(self, callbacks): self.messages = [] self._callbacks = callbacks self._helpers = callbacks.getHelpers() self._callbacks.setExtensionName('TPLogScan') self._log = ArrayList() self._lock = Lock() self.jSplitPaneV = JSplitPane(JSplitPane.VERTICAL_SPLIT, True) self.jSplitPaneV.setDividerLocation(300) self.jSplitPaneV.setOneTouchExpandable(True) self.jPanel_top = JPanel() self.jTabbedPane = JTabbedPane(JTabbedPane.TOP) self.iRequestTextEditor = self._callbacks.createMessageEditor(self, False) self.iResponseTextEditor = self._callbacks.createMessageEditor(self, False) self.jTable = CustomTable(self) self.jTable.setShowGrid(True) self.jTable.setAutoCreateRowSorter(True) self.jTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS) first_column_model = self.jTable.getColumnModel().getColumn(0) first_column_model.setPreferredWidth(60); first_column_model.setMaxWidth(60) first_column_model.setMinWidth(60) self.jTable.getColumnModel().getColumn(1).setPreferredWidth(300) third_column_model = self.jTable.getColumnModel().getColumn(2) third_column_model.setPreferredWidth(100) third_column_model.setMinWidth(100) self.jTable.getColumnModel().getColumn(3).setPreferredWidth(600) self.jTable.getColumnModel().getColumn(4).setPreferredWidth(100) self.jTable.getColumnModel().getColumn(5).setPreferredWidth(100) self.jScrollPane1 = JScrollPane(self.jTable) self.jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED) self.jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.jTabbedPane.addTab("Log", self.jScrollPane1) self.jPanel_top.add(self.jTabbedPane) self.jPanel_top.setLayout(GridLayout(1,1)) self.jSplitPaneInfo = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, True) self.jSplitPaneInfo.setDividerLocation(650) self.jSplitPaneInfo.setOneTouchExpandable(True) self.jPanel_reqInfo_left = JPanel() self.jPanel_respInfo_right = JPanel() self.jPanel_reqInfo_left.setLayout(BorderLayout()) self.jPanel_respInfo_right.setLayout(BorderLayout()) self.jPanel_reqInfo_left.add(self.iRequestTextEditor.getComponent(), BorderLayout.CENTER) self.jPanel_respInfo_right.add(self.iResponseTextEditor.getComponent(), BorderLayout.CENTER) self.jSplitPaneInfo.add(self.jPanel_reqInfo_left, JSplitPane.LEFT) self.jSplitPaneInfo.add(self.jPanel_respInfo_right, JSplitPane.RIGHT) self.jSplitPaneV.add(self.jPanel_top, JSplitPane.TOP) self.jSplitPaneV.add(self.jSplitPaneInfo, JSplitPane.BOTTOM) self._callbacks.customizeUiComponent(self.jSplitPaneV) self._callbacks.customizeUiComponent(self.jPanel_top) self._callbacks.customizeUiComponent(self.jTabbedPane) self._callbacks.customizeUiComponent(self.jTable) self._callbacks.customizeUiComponent(self.jScrollPane1) self._callbacks.customizeUiComponent(self.jSplitPaneInfo) self._callbacks.customizeUiComponent(self.jPanel_reqInfo_left) self._callbacks.customizeUiComponent(self.jPanel_respInfo_right) self._callbacks.addSuiteTab(self) self._callbacks.registerHttpListener(self) self._callbacks.registerContextMenuFactory(self) return def getTabCaption(self): return 'TPLogScan' def getUiComponent(self): return self.jSplitPaneV def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 6 def getColumnName(self, columnIndex): if columnIndex == 0: return "#" if columnIndex == 1: return "Host" if columnIndex == 2: return "Method" if columnIndex == 3: return "URL" if columnIndex == 4: return "Status" if columnIndex == 5: return "Length" return "" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) url = logEntry._url.toString() url_parse = urlparse.urlparse(url) if url_parse.netloc.find(':') != -1: netloc = url_parse.netloc[:url_parse.netloc.find(':')] host = url_parse.scheme + '://' + netloc path = url_parse.path if columnIndex == 0: return rowIndex+1 if columnIndex == 1: return host if columnIndex == 2: return logEntry._method if columnIndex == 3: return path if columnIndex == 4: return logEntry._status_code if columnIndex == 5: return logEntry._length return "" def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): # tool_name = self._callbacks.getToolName(toolFlag) # if tool_name != 'Extender': if toolFlag != 1024: return if messageIsRequest: return request_info = self._helpers.analyzeRequest(messageInfo) response_info = self._helpers.analyzeResponse(messageInfo.getResponse()) response_headers = response_info.getHeaders() response_length = 0 for header in response_headers: header = header.encode('utf-8') if header.startswith("Content-Length"): response_length = int(header.replace('Content-Length: ', '')) length = response_length if response_length > 0 else 0 self._lock.acquire() row = self._log.size() self._log.add(LogEntry(toolFlag, self._callbacks.saveBuffersToTempFiles(messageInfo), request_info.getUrl(),request_info.getMethod(),response_info.getStatusCode(),length)) self.fireTableRowsInserted(row, row) self._lock.release() def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() def loadMenus(self): self.menus = [] self.mainMenu = JMenu("TPLogScan") self.menus.append(self.mainMenu) menu = JMenuItem('ThinkPHP v3', None, actionPerformed=lambda x: self.eventHandler(x)) self.mainMenu.add(menu) menu = JMenuItem('ThinkPHP v5', None, actionPerformed=lambda x: self.eventHandler(x)) self.mainMenu.add(menu) def createMenuItems(self, invocation): self.loadMenus() self.messages = invocation.getSelectedMessages() return self.menus if self.menus else None def eventHandler(self, x): menuName = x.getSource().text if menuName == 'ThinkPHP v3': version = 3 elif menuName == 'ThinkPHP v5': version = 5 else: print("chose error") return for message in self.messages: url = str(self._helpers.analyzeRequest(message).getUrl()) url_parse = urlparse.urlparse(url) url = url_parse.scheme + '://' + url_parse.netloc print("[*] url: {}".format(url)) datetime_now = datetime.datetime.now() year = (datetime_now - datetime.timedelta(days=30)).year month = (datetime_now - datetime.timedelta(days=30)).month day = (datetime_now - datetime.timedelta(days=30)).day tplogscan = TPLogScan(url, version, year, month, day) log_path = tplogscan.checkLogPath() if not log_path: print("[-] {} can't get log file! ".format(url)) self._callbacks.issueAlert("{} can't get log file".format(url)) return filename_list = tplogscan.genFileName() t = threading.Thread(target=self.logScan, args=(message, version, log_path, filename_list)) t.start() def logScan(self, message, version, log_path, filename_list): http_service = message.getHttpService() old_request = self._helpers.bytesToString(message.getRequest()) old_path = self._helpers.analyzeRequest(message).getUrl().getPath() for filename in filename_list: try: new_request = old_request.replace(" " + old_path + " HTTP/", " " + log_path+filename + " HTTP/") response, status_code = self.sendRequest(http_service, new_request) if status_code != 200: continue tmp_filename = filename now_filename = '' pattern = re.compile(r"\[ (\d{4}-\d{2}-\d{2})T((\d{2}:){2}\d{2})\+08:00 \]") flag = True while flag: match_result = pattern.search(response) if not match_result: break time_str = match_result.group(1) + ' ' + match_result.group(2) timeArray = time.strptime(time_str, "%Y-%m-%d %H:%M:%S") timestamp = int(time.mktime(timeArray)) timestamp_list = [str(timestamp), str(timestamp-1), str(timestamp-2), str(timestamp-3)] for timestamp in timestamp_list: if version == 3: tmp_filename = timestamp + '-' + filename else: tmp_filename = filename[:filename.find('/')] + '/' + timestamp + '-' + filename[filename.find('/')+1:] if tmp_filename == now_filename: flag = False break new_request = old_request.replace(" " + old_path + " HTTP/", " " + log_path+tmp_filename + " HTTP/") response, status_code = self.sendRequest(http_service, new_request) if status_code == 200: now_filename = tmp_filename break except Exception as e: print("[-] error: {}".format(e)) print('[*] Log Scan complete!') def sendRequest(self, http_service, new_request): checkRequestResponse = self._callbacks.makeHttpRequest(http_service, self._helpers.stringToBytes(new_request)) status_code = self._helpers.analyzeResponse(checkRequestResponse.getResponse()).getStatusCode() print('[*] {} | {}'.format(self._helpers.analyzeRequest(checkRequestResponse).getUrl(), status_code)) return self._helpers.bytesToString(checkRequestResponse.getResponse()), status_code
class ConsolePanel(Panel): def __init__(self): self.console = None self.outText = None self.inText = None self.outTextScroller = None self.nestedInputPanel = None self.directoryText = None Panel.__init__(self, "insets 0 0 0 0") def sendCommand(self, command): print str(self) oldText = self.inText.getText() self.inText.setText(command) self.inText.getActionListeners()[0].actionPerformed(None) self.inText.setText(oldText) def setDirectoryText(self, dirText): self.directoryText.setText(dirText) self.nestedInputPanel.revalidate() def write_out(self, text): if not self.outText: return self.outText.setText(self.outText.getText() + text) def initUI(self): font = Font("Courier New", Font.BOLD, 14) #create the output text panel self.outText = JTextArea() self.outText.setEditable(False) self.outText.setFont(font) self.outText.setWrapStyleWord(True) self.outText.setLineWrap(True) #self.outText.setLineWrap(True) #self.outText.setWrapStyleWord(True) class NoGhostScroller(JScrollPane): def paintComponent(self, g): g.setColor(self.getBackground()) g.fillRect(0, 0, self.getWidth(), self.getHeight()) #super(NoGhostScroller, self).paintComponent(g) self.outTextScroller = JScrollPane(self.outText) self.outTextScroller.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) self.outTextScroller.getVerticalScrollBar().setForeground( Color(255, 0, 0)) #self.outText.setOpaque(False) self.outText.setBackground(Color(0, 20, 0)) self.outText.setForeground(Color.WHITE) #self.outTextScroller.setOpaque(False) self.outTextScroller.setBackground(Color(0, 20, 0)) #self.outText.repaint() #self.layered = JLayeredPane() #self.layered.setLayer(self.outTextScroller, 0) #create the input text box self.inText = JTextField() self.inText.setFocusTraversalKeysEnabled(False) self.inText.setFont(font) self.inText.setBackground(Color(0, 20, 0)) self.inText.setForeground(Color.WHITE) self.inText.getCaret().setVisible(True) self.inText.getCaret().setBlinkRate(500) self.inText.setCaretColor(Color(200, 255, 200)) class InFocusAdapter(FocusAdapter): def focusLost(adap, e): self.inText.setVisible(True) self.inText.addFocusListener(InFocusAdapter()) self.nestedInputPanel = Panel("Insets 0 0 0 0") #create the directory text box self.directoryText = JTextField() self.directoryText.setEditable(False) self.directoryText.setFont(font) self.directoryText.setBackground(Color(0, 20, 0)) self.directoryText.setForeground(Color.WHITE) #set up the console sys.stdout = FakeOut(self.outText) self.console = BashED_Console(stdout=sys.stdout) self.directoryText.setText(self.console.get_prompt()) self.revalidate() dirTex = self.directoryText #create the listener that fires when the 'return' key is pressed class InputTextActionListener(ActionListener): def __init__(self, parent, inp, out, console): self.parent = parent self.inp = inp self.out = out self.console = console def actionPerformed(self, e): #print self.getCommandText() # print(self.console.get_prompt()) # self.console.onecmd(self.inp.getText()) # self.parent.write_out("\n" + self.inp.getText()) # dirTex.setText(self.console.get_prompt()) # self.inp.setText("") self.parent.write_out(self.console.get_prompt() + self.inp.getText() + '\n') if 'clear' in self.inp.getText().split(' ')[0]: self.out.setText("") #clear the screen else: self.console.onecmd(self.inp.getText()) dirTex.setText(self.console.get_prompt()) self.inp.setText("") #create the listener that fires whenever a user hits a key class InputKeyActionListener(KeyAdapter): def __init__(self, parent, inp, out, console): self.parent = parent self.inp = inp self.out = out self.console = console def keyReleased(self, k): inp = self.inp.getText() if k.getKeyCode() == 9: #tab character autos = self.console.tabcomplete(self.inp.getText()) if len(autos) == 1: self.inp.setText(autos[0]) else: i = 0 for option in autos: self.parent.write_out(option) if i % 3 == 0: print('\n') else: print('\t') hist = None if k.getKeyCode() == 38: hist = self.console.next_hist() if k.getKeyCode() == 40: hist = self.console.last_hist() if hist: self.inp.setText(hist.rstrip('\n')) #prevent from firing self.inText.addActionListener( InputTextActionListener(self, self.inText, self.outText, self.console)) self.inText.addKeyListener( InputKeyActionListener(self, self.inText, self.outText, self.console)) def addUI(self): self.add(self.outTextScroller, "cell 0 0, push, grow") self.add(self.nestedInputPanel, "cell 0 1, pushx, growx") self.nestedInputPanel.add(self.directoryText, "cell 0 0") self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")
class MyPanel(JSplitPane): def __init__(self, scannerInstance): self.scannerInstance = scannerInstance JSplitPane.__init__(self, JSplitPane.VERTICAL_SPLIT) # super(MyPanel, self).__init__(self, JSplitPane.VERTICAL_SPLIT) # self.setSize(640, 460) self.setBorder(EmptyBorder(20, 20, 20, 20)) self.topPanel = JPanel(BorderLayout(10, 10)) self.topPanel.setBorder(EmptyBorder(0, 0, 10, 0)) # self.topPanel.setBackground(Color.blue) self.bottomPanel = JPanel() self.bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0)) # self.bottomPanel.setBackground(Color.yellow) self.bottomPanel.setPreferredSize(Dimension(580, 40)) # plain self.plainPanel = JPanel(BorderLayout(10, 10)) self.plainTextPane = JTextArea() self.plainTextPane.setLineWrap(True) self.plainTextPane.setEditable(True) self.plainScrollPane = JScrollPane(self.plainTextPane) self.plainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) self.plainPanel.add(JLabel("PLAIN:", SwingConstants.CENTER), BorderLayout.PAGE_START) self.plainPanel.add(self.plainScrollPane, BorderLayout.CENTER) self.topPanel.add(self.plainPanel, BorderLayout.LINE_START) # button self.btnsPanel = JPanel(GridBagLayout()) gbc = GridBagConstraints() gbc.fill = GridBagConstraints.HORIZONTAL gbc.gridx = 0 gbc.gridy = 0 self.btnsPanel.add(JButton("=Encrypt=>", actionPerformed=self.encrypt), gbc) gbc.fill = GridBagConstraints.HORIZONTAL gbc.gridx = 0 gbc.gridy = 1 self.btnsPanel.add(JButton("<=Decrypt=", actionPerformed=self.decrypt), gbc) gbc.fill = GridBagConstraints.HORIZONTAL gbc.gridx = 0 gbc.gridy = 2 gbc.gridheight = 2 gbc.ipadx = 10 self.btnsPanel.add(JButton("SIGN", actionPerformed=self.sign), gbc) # b_enc.setPreferredSize(Dimension(30, 20)) # b_dec.setPreferredSize(Dimension(30, 20)) self.topPanel.add(self.btnsPanel, BorderLayout.CENTER) # cipher self.cipherPanel = JPanel(BorderLayout(10, 10)) self.cipherTextPane = JTextArea() self.cipherTextPane.setLineWrap(True) self.cipherTextPane.setEditable(True) self.cipherScrollPane = JScrollPane(self.cipherTextPane) self.cipherScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) self.cipherPanel.add(JLabel("CIPHER:", SwingConstants.CENTER), BorderLayout.PAGE_START) self.cipherPanel.add(self.cipherScrollPane, BorderLayout.CENTER) self.topPanel.add(self.cipherPanel, BorderLayout.LINE_END) self.signPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.signPanel.add(JLabel("SIGN:", SwingConstants.LEFT), BorderLayout.LINE_START) self.signField = JTextField(50) self.signPanel.add(self.signField) self.bottomPanel.add(self.signPanel) self.plainPanel.setPreferredSize(Dimension(260, 400)) self.btnsPanel.setPreferredSize(Dimension(80, 400)) self.cipherPanel.setPreferredSize(Dimension(260, 400)) self.setTopComponent(self.topPanel) self.setBottomComponent(self.bottomPanel) def setPlain(self, plain): if plain: self.plainTextPane.setText(plain.decode("utf-8")) def setCipher(self, cipher): self.cipherTextPane.setText(cipher) def setSignature(self, sign): self.signField.setText(sign) def unicode_to_str(self, content): data = "" for i in content: data += chr(ord(i)) return data def get_real_content(self, content): s_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) handled_cnt = None data = self.unicode_to_str(content) try: s_client.connect(LOCAL_IPC) s_client.send(data) handled_cnt = "" while True: _sp = s_client.recv(1024) if _sp and len(_sp) > 0: handled_cnt += _sp if len(_sp) < 1024: break else: break except socket.error: BP_STDERR.println("fail to connect local IPC service.") s_client.close() # BP_STDOUT.println("get_real_content - %s" % handled_cnt.decode("utf-8")) return handled_cnt if handled_cnt and len(handled_cnt) > 0 else None def encrypt(self, event): plain = self.plainTextPane.getText() # BP_STDERR.println("plain type - %s" % type(plain)) result = self.get_real_content(b"\x01" + plain) self.setCipher(result) def decrypt(self, event, is_req=None): cipher = self.cipherTextPane.getText() # BP_STDERR.println("cipher type - %s" % type(cipher)) flag = b"\x02" if is_req is True else b"\x03" if is_req is False else b"\x00" result = self.get_real_content(flag + cipher) self.setPlain(result) def sign(self, event): text = self.plainTextPane.getText() # BP_STDERR.println("sign func called! - %s" % text) result = self.get_real_content(b"\x04" + text) self.setSignature(result)
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)
class ConsolePanel(Panel): def __init__(self): self.console = None self.outText = None self.inText = None self.outTextScroller = None self.nestedInputPanel = None self.directoryText = None Panel.__init__(self, "insets 0 0 0 0") def sendCommand(self, command): print str(self) oldText = self.inText.getText() self.inText.setText(command) self.inText.getActionListeners()[0].actionPerformed(None) self.inText.setText(oldText) def setDirectoryText(self, dirText): self.directoryText.setText(dirText) self.nestedInputPanel.revalidate() def write_out(self,text): if not self.outText: return self.outText.setText(self.outText.getText() + text) def initUI(self): font = Font("Courier New", Font.BOLD, 14) #create the output text panel self.outText = JTextArea() self.outText.setEditable(False) self.outText.setFont(font) self.outText.setWrapStyleWord(True) self.outText.setLineWrap(True) #self.outText.setLineWrap(True) #self.outText.setWrapStyleWord(True) class NoGhostScroller(JScrollPane): def paintComponent(self, g): g.setColor(self.getBackground()) g.fillRect(0, 0, self.getWidth(), self.getHeight()) #super(NoGhostScroller, self).paintComponent(g) self.outTextScroller = JScrollPane(self.outText) self.outTextScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) self.outTextScroller.getVerticalScrollBar().setForeground(Color(255, 0, 0)) #self.outText.setOpaque(False) self.outText.setBackground(Color(0, 20, 0)) self.outText.setForeground(Color.WHITE) #self.outTextScroller.setOpaque(False) self.outTextScroller.setBackground(Color(0, 20, 0)) #self.outText.repaint() #self.layered = JLayeredPane() #self.layered.setLayer(self.outTextScroller, 0) #create the input text box self.inText = JTextField() self.inText.setFocusTraversalKeysEnabled(False) self.inText.setFont(font) self.inText.setBackground(Color(0, 20, 0)) self.inText.setForeground(Color.WHITE) self.inText.getCaret().setVisible(True) self.inText.getCaret().setBlinkRate(500) self.inText.setCaretColor(Color(200,255,200)) class InFocusAdapter(FocusAdapter): def focusLost(adap, e): self.inText.setVisible(True) self.inText.addFocusListener(InFocusAdapter()) self.nestedInputPanel = Panel("Insets 0 0 0 0") #create the directory text box self.directoryText = JTextField() self.directoryText.setEditable(False) self.directoryText.setFont(font) self.directoryText.setBackground(Color(0, 20, 0)) self.directoryText.setForeground(Color.WHITE) #set up the console sys.stdout = FakeOut(self.outText) self.console = BashED_Console(stdout=sys.stdout) self.directoryText.setText(self.console.get_prompt()) self.revalidate(); dirTex = self.directoryText; #create the listener that fires when the 'return' key is pressed class InputTextActionListener(ActionListener): def __init__(self,parent,inp,out,console): self.parent = parent self.inp = inp self.out = out self.console = console def actionPerformed(self, e): #print self.getCommandText() # print(self.console.get_prompt()) # self.console.onecmd(self.inp.getText()) # self.parent.write_out("\n" + self.inp.getText()) # dirTex.setText(self.console.get_prompt()) # self.inp.setText("") self.parent.write_out(self.console.get_prompt() + self.inp.getText() + '\n') if 'clear' in self.inp.getText().split(' ')[0]: self.out.setText("") #clear the screen else: self.console.onecmd(self.inp.getText()) dirTex.setText(self.console.get_prompt()) self.inp.setText("") #create the listener that fires whenever a user hits a key class InputKeyActionListener(KeyAdapter): def __init__(self,parent,inp,out,console): self.parent = parent self.inp = inp self.out = out self.console = console def keyReleased(self, k): inp = self.inp.getText() if k.getKeyCode() == 9: #tab character autos = self.console.tabcomplete(self.inp.getText()) if len(autos) == 1: self.inp.setText(autos[0]) else: i = 0 for option in autos: self.parent.write_out(option) if i % 3 == 0: print('\n') else: print('\t') hist = None if k.getKeyCode() == 38: hist = self.console.next_hist() if k.getKeyCode() == 40: hist = self.console.last_hist() if hist: self.inp.setText(hist.rstrip('\n'))#prevent from firing self.inText.addActionListener(InputTextActionListener(self,self.inText,self.outText,self.console)) self.inText.addKeyListener(InputKeyActionListener(self,self.inText,self.outText,self.console)) def addUI(self): self.add(self.outTextScroller, "cell 0 0, push, grow") self.add(self.nestedInputPanel, "cell 0 1, pushx, growx") self.nestedInputPanel.add(self.directoryText, "cell 0 0") self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")