class DatabasePanel(JPanel, ActionListener): __metaclass__ = Singleton def __init__(self): super(DatabasePanel, self).__init__() self._button = None self._text_field = None def actionPerformed(self, event): database_path = UIHelpers.choose_file() if database_path: if Application.get_instance().execute( SetDomainDictValueCommand( SetDomainDictValueCommand.TYPE_PERSISTENCE, 'database_path', database_path)): self._text_field.setText(database_path) def display(self, values): self._prepare_components(values) def _prepare_components(self, values): self._text_field = JTextField() self._text_field.setColumns(30) self._text_field.setEditable(False) self._text_field.setText(values['database_path']) self.add(self._text_field) button = JButton('Save as...') button.addActionListener(self) self.add(button)
class TextFieldPanel(JPanel, FocusListener): __metaclass__ = Singleton def __init__(self): super(TextFieldPanel, self).__init__() self._text_field = None def focusGained(self, event): pass def focusLost(self, event): Application.get_instance().execute( SetDomainDictValueCommand( self._get_domain_dict_type(), self._get_domain_dict_key(), InfrastructureHelpers.split(self._text_field.getText()))) def display(self, values): self._prepare_components(values) def _prepare_components(self, values): self._text_field = JTextField() self._text_field.setColumns(30) self._text_field.setEditable(True) self._text_field.setText( InfrastructureHelpers.join(values[self._get_domain_dict_key()])) self._text_field.addFocusListener(self) self.add(self._text_field)
class TagPanel(JPanel, DocumentListener): __metaclass__ = Singleton def __init__(self): super(TagPanel, self).__init__() self._text_field = None def changeUpdate(self, event): self._update() def insertUpdate(self, event): self._update() def removeUpdate(self, event): self._update() def display(self, values): self.add(JLabel('<html><b>Tags:</b></html>')) self._text_field = JTextField() self._text_field.setColumns(20) self._text_field.setEditable(True) self._text_field.setText(InfrastructureHelpers.join(values['tags'])) self._text_field.getDocument().addDocumentListener(self) self.add(self._text_field) def _update(self): Application.get_instance().execute(SetDomainDictValueCommand( SetDomainDictValueCommand.TYPE_VISIBLE_ITEMS, 'tags', InfrastructureHelpers.split(self._text_field.getText()) ))
class HumanDetailPanel(DetailPanel): """ generated source for class HumanDetailPanel """ moveTable = JZebraTable() moveTextField = JTextField() selectButton = JButton() selection = Move() timerBar = JTimerBar() def __init__(self): """ generated source for method __init__ """ super(HumanDetailPanel, self).__init__(GridBagLayout()) model = DefaultTableModel() model.addColumn("Legal Moves") self.moveTable = JZebraTable(model) self.selectButton = JButton(selectButtonMethod()) self.moveTextField = JTextField() self.timerBar = JTimerBar() self.selection = None self.moveTable.setShowHorizontalLines(True) self.moveTable.setShowVerticalLines(True) self.moveTextField.setEditable(False) self.add(JScrollPane(self.moveTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), GridBagConstraints(0, 0, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) self.add(self.selectButton, GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 0, 0)) self.add(self.moveTextField, GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) self.add(self.timerBar, GridBagConstraints(0, 2, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) @overloaded def observe(self, event): """ generated source for method observe """ if isinstance(event, (HumanNewMovesEvent, )): self.observe(event) elif isinstance(event, (HumanTimeoutEvent, )): self.observe(event) elif isinstance(event, (PlayerTimeEvent, )): self.observe(event) @observe.register(object, HumanNewMovesEvent) def observe_0(self, event): """ generated source for method observe_0 """ model = self.moveTable.getModel() model.setRowCount(0) for move in event.getMoves(): model.addRow([None]*) self.selection = event.getSelection() self.moveTextField.setText(self.selection.__str__()) @observe.register(object, HumanTimeoutEvent) def observe_1(self, event): """ generated source for method observe_1 """ event.getHumanPlayer().setMove(self.selection) @observe.register(object, PlayerTimeEvent) def observe_2(self, event): """ generated source for method observe_2 """ self.timerBar.time(event.getTime(), 500) def selectButtonMethod(self): """ generated source for method selectButtonMethod """ return AbstractAction("Select")
def showLoginIdPassword(data): global frame frame = JFrame("Show Id Password ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,350) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,350) panel.setLocation(0,0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("LoginId AND Password") heading.setBounds(200,30,150,40) lbLoginId = JLabel("LoginId") lbPassword = JLabel("password") tfLoginId = JTextField(data[0].encode('ascii')) tfPassword = JTextField(data[1].encode('ascii')) tfLoginId.setEditable(False) tfPassword.setEditable(False) lbLoginId.setBounds(50,100,150,30) lbPassword.setBounds(50,150,150,30) tfLoginId.setBounds(220,100,150,30) tfPassword.setBounds(220,150,150,30) btnOk = JButton("Ok",actionPerformed=clickOk) btnOk.setBounds(250,220,100,30) panel.add(heading) panel.add(lbLoginId) panel.add(lbPassword) panel.add(tfLoginId) panel.add(tfPassword) panel.add(btnOk) frame.add(panel)
def updateTeacherForm(data): global heading global tfTeacherName global tfTeacherPhone global taTeacherAddress global tfTeacherEmail global tfTeacherCourse global tfTeacherPayment global frame global btnEnter frame = JFrame(" Teacher ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 600) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 600) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel(" TEACHER PROFILE") heading.setBounds(200, 30, 150, 40) lbTeacherName = JLabel("Teacher Name ") lbTeacherPhone = JLabel("Phone") lbTeacherEmail = JLabel("Email") lbTeacherAddress = JLabel("Address") lbTeacherCourse = JLabel("Teacher Course ") lbTeacherPayment = JLabel("Teacher Payment") teacherName = data[0].encode('ascii') teacherPhone = data[1].encode('ascii') teacherEmail = data[2].encode('ascii') teacherAddress = data[3].encode('ascii') teacherCourse = data[4].encode('ascii') teacherPayment = data[5] tfTeacherName = JTextField(teacherName) tfTeacherPhone = JTextField(teacherPhone) taTeacherAddress = JTextArea(teacherAddress) tfTeacherEmail = JTextField(teacherEmail) tfTeacherCourse = JTextField(teacherCourse) tfTeacherPayment = JTextField(str(teacherPayment)) tfTeacherCourse.setEditable(False) tfTeacherPayment.setEditable(False) tfTeacherName.setEditable(False) lbTeacherName.setBounds(70, 100, 130, 30) lbTeacherPhone.setBounds(70, 150, 130, 30) lbTeacherEmail.setBounds(70, 200, 130, 30) lbTeacherAddress.setBounds(70, 250, 130, 30) lbTeacherCourse.setBounds(70, 350, 130, 30) lbTeacherPayment.setBounds(70, 400, 130, 30) tfTeacherName.setBounds(220, 100, 130, 30) tfTeacherPhone.setBounds(220, 150, 130, 30) tfTeacherEmail.setBounds(220, 200, 130, 30) taTeacherAddress.setBounds(220, 250, 130, 80) tfTeacherCourse.setBounds(220, 350, 130, 30) tfTeacherPayment.setBounds(220, 400, 130, 30) btnEnter = JButton("Update", actionPerformed=clickUpdateTeacher) btnEnter.setBounds(350, 450, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickCancel) btnCancel.setBounds(100, 450, 100, 40) panel.add(heading) panel.add(lbTeacherName) panel.add(lbTeacherPhone) panel.add(lbTeacherEmail) panel.add(lbTeacherAddress) panel.add(lbTeacherCourse) panel.add(lbTeacherPayment) panel.add(tfTeacherName) panel.add(tfTeacherPhone) panel.add(tfTeacherEmail) panel.add(taTeacherAddress) panel.add(tfTeacherCourse) panel.add(tfTeacherPayment) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
class ConsoleController: def __init__(self, parent): self._parent = parent self._sessions = self._parent.sessions() self._request = None #TODO I'll need a request in order to connect to something self._position = None #TODO I'll need a position, something to change in the header to insert the command self._pwd = None self._commandHistory = [] self._historyIndex = 0 self._tabComplete = [] def getMainComponent(self): self._mainPanel = JPanel(BorderLayout()) # input self._consolePwd = JTextField() self._consolePwd.setEditable(False) self._consolePwd.setText("Not initialized") self._consoleInput = JTextField() #Remove 'tab' low-level tab-function of jumping to other component, so I can use it self._consoleInput.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET) self._consoleInput.addActionListener(self.EnterPress()) self._consoleInput.addKeyListener(self.KeyPress()) self._inputPanel = JPanel(BorderLayout()) self._inputPanel.add(self._consolePwd, BorderLayout.WEST) self._inputPanel.add(self._consoleInput, BorderLayout.CENTER) # output self._consoleOutput = JTextArea() self._consoleOutput.setEditable(False) self._consoleOutput.setForeground(Color.WHITE) self._consoleOutput.setBackground(Color.BLACK) self._consoleOutput.setFont(self._consoleOutput.getFont().deriveFont(12.0)) self._scrollPaneConsoleOutput = JScrollPane(self._consoleOutput) # Add to main panel and return the main panel self._mainPanel.add(self._scrollPaneConsoleOutput, BorderLayout.CENTER) self._mainPanel.add(self._inputPanel, BorderLayout.SOUTH) return self._mainPanel def sendCommand(self, requestId, cmd, directTo): Utils.out("ConsoleController > sendCommand > 'cmd'") Utils.out(cmd) if cmd == 'clear': self.resetOutput() self._commandHistory.append(cmd) self.resetHistoryIndex() self.clearCmd() return cmdModified = cmd requestHttpMethod = self._parent.getRequestHttpService(requestId) #If I use virtual persistence and there's already a pwd set if Utils.shellController._virtualPersistence and self.pwd(): #Then always prepend 'cd <pwd>' to any command executed. In reality we # always enter in the same directory, but because this shell keeps track # of where the user thinks he is, and always goes to that directory first # the illusion of a persistence is created cmdVirtual = "cd " + self.pwd() cmdModified = cmdVirtual + "; " + cmd requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start() self._commandHistory.append(cmd) self.resetHistoryIndex() self.clearCmd() if Utils.shellController._virtualPersistence: if cmd.startswith('cd '): Utils.out("ConsoleController > sendCommand: detected 'cd '") #ask for pwd cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX) requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start() if Utils.shellController._tabCompletion: #ask 'ls -1a' for tab-completion # The first command, pwd is set here, but cmdVirtual ain't. But this # also means we are at the entry directory anyway, so we can just ask ls # and get the correct tab completion anyway try: cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX) except: cmdTabComplete = Commands.ls(Commands.OS_LINUX) requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start() else: if Utils.shellController._tabCompletion: cmdTabComplete = Commands.ls(Commands.OS_LINUX) requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start() #either way execute the requested command def startSession(self): #TODO when starting a session I want to test for a number of things: # if I can reform the request to a post request and still have it work # if base 64 is available # if bash is available self.setPwd(None) if Utils.shellController._virtualPersistence and Utils.shellController._outputIsolator: Utils.out("startSession > virtualPersistence enabled > Requesting pwd") self.sendCommand(self._parent.currentRequestId(), Commands.pwd(Commands.OS_LINUX), 'pwd') def appendOutput(self, text, printCommand=True): try: if printCommand: self.printCommand(self._commandHistory[-1]) except: pass self._consoleOutput.append("\n" + text) #auto scroll down if needed self._consoleOutput.setCaretPosition(self._consoleOutput.getDocument().getLength()) def resetOutput(self): Utils.setConsole('') def printCommand(self, cmd): self._consoleOutput.append("\n" + self._pwd + "# " + cmd) def printCurrentCommand(self): self.printCommand(self.cmd()) def setPwd(self, pwd): self._pwd = pwd if pwd is None: self._consolePwd.setText('') else: self._consolePwd.setText(pwd) Utils.consoleController._mainPanel.revalidate() def pwd(self): return self._pwd def cmdHistoryCount(self): return len(self._commandHistory) #TODO - 1 def setCmd(self, cmd): self._consoleInput.setText(cmd) def cmd (self): return self._consoleInput.getText() def clearCmd(self): self._consoleInput.setText('') def resetHistoryIndex(self): self._historyIndex = self.cmdHistoryCount() def previousCommand(self): if self._historyIndex > 0: self._historyIndex -= 1 self.setCmd(self._commandHistory[self._historyIndex]) def nextCommand(self): if self._historyIndex < self.cmdHistoryCount(): self._historyIndex += 1 self.setCmd(self._commandHistory[self._historyIndex]) else: self.clearCmd() self.resetHistoryIndex() def setTabComplete(self, text): self._tabComplete = text.splitlines() def findTabComplete(self, beginCharacters=''): suggestions = [] if beginCharacters: for suggestion in self._tabComplete: Utils.debug("suggestion", suggestion) Utils.debug("text", beginCharacters) if suggestion[0:len(beginCharacters)] == beginCharacters: suggestions.append(suggestion) else: suggestions = self._tabComplete return suggestions def tabComplete(self): currentCommand = self.cmd() Utils.debug("currentCommand", currentCommand) if currentCommand: commandArray = currentCommand.split(' ') lastword = commandArray.pop() Utils.debug("lastword", lastword) suggestions = self.findTabComplete(lastword) if suggestions: if len(suggestions) > 1: self.printCurrentCommand() for suggestion in suggestions: self.appendOutput(suggestion, False) if len(suggestions) == 1: self.setCmd(' '.join(commandArray) + ' ' + suggestions.pop()) else: suggestions = self.findTabComplete() if len(suggestions) > 1: self.printCurrentCommand() for suggestion in suggestions: self.appendOutput(suggestion, False) class EnterPress(ActionListener): #TODO remove: AbstractAction def actionPerformed(self, e): Utils.consoleController.sendCommand(Utils.shellController.currentRequestId(), Utils.consoleInput.getText(), 'console') def keyPressed(self, e): Utils.out("key pressed") class KeyPress(KeyListener): def keyTyped(self, e): pass def keyReleased(self, e): if e.getKeyCode() == e.VK_DOWN: Utils.consoleController.nextCommand() Utils.out("released down") if e.getKeyCode() == e.VK_UP: Utils.consoleController.previousCommand() Utils.out("released up") if e.getKeyCode() == e.VK_TAB: Utils.out("pressed tab") Utils.consoleController.tabComplete() def keyPressed(self, e): pass
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 EditSettingsView(JDialog): def __init__(self, controller, working_dir, servers, keystrokes, languages, projects): self.logger = logging.getLogger("NammuController") self.setAlwaysOnTop(True) self.controller = controller self.working_dir = working_dir self.servers = servers self.keystrokes = keystrokes self.languages = languages self.projects = projects self.pane = self.getContentPane() def build(self): ''' Create all tab panels and put together to form the settings window. ''' self.setLayout(BorderLayout()) self.add(self.build_tabbed_panel(), BorderLayout.CENTER) self.add(self.build_buttons_panel(), BorderLayout.SOUTH) def build_tabbed_panel(self): ''' Build panel with tabs for each of the settings editable sections. ''' tabbed_pane = JTabbedPane() tab_titles = ["General", "Keystrokes", "Languages", "Projects"] for title in tab_titles: panel = self.build_settings_panel(title.lower()) tabbed_pane.addTab(title, panel) return tabbed_pane def build_settings_panel(self, text): ''' Call correspondent method to create panel for given tab text. ''' panel = getattr(self, "build_{}_panel".format(text))() return panel def build_general_panel(self): ''' Create the panel that'll go in the General tab. This should contain options for choosing which server to use for validation as well as default working dir. ''' panel = JPanel(GridBagLayout()) constraints = GridBagConstraints() constraints.insets = Insets(10, 10, 10, 10) panel = self.build_working_dir_panel(constraints, panel) panel = self.build_servers_panel(constraints, panel) return panel def build_working_dir_panel(self, constraints, panel): ''' Working directory row: label + field + button This is for users to browse for their preferred default directory when opening/creating a new file. ''' working_dir_label = JLabel("Working directory:") constraints.weightx = 0.30 constraints.gridx = 0 constraints.gridy = 0 constraints.anchor = GridBagConstraints.EAST panel.add(working_dir_label, constraints) self.field = JTextField() self.field.setEditable(False) # Can't find an elegant way to default to something that would be # crossplatform, and I can't leave the default field empty. if self.working_dir['default'] != "None": self.field.setText(self.working_dir['default']) else: self.field.setText(os.getcwd()) constraints.weightx = 0.60 constraints.gridx = 1 constraints.gridy = 0 constraints.fill = GridBagConstraints.HORIZONTAL constraints.insets = Insets(10, 10, 10, 5) panel.add(self.field, constraints) constraints.fill = 0 button = JButton("Browse", actionPerformed=self.browse) constraints.weightx = 0.10 constraints.gridx = 2 constraints.gridy = 0 constraints.insets = Insets(10, 0, 10, 10) panel.add(button, constraints) return panel def build_servers_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' constraints.insets = Insets(10, 10, 80, 10) server_label = JLabel("ORACC server location:") constraints.weightx = 0.30 constraints.gridx = 0 constraints.gridy = 1 panel.add(server_label, constraints) self.combo = self.build_servers_combobox() constraints.weightx = 0.70 constraints.gridx = 1 constraints.gridy = 1 constraints.gridwidth = 2 constraints.fill = GridBagConstraints.HORIZONTAL panel.add(self.combo, constraints) return panel def build_servers_combobox(self): combo = JComboBox() # Go through list of servers and add to combo box. for server in self.servers.keys(): if server != "default": combo_item = "{}: {}:{}".format(server, self.servers[server]['url'], self.servers[server]['port']) combo.addItem(combo_item) # If this item is the default one, set it as selected if server == self.servers['default']: combo.setSelectedItem(combo_item) return combo def build_buttons_panel(self): ''' Builds the buttons panel to save or cancel changes. TODO: Reset button to reset to defaults? ''' panel = JPanel(FlowLayout()) panel.add(JButton('Cancel', actionPerformed=self.cancel)) panel.add(JButton('Save', actionPerformed=self.save)) return panel def build_keystrokes_panel(self): ''' Create the panel that'll go in the Keystrokes tab. This should contain options for choosing which keystrokes are to be assigned to which actions. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_languages_panel(self): ''' Create the panel that'll go in the Languages tab. This should contain options for choosing which is the list of languages that can be included from the new ATF window and their abbrv. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_projects_panel(self): ''' Create the panel that'll go in the Projects tab. This should contain the list of preferred projects and a means to select which is the preferred default. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("Edit settings") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def display_error(self, keyword): ''' Display error message when keyword is not in settings file. ''' pass def cancel(self, event=None): ''' Close window and don't save changes. ''' self.dispose() def save(self, event=None): ''' Save changes made by user on local settings file. ''' # Update only the working_dir and the server for now # TODO: update keystrokes, projects list, etc. working_dir = self.field.getText() # The server format is "name: url:port". We only need "name" server = self.combo.getSelectedItem().split(':')[0] self.controller.update_config(working_dir, server) # Close window self.dispose() def browse(self, event=None): ''' Open new dialog for the user to select a path as default working dir. ''' default_path = self.field.getText() if not os.path.isdir(default_path): default_path = os.getcwd() fileChooser = JFileChooser(default_path) fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) # Fixed showDialog bug using showOpenDialog instead. The former was # duplicating the last folder name in the path due to a Java bug in # OSX in the implementation of JFileChooser! status = fileChooser.showOpenDialog(self) if status == JFileChooser.APPROVE_OPTION: self.field.setText(fileChooser.getSelectedFile().toString())
class ChannelPanel(JPanel): gbc = GridBagConstraints() def __init__(self): JPanel.__init__(self) self.setLayout(GridBagLayout()) self.setBorder(TitledBorder("Channel")) # some helper constants REL = GridBagConstraints.RELATIVE REM = GridBagConstraints.REMAINDER HORIZ = GridBagConstraints.HORIZONTAL NW = GridBagConstraints.NORTHWEST CENTER = GridBagConstraints.CENTER # --- title label = JLabel("Title:") self.constrain(label, REL, REL, REL, 1, HORIZ, CENTER, 1.0, 1.0, 2, 2, 2, 2) self.field_title = JTextField() self.field_title.setEditable(0) self.constrain(self.field_title, REL, REL, REM, 1, HORIZ, CENTER, 1.0, 1.0, 2, 2, 2, 2) # --- description label = JLabel("Description:") self.constrain(label, REL, REL, REL, 1, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) self.field_descr = JTextArea(3, 40) self.field_descr.setEditable(0) # wrap long lines self.field_descr.setLineWrap(1) # allow only full words to be wrapped self.field_descr.setWrapStyleWord(1) # ensure that the border look is the same self.field_descr.setBorder(self.field_title.getBorder()) self.constrain(self.field_descr, REL, REL, REM, 1, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) # --- location label = JLabel("Location:") self.constrain(label, REL, REL, REL, 1, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) self.field_location = JTextField() self.constrain(self.field_location, REL, REL, REM, REL, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) # --- last update label = JLabel("Last Update:") self.constrain(label, REL, REL, REL, REM, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) self.field_lastupdate = JTextField() self.field_lastupdate.setEditable(0) self.constrain(self.field_lastupdate, REL, REL, REM, REM, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) def setChannel(self, channel): self.channel = channel self.field_title.setText(channel.getTitle()) self.field_descr.setText(channel.getDescription()) self.field_location.setText(channel.getLocation().toString()) self.field_lastupdate.setText( channel.getSubscription().getLastUpdated().toString()) def refresh(self): self.setChannel(self.channel) def constrain(self, component, grid_x, grid_y, grid_width, grid_height, fill, anchor, weight_x, weight_y, top, left, bottom, right): container = self c = self.gbc c.gridx = grid_x c.gridy = grid_y c.gridwidth = grid_width c.gridheight = grid_height c.fill = fill c.anchor = anchor c.weightx = weight_x c.weighty = weight_y if (top + bottom + left + right > 0): c.insets = Insets(top, left, bottom, right) container.getLayout().setConstraints(component, c) container.add(component)
class ChatApp(JFrame): ## Constructor function, initiate the base classes and call the GUI def __init__(self): '''Calls the base class and main UI ''' # Call to the super class, initiates associated base classes super(ChatApp, self).__init__() # Call the Initial UI self.initUI() ## Build the GUI for login, uses GroupLayout Manager for component positioning def initUI(self): '''Initial UI and Widget creation takes place here! ''' self.setContentPane = JPanel() #self.setDefaultLookAndFeelDecorated(True) # Borders foreground_colour = Color(30,57,68) background_colour = Color(247,246,242) window_background = Color(145,190,210) self.border = BorderFactory.createLoweredBevelBorder() self.border2 = BorderFactory.createLineBorder(foreground_colour, 1, True) # Fonts self.entry_font= Font("Ubuntu Light", Font.BOLD, 20) self.label_font= Font("Ubuntu Light", Font.BOLD, 17) self.btn_font=Font("Ubuntu Light", Font.BOLD, 15) # Layout start layout=GroupLayout(self.getContentPane()) self.getContentPane().setLayout(layout) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) self.setPreferredSize(Dimension(300, 150)) # Create the labels user_label= JLabel(" Username : "******" Server : ", JLabel.LEFT, font=self.label_font) # Colours user_label.setForeground(foreground_colour) server_label.setForeground(foreground_colour) # Create the text entries self.username=JTextField(actionPerformed=self.continueEvent, border=self.border2, font = self.entry_font) self.server=JTextField(actionPerformed=self.continueEvent, border=self.border2, font = self.entry_font) # Colours self.username.setBackground(background_colour) self.server.setBackground(background_colour) self.username.setForeground(foreground_colour) self.server.setForeground(foreground_colour) # Allow editable self.username.setEditable(True) self.server.setEditable(True) # Create the buttons quit_btn=JButton(" Quit! ", actionPerformed=self.closeEvent, border=self.border2, font=self.btn_font) go_btn=JButton(" Go! ", actionPerformed=self.continueEvent, border=self.border2, font=self.btn_font) # Colours quit_btn.setBackground(background_colour) go_btn.setBackground(background_colour) quit_btn.setForeground(foreground_colour) go_btn.setForeground(foreground_colour) # Setting up the horizontal groups parameters layout.setHorizontalGroup(layout.createSequentialGroup() # Left side .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(user_label) .addComponent(server_label)) # Right side .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(self.username) .addComponent(self.server) .addGroup(layout.createSequentialGroup() .addComponent(quit_btn) .addComponent(go_btn))) ) # Setting up Vertical Groups layout.setVerticalGroup(layout.createSequentialGroup() # Top group .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(user_label) .addComponent(self.username)) # Middle group .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(server_label) .addComponent(self.server)) # Bottom group .addGroup(layout.createParallelGroup() .addComponent(quit_btn) .addComponent(go_btn)) ) # Finalise the GUI layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn]) self.getContentPane().setBackground(window_background) self.pack() self.setTitle('Chat Login') self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True) ## Event driven funtion to respond to quit button click def closeEvent(self,event): '''Function to close the login window ''' print("Goodbye!") exit() ## Event driven function to respond to send button click, grabs text and sends it down the wire def continueEvent(self,event): '''Function that retreives the login details for sending to the server ''' # Grab the text that has been entered user = self.username.getText() Host = self.server.getText() # Default port Port=60001 connected=False while not connected: # Try make a connection except when there isn't one available, then quit program' try: tn=telnetlib.Telnet(Host, Port) connected=True continue except: JOptionPane.showMessageDialog(self,'Connection Error, No Server Available!') self.username.setText('') self.server.setText('') self.username.requestFocusInWindow() return # Listen for a response response = tn.read_until('<<<') print(response) # Acknowledge with the username tn.write(user+'\r\n') # Receive validation of name, present dialog if not valid valid_name = tn.read_until('<') valid_name.strip() v_name, delim = valid_name.split('<') if v_name.strip() != 'OK': JOptionPane.showMessageDialog(self,'Bad Username, please choose another') self.username.setText('') self.username.requestFocusInWindow() return # Set the login GUI to hidden self.setVisible(False) ## <<<<<< I have no idea why this doesn't work but I suspect it's something to do with either inheritance or having 2 class instances # Call the main program, pass the connection as a parameter ChatClient(user,response , tn)
def studentProfileForm(data): global heading global tfStudentName global tfStudentPhone global taStudentAddress global tfStudentEmail global tfCourseName global tfCourseFee global tfStudentAssignTeacher global frame global btnEnter frame = JFrame(" Student ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 620) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 620) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel(" STUDENT PROFILE") heading.setBounds(200, 30, 150, 40) lbStudentName = JLabel("Student Name ") lbStudentPhone = JLabel("Phone") lbStudentEmail = JLabel("Email") lbStudentAddress = JLabel("Address") lbCourseName = JLabel("Course Name ") lbCourseFee = JLabel("Course Fee") lbStudentAssignTeacher = JLabel("Teacher") studentName = data[0].encode('ascii') studentPhone = data[1].encode('ascii') studentEmail = data[2].encode('ascii') studentAddress = data[3].encode('ascii') courseName = data[4].encode('ascii') courseFee = data[5] studentAssignTeacher = data[6].encode('ascii') tfStudentName = JTextField(studentName) tfStudentPhone = JTextField(studentPhone) taStudentAddress = JTextArea(studentAddress) tfStudentEmail = JTextField(studentEmail) tfCourseName = JTextField(courseName) tfCourseFee = JTextField(str(courseFee)) tfStudentAssignTeacher = JTextField(studentAssignTeacher) tfCourseName.setEditable(False) tfCourseFee.setEditable(False) tfStudentAssignTeacher.setEditable(False) tfStudentName.setEditable(False) lbStudentName.setBounds(70, 100, 130, 30) lbStudentPhone.setBounds(70, 150, 130, 30) lbStudentEmail.setBounds(70, 200, 130, 30) lbStudentAddress.setBounds(70, 250, 130, 30) lbCourseName.setBounds(70, 350, 130, 30) lbCourseFee.setBounds(70, 400, 130, 30) lbStudentAssignTeacher.setBounds(70, 450, 130, 30) tfStudentName.setBounds(220, 100, 130, 30) tfStudentPhone.setBounds(220, 150, 130, 30) tfStudentEmail.setBounds(220, 200, 130, 30) taStudentAddress.setBounds(220, 250, 130, 80) tfCourseName.setBounds(220, 350, 130, 30) tfCourseFee.setBounds(220, 400, 130, 30) tfStudentAssignTeacher.setBounds(220, 450, 130, 30) btnEnter = JButton("Update", actionPerformed=clickUpdateStudent) btnEnter.setBounds(350, 530, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickCancel) btnCancel.setBounds(100, 530, 100, 40) panel.add(heading) panel.add(lbStudentName) panel.add(lbStudentPhone) panel.add(lbStudentEmail) panel.add(lbStudentAddress) panel.add(lbCourseName) panel.add(lbCourseFee) panel.add(lbStudentAssignTeacher) panel.add(tfStudentName) panel.add(tfStudentPhone) panel.add(tfStudentEmail) panel.add(taStudentAddress) panel.add(tfCourseName) panel.add(tfCourseFee) panel.add(tfStudentAssignTeacher) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
class EditSettingsView(JDialog): def __init__(self, controller, working_dir, servers, console_style, edit_area_style, keystrokes, languages, projects): self.logger = logging.getLogger("NammuController") self.setAlwaysOnTop(True) self.controller = controller self.working_dir = working_dir self.servers = servers self.keystrokes = keystrokes self.languages = languages self.projects = projects self.console_fontsize = console_style['fontsize']['user'] self.console_font_color = console_style['font_color']['user'] self.console_bg_color = console_style['background_color']['user'] self.edit_area_fontsize = edit_area_style['fontsize']['user'] self.pane = self.getContentPane() # Grab the console color options from the console view self.consoleView = self.controller.controller.consoleController.view self.color_options = self.consoleView.colors.keys() def build(self): ''' Create all tab panels and put together to form the settings window. ''' self.setLayout(BorderLayout()) self.add(self.build_tabbed_panel(), BorderLayout.CENTER) self.add(self.build_buttons_panel(), BorderLayout.SOUTH) def build_tabbed_panel(self): ''' Build panel with tabs for each of the settings editable sections. ''' tabbed_pane = JTabbedPane() tab_titles = ["General", "Appearance", "Keystrokes", "Languages", "Projects"] for title in tab_titles: panel = self.build_settings_panel(title.lower()) tabbed_pane.addTab(title, panel) return tabbed_pane def build_settings_panel(self, text): ''' Call correspondent method to create panel for given tab text. ''' panel = getattr(self, "build_{}_panel".format(text))() return panel def build_general_panel(self): ''' Create the panel that'll go in the General tab. This should contain options for choosing which server to use for validation as well as default working dir. ''' panel = JPanel(GridBagLayout()) constraints = self.add_constraints(GridBagConstraints(), insets=Insets(10, 10, 10, 10)) self.build_working_dir_panel(constraints, panel) self.build_servers_panel(constraints, panel) return panel def add_constraints(self, constraints, weightx=None, gridx=None, gridy=None, fill=None, insets=None, gridwidth=None, anchor=None): ''' Wrapper around the various constraints we need to set. ''' # Cant use pythonic truth value test as we need 0 to evaluate as true if weightx is not None: constraints.weightx = weightx if gridx is not None: constraints.gridx = gridx if gridy is not None: constraints.gridy = gridy if fill is not None: constraints.fill = fill if insets is not None: constraints.insets = insets if gridwidth is not None: constraints.gridwidth = gridwidth if anchor is not None: constraints.anchor = anchor return constraints def build_working_dir_panel(self, constraints, panel): ''' Working directory row: label + field + button This is for users to browse for their preferred default directory when opening/creating a new file. ''' working_dir_label = JLabel("Working directory:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=0, anchor=GridBagConstraints.EAST) panel.add(working_dir_label, constraints) self.wd_field = JTextField() self.wd_field.setEditable(False) # Can't find an elegant way to default to something that would be # crossplatform, and I can't leave the default field empty. if self.working_dir['default'] != "None": self.wd_field.setText(self.working_dir['default']) else: self.wd_field.setText(os.getcwd()) constraints = self.add_constraints(constraints, weightx=0.60, gridx=1, gridy=0, fill=GridBagConstraints.HORIZONTAL, insets=Insets(10, 10, 10, 5)) panel.add(self.wd_field, constraints) constraints.fill = 0 button = JButton("Browse", actionPerformed=self.browse) constraints = self.add_constraints(constraints, weightx=0.10, gridx=2, gridy=0, insets=Insets(10, 0, 10, 10)) panel.add(button, constraints) def build_console_background_color_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' console_bg_label = JLabel("Console background color:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=2) panel.add(console_bg_label, constraints) self.bg_color_combo = self.build_combobox(self.color_options, self.console_bg_color) constraints = self.add_constraints(constraints, weightx=0.70, gridx=1, gridy=2, gridwidth=2, fill=GridBagConstraints.HORIZONTAL) panel.add(self.bg_color_combo, constraints) def build_console_font_color_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' console_font_label = JLabel("Console font color:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=3) panel.add(console_font_label, constraints) self.font_color_combo = self.build_combobox(self.color_options, self.console_font_color) constraints = self.add_constraints(constraints, weightx=0.70, gridx=1, gridy=3, gridwidth=2, fill=GridBagConstraints.HORIZONTAL) panel.add(self.font_color_combo, constraints) def build_servers_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' server_label = JLabel("ORACC server location:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=1, insets=Insets(10, 10, 80, 10)) panel.add(server_label, constraints) self.combo = self.build_servers_combobox() constraints = self.add_constraints(constraints, weightx=0.70, gridx=1, gridy=1, gridwidth=2, fill=GridBagConstraints.HORIZONTAL) panel.add(self.combo, constraints) def build_console_font_panel(self, constraints, panel): ''' Font size on a textfield. ''' fontzise_label = JLabel("Console font size:") constraints = self.add_constraints(constraints, weightx=0.20, gridx=0, gridy=0, fill=GridBagConstraints.HORIZONTAL) panel.add(fontzise_label, constraints) self.fs_field = JTextField() self.fs_field.setEditable(True) if self.console_fontsize: self.fs_field.setText("{}".format(self.console_fontsize)) else: self.fs_field.setText(self.controller.config[ 'console_style']['fontsize']['default']) constraints = self.add_constraints(constraints, weightx=0.80, gridx=1, gridy=0, fill=GridBagConstraints.HORIZONTAL) panel.add(self.fs_field, constraints) def build_edit_area_font_panel(self, constraints, panel): ''' Font size on a textfield. ''' fontzise_label = JLabel("Edit area font size:") constraints = self.add_constraints(constraints, weightx=0.20, gridx=0, gridy=4) panel.add(fontzise_label, constraints) self.edit_area_fs_field = JTextField() self.edit_area_fs_field.setEditable(True) if self.edit_area_fontsize: self.edit_area_fs_field.setText( "{}".format(self.edit_area_fontsize)) else: self.edit_area_fs_field.setText(self.controller.config[ 'edit_area_style']['fontsize']['default']) constraints = self.add_constraints(constraints, weightx=0.80, gridx=1, gridy=4, fill=GridBagConstraints.HORIZONTAL) panel.add(self.edit_area_fs_field, constraints) def build_combobox(self, choices, default): ''' Generic method to construct a combobox. choices should be an iterable of strings of the choices to be made and default should be a string which is equal to one of the values within the iterable. ''' combo = JComboBox() for choice in choices: combo.addItem(choice) combo.setSelectedItem(default) return combo def build_servers_combobox(self): combo = JComboBox() # Go through list of servers and add to combo box. for server in self.servers.keys(): if server != "default": combo_item = "{}: {}:{}".format(server, self.servers[server]['url'], self.servers[server]['port']) combo.addItem(combo_item) # If this item is the default one, set it as selected if server == self.servers['default']: combo.setSelectedItem(combo_item) return combo def build_buttons_panel(self): ''' Builds the buttons panel to save or cancel changes. TODO: Reset button to reset to defaults? ''' panel = JPanel(FlowLayout()) panel.add(JButton('Cancel', actionPerformed=self.cancel)) panel.add(JButton('Save', actionPerformed=self.save)) return panel def build_keystrokes_panel(self): ''' Create the panel that'll go in the Keystrokes tab. This should contain options for choosing which keystrokes are to be assigned to which actions. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_languages_panel(self): ''' Create the panel that'll go in the Languages tab. This should contain options for choosing which is the list of languages that can be included from the new ATF window and their abbrv. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_projects_panel(self): ''' Create the panel that'll go in the Projects tab. This should contain the list of preferred projects and a means to select which is the preferred default. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_appearance_panel(self): ''' Create the panel that'll go in the General tab. This should contain options for choosing which server to use for validation as well as default working dir. ''' panel = JPanel(GridBagLayout()) constraints = self.add_constraints(GridBagConstraints(), insets=Insets(10, 10, 10, 10)) self.build_console_font_panel(constraints, panel) self.build_console_font_color_panel(constraints, panel) self.build_console_background_color_panel(constraints, panel) self.build_edit_area_font_panel(constraints, panel) return panel def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("Edit settings") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def display_error(self, keyword): ''' Display error message when keyword is not in settings file. ''' pass def cancel(self, event=None): ''' Close window and don't save changes. ''' self.dispose() def validate_fontsize(self, input_size, target_key): ''' Method to validate an input fontsize. The target key points to either the console font sizes 'console_style' or the edit area font sizes 'edit_area_style'. If the value is invalid, return the previous user fontsize that was stored. The second return value is a bool indicating if the value has changed. ''' # Extract plain english from key name for use in error message target = target_key[:-6].replace('_', ' ') # Use isnumeric() to test if a unicode string only has digits if (input_size.isnumeric() and (8 <= int(input_size) <= 30)): return input_size, True else: input_size = self.controller.config[target_key]['fontsize']['user'] self.logger.error("Invalid {} font size. Please enter a " "number between 8 and 36.\n\n" "Font size left at " "previous value: {}".format(target, input_size)) return input_size, False def validate_colors(self, bg_color, font_color): ''' Validate console colors to ensure they do not match. The second return value is a bool indicating if the value has changed. ''' valid = True if bg_color == font_color: config = self.controller.config self.logger.error("Console font colour cannot match background" " colour. Resetting to default values.") bg_color = config['console_style']['background_color']['default'] font_color = config['console_style']['font_color']['default'] valid = False return bg_color, font_color, valid def validate_working_dir(self, working_dir): ''' Method to validate input working directories. If directory does not exist or if a path to a file is provided instead of a path to a directory the method returns None. The second return value is a bool indicating if the value has changed. ''' if os.path.isdir(working_dir): return working_dir, True else: self.logger.error("{} is not a valid working directory." " No working directory has been " "saved".format(working_dir)) return None, False def validate_all_inputs(self, working_dir, console_fontsize, edit_area_fontsize, bg_color, font_color): ''' Wrapper around the input validation methods. Returns a tuple containing the validated inputs with the last value in the tuple a boolean set to False if any of the values have been altered during the validation and True if there have been no changes. ''' # Collect the results of each validation. In future we might use this # to provide more detailed error logging on bad user input validation_results = [] # Validate the working directory input string working_dir, v = self.validate_working_dir(working_dir) validation_results.append(v) # Validate the input fontsizes con_size, v = self.validate_fontsize(console_fontsize, 'console_style') validation_results.append(v) edit_size, v = self.validate_fontsize(edit_area_fontsize, 'edit_area_style') validation_results.append(v) # Validate input console colors bg_color, font_color, v = self.validate_colors(bg_color, font_color) validation_results.append(v) return (working_dir, int(con_size), font_color, bg_color, int(edit_size), all(validation_results)) def save(self, event=None): ''' Save changes made by user on local settings file. ''' # Update only the working_dir and the server for now # TODO: update keystrokes, projects list, etc. working_dir = self.wd_field.getText() # Read the fontsize from the textfield console_fontsize = self.fs_field.getText() edit_area_fontsize = self.edit_area_fs_field.getText() # Get the user selected font and background colours bg_color = self.bg_color_combo.getSelectedItem() font_color = self.font_color_combo.getSelectedItem() validated = self.validate_all_inputs(working_dir, console_fontsize, edit_area_fontsize, bg_color, font_color) # The server format is "name: url:port". We only need "name" server = self.combo.getSelectedItem().split(':')[0] self.controller.update_config(validated[0], server, validated[1], validated[2], validated[3], int(validated[4])) # If no values have been changed, print that settings have been # updated without errors if validated[5]: self.logger.info("Settings have been successfully updated.") # On saving settings, update the console and edit area properties self.controller.refreshConsole() self.controller.refreshEditArea() # Close window self.dispose() # Refresh the syntax highlighting in a separate thread so it updates # after everything else has been done. runSwingLater(self.controller.controller.initHighlighting) def browse(self, event=None): ''' Open new dialog for the user to select a path as default working dir. ''' default_path = self.wd_field.getText() if not os.path.isdir(default_path): default_path = os.getcwd() fileChooser = JFileChooser(default_path) fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) # Fixed showDialog bug using showOpenDialog instead. The former was # duplicating the last folder name in the path due to a Java bug in # OSX in the implementation of JFileChooser! status = fileChooser.showOpenDialog(self) if status == JFileChooser.APPROVE_OPTION: self.wd_field.setText(fileChooser.getSelectedFile().toString())
def addStudent(courseName, courseFee, v): global tfStudentName global tfStudentPhone global tfStudentEmail global taStudentAddress global tfCourseName global tfCourseFee global cbStudentAssignTeacher global frame frame = JFrame("Add Student ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 600) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 600) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("ADD STUDENT") heading.setBounds(200, 30, 150, 40) lbCourseName = JLabel(" Course name") lbCourseFee = JLabel(" Course Fee") lbStudentName = JLabel("Student name ") lbStudentPhone = JLabel("Phone") lbStudentEmail = JLabel("Email Id") lbStudentAddress = JLabel("Address") lbStudentAssignTeacher = JLabel("Student Assign teacher ") tfCourseName = JTextField(courseName) tfCourseFee = JTextField(str(courseFee)) tfStudentName = JTextField() tfStudentPhone = JTextField() tfStudentEmail = JTextField() taStudentAddress = JTextArea() cbStudentAssignTeacher = JComboBox(v) tfCourseName.setEditable(False) tfCourseFee.setEditable(False) lbCourseName.setBounds(70, 100, 130, 30) lbCourseFee.setBounds(70, 150, 130, 30) lbStudentName.setBounds(70, 200, 130, 30) lbStudentPhone.setBounds(70, 250, 130, 30) lbStudentEmail.setBounds(70, 300, 130, 30) lbStudentAddress.setBounds(70, 350, 130, 80) lbStudentAssignTeacher.setBounds(70, 450, 130, 30) tfCourseName.setBounds(220, 100, 130, 30) tfCourseFee.setBounds(220, 150, 130, 30) tfStudentName.setBounds(220, 200, 130, 30) tfStudentPhone.setBounds(220, 250, 130, 30) tfStudentEmail.setBounds(220, 300, 130, 30) taStudentAddress.setBounds(220, 350, 130, 80) cbStudentAssignTeacher.setBounds(220, 450, 130, 30) btnEnter = JButton("ADD", actionPerformed=clickAddStudent) btnEnter.setBounds(350, 510, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickbtnCancelForm) btnCancel.setBounds(50, 510, 100, 40) panel.add(heading) panel.add(lbCourseName) panel.add(lbCourseFee) panel.add(lbStudentName) panel.add(lbStudentPhone) panel.add(lbStudentEmail) panel.add(lbStudentAddress) panel.add(lbStudentAssignTeacher) panel.add(tfCourseName) panel.add(tfCourseFee) panel.add(tfStudentName) panel.add(tfStudentPhone) panel.add(tfStudentEmail) panel.add(taStudentAddress) panel.add(cbStudentAssignTeacher) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
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 ChannelPanel(JPanel): gbc = GridBagConstraints() def __init__(self): JPanel.__init__(self) self.setLayout(GridBagLayout()) self.setBorder(TitledBorder("Channel")) # some helper constants REL = GridBagConstraints.RELATIVE REM = GridBagConstraints.REMAINDER HORIZ = GridBagConstraints.HORIZONTAL NW = GridBagConstraints.NORTHWEST CENTER = GridBagConstraints.CENTER # --- title label = JLabel("Title:") self.constrain(label, REL, REL, REL, 1, HORIZ, CENTER, 1.0, 1.0, 2, 2, 2, 2) self.field_title = JTextField() self.field_title.setEditable(0) self.constrain(self.field_title, REL, REL, REM, 1, HORIZ, CENTER, 1.0, 1.0, 2, 2, 2, 2) # --- description label = JLabel("Description:") self.constrain(label, REL, REL, REL, 1, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) self.field_descr = JTextArea(3, 40) self.field_descr.setEditable(0) # wrap long lines self.field_descr.setLineWrap(1) # allow only full words to be wrapped self.field_descr.setWrapStyleWord(1) # ensure that the border look is the same self.field_descr.setBorder(self.field_title.getBorder()) self.constrain(self.field_descr, REL, REL, REM, 1, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) # --- location label = JLabel("Location:") self.constrain(label, REL, REL, REL, 1, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) self.field_location = JTextField() self.constrain(self.field_location, REL, REL, REM, REL, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) # --- last update label = JLabel("Last Update:") self.constrain(label, REL, REL, REL, REM, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) self.field_lastupdate = JTextField() self.field_lastupdate.setEditable(0) self.constrain(self.field_lastupdate, REL, REL, REM, REM, HORIZ, NW, 1.0, 1.0, 2, 2, 2, 2) def setChannel(self, channel): self.channel = channel self.field_title.setText(channel.getTitle()) self.field_descr.setText(channel.getDescription()) self.field_location.setText(channel.getLocation().toString()) self.field_lastupdate.setText(channel.getSubscription().getLastUpdated().toString()) def refresh(self): self.setChannel(self.channel) def constrain(self, component, grid_x, grid_y, grid_width, grid_height, fill, anchor, weight_x, weight_y, top, left, bottom, right): container = self c = self.gbc c.gridx = grid_x c.gridy = grid_y c.gridwidth = grid_width c.gridheight = grid_height c.fill = fill c.anchor = anchor c.weightx = weight_x c.weighty = weight_y if (top + bottom + left + right > 0): c.insets = Insets(top, left, bottom, right) container.getLayout().setConstraints(component, c) container.add(component)
class EditSettingsView(JDialog): def __init__(self, controller, working_dir, servers, console_style, edit_area_style, keystrokes, languages, projects): self.logger = logging.getLogger("NammuController") self.setAlwaysOnTop(True) self.controller = controller self.working_dir = working_dir self.servers = servers self.keystrokes = keystrokes self.languages = languages self.projects = projects self.console_fontsize = console_style['fontsize']['user'] self.console_font_color = console_style['font_color']['user'] self.console_bg_color = console_style['background_color']['user'] self.edit_area_fontsize = edit_area_style['fontsize']['user'] self.pane = self.getContentPane() # Grab the console color options from the console view self.consoleView = self.controller.controller.consoleController.view self.color_options = self.consoleView.colors.keys() def build(self): ''' Create all tab panels and put together to form the settings window. ''' self.setLayout(BorderLayout()) self.add(self.build_tabbed_panel(), BorderLayout.CENTER) self.add(self.build_buttons_panel(), BorderLayout.SOUTH) def build_tabbed_panel(self): ''' Build panel with tabs for each of the settings editable sections. ''' tabbed_pane = JTabbedPane() tab_titles = [ "General", "Appearance", "Keystrokes", "Languages", "Projects" ] for title in tab_titles: panel = self.build_settings_panel(title.lower()) tabbed_pane.addTab(title, panel) return tabbed_pane def build_settings_panel(self, text): ''' Call correspondent method to create panel for given tab text. ''' panel = getattr(self, "build_{}_panel".format(text))() return panel def build_general_panel(self): ''' Create the panel that'll go in the General tab. This should contain options for choosing which server to use for validation as well as default working dir. ''' panel = JPanel(GridBagLayout()) constraints = self.add_constraints(GridBagConstraints(), insets=Insets(10, 10, 10, 10)) self.build_working_dir_panel(constraints, panel) self.build_servers_panel(constraints, panel) return panel def add_constraints(self, constraints, weightx=None, gridx=None, gridy=None, fill=None, insets=None, gridwidth=None, anchor=None): ''' Wrapper around the various constraints we need to set. ''' # Cant use pythonic truth value test as we need 0 to evaluate as true if weightx is not None: constraints.weightx = weightx if gridx is not None: constraints.gridx = gridx if gridy is not None: constraints.gridy = gridy if fill is not None: constraints.fill = fill if insets is not None: constraints.insets = insets if gridwidth is not None: constraints.gridwidth = gridwidth if anchor is not None: constraints.anchor = anchor return constraints def build_working_dir_panel(self, constraints, panel): ''' Working directory row: label + field + button This is for users to browse for their preferred default directory when opening/creating a new file. ''' working_dir_label = JLabel("Working directory:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=0, anchor=GridBagConstraints.EAST) panel.add(working_dir_label, constraints) self.wd_field = JTextField() self.wd_field.setEditable(False) # Can't find an elegant way to default to something that would be # crossplatform, and I can't leave the default field empty. if self.working_dir['default'] != "None": self.wd_field.setText(self.working_dir['default']) else: self.wd_field.setText(os.getcwd()) constraints = self.add_constraints(constraints, weightx=0.60, gridx=1, gridy=0, fill=GridBagConstraints.HORIZONTAL, insets=Insets(10, 10, 10, 5)) panel.add(self.wd_field, constraints) constraints.fill = 0 button = JButton("Browse", actionPerformed=self.browse) constraints = self.add_constraints(constraints, weightx=0.10, gridx=2, gridy=0, insets=Insets(10, 0, 10, 10)) panel.add(button, constraints) def build_console_background_color_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' console_bg_label = JLabel("Console background color:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=2) panel.add(console_bg_label, constraints) self.bg_color_combo = self.build_combobox(self.color_options, self.console_bg_color) constraints = self.add_constraints(constraints, weightx=0.70, gridx=1, gridy=2, gridwidth=2, fill=GridBagConstraints.HORIZONTAL) panel.add(self.bg_color_combo, constraints) def build_console_font_color_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' console_font_label = JLabel("Console font color:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=3) panel.add(console_font_label, constraints) self.font_color_combo = self.build_combobox(self.color_options, self.console_font_color) constraints = self.add_constraints(constraints, weightx=0.70, gridx=1, gridy=3, gridwidth=2, fill=GridBagConstraints.HORIZONTAL) panel.add(self.font_color_combo, constraints) def build_servers_panel(self, constraints, panel): ''' Server location row: label + dropdown Contains a drop down with the servers to choose from. ''' server_label = JLabel("ORACC server location:") constraints = self.add_constraints(constraints, weightx=0.30, gridx=0, gridy=1, insets=Insets(10, 10, 80, 10)) panel.add(server_label, constraints) self.combo = self.build_servers_combobox() constraints = self.add_constraints(constraints, weightx=0.70, gridx=1, gridy=1, gridwidth=2, fill=GridBagConstraints.HORIZONTAL) panel.add(self.combo, constraints) def build_console_font_panel(self, constraints, panel): ''' Font size on a textfield. ''' fontzise_label = JLabel("Console font size:") constraints = self.add_constraints(constraints, weightx=0.20, gridx=0, gridy=0, fill=GridBagConstraints.HORIZONTAL) panel.add(fontzise_label, constraints) self.fs_field = JTextField() self.fs_field.setEditable(True) if self.console_fontsize: self.fs_field.setText("{}".format(self.console_fontsize)) else: self.fs_field.setText( self.controller.config['console_style']['fontsize']['default']) constraints = self.add_constraints(constraints, weightx=0.80, gridx=1, gridy=0, fill=GridBagConstraints.HORIZONTAL) panel.add(self.fs_field, constraints) def build_edit_area_font_panel(self, constraints, panel): ''' Font size on a textfield. ''' fontzise_label = JLabel("Edit area font size:") constraints = self.add_constraints(constraints, weightx=0.20, gridx=0, gridy=4) panel.add(fontzise_label, constraints) self.edit_area_fs_field = JTextField() self.edit_area_fs_field.setEditable(True) if self.edit_area_fontsize: self.edit_area_fs_field.setText("{}".format( self.edit_area_fontsize)) else: self.edit_area_fs_field.setText( self.controller.config['edit_area_style']['fontsize'] ['default']) constraints = self.add_constraints(constraints, weightx=0.80, gridx=1, gridy=4, fill=GridBagConstraints.HORIZONTAL) panel.add(self.edit_area_fs_field, constraints) def build_combobox(self, choices, default): ''' Generic method to construct a combobox. choices should be an iterable of strings of the choices to be made and default should be a string which is equal to one of the values within the iterable. ''' combo = JComboBox() for choice in choices: combo.addItem(choice) combo.setSelectedItem(default) return combo def build_servers_combobox(self): combo = JComboBox() # Go through list of servers and add to combo box. for server in self.servers.keys(): if server != "default": combo_item = "{}: {}:{}".format(server, self.servers[server]['url'], self.servers[server]['port']) combo.addItem(combo_item) # If this item is the default one, set it as selected if server == self.servers['default']: combo.setSelectedItem(combo_item) return combo def build_buttons_panel(self): ''' Builds the buttons panel to save or cancel changes. TODO: Reset button to reset to defaults? ''' panel = JPanel(FlowLayout()) panel.add(JButton('Cancel', actionPerformed=self.cancel)) panel.add(JButton('Save', actionPerformed=self.save)) return panel def build_keystrokes_panel(self): ''' Create the panel that'll go in the Keystrokes tab. This should contain options for choosing which keystrokes are to be assigned to which actions. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_languages_panel(self): ''' Create the panel that'll go in the Languages tab. This should contain options for choosing which is the list of languages that can be included from the new ATF window and their abbrv. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_projects_panel(self): ''' Create the panel that'll go in the Projects tab. This should contain the list of preferred projects and a means to select which is the preferred default. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel def build_appearance_panel(self): ''' Create the panel that'll go in the General tab. This should contain options for choosing which server to use for validation as well as default working dir. ''' panel = JPanel(GridBagLayout()) constraints = self.add_constraints(GridBagConstraints(), insets=Insets(10, 10, 10, 10)) self.build_console_font_panel(constraints, panel) self.build_console_font_color_panel(constraints, panel) self.build_console_background_color_panel(constraints, panel) self.build_edit_area_font_panel(constraints, panel) return panel def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("Edit settings") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def display_error(self, keyword): ''' Display error message when keyword is not in settings file. ''' pass def cancel(self, event=None): ''' Close window and don't save changes. ''' self.dispose() def validate_fontsize(self, input_size, target_key): ''' Method to validate an input fontsize. The target key points to either the console font sizes 'console_style' or the edit area font sizes 'edit_area_style'. If the value is invalid, return the previous user fontsize that was stored. The second return value is a bool indicating if the value has changed. ''' # Extract plain english from key name for use in error message target = target_key[:-6].replace('_', ' ') # Use isnumeric() to test if a unicode string only has digits if (input_size.isnumeric() and (8 <= int(input_size) <= 30)): return input_size, True else: input_size = self.controller.config[target_key]['fontsize']['user'] self.logger.error("Invalid {} font size. Please enter a " "number between 8 and 36.\n\n" "Font size left at " "previous value: {}".format(target, input_size)) return input_size, False def validate_colors(self, bg_color, font_color): ''' Validate console colors to ensure they do not match. The second return value is a bool indicating if the value has changed. ''' valid = True if bg_color == font_color: config = self.controller.config self.logger.error("Console font colour cannot match background" " colour. Resetting to default values.") bg_color = config['console_style']['background_color']['default'] font_color = config['console_style']['font_color']['default'] valid = False return bg_color, font_color, valid def validate_working_dir(self, working_dir): ''' Method to validate input working directories. If directory does not exist or if a path to a file is provided instead of a path to a directory the method returns None. The second return value is a bool indicating if the value has changed. ''' if os.path.isdir(working_dir): return working_dir, True else: self.logger.error("{} is not a valid working directory." " No working directory has been " "saved".format(working_dir)) return None, False def validate_all_inputs(self, working_dir, console_fontsize, edit_area_fontsize, bg_color, font_color): ''' Wrapper around the input validation methods. Returns a tuple containing the validated inputs with the last value in the tuple a boolean set to False if any of the values have been altered during the validation and True if there have been no changes. ''' # Collect the results of each validation. In future we might use this # to provide more detailed error logging on bad user input validation_results = [] # Validate the working directory input string working_dir, v = self.validate_working_dir(working_dir) validation_results.append(v) # Validate the input fontsizes con_size, v = self.validate_fontsize(console_fontsize, 'console_style') validation_results.append(v) edit_size, v = self.validate_fontsize(edit_area_fontsize, 'edit_area_style') validation_results.append(v) # Validate input console colors bg_color, font_color, v = self.validate_colors(bg_color, font_color) validation_results.append(v) return (working_dir, int(con_size), font_color, bg_color, int(edit_size), all(validation_results)) def save(self, event=None): ''' Save changes made by user on local settings file. ''' # Update only the working_dir and the server for now # TODO: update keystrokes, projects list, etc. working_dir = self.wd_field.getText() # Read the fontsize from the textfield console_fontsize = self.fs_field.getText() edit_area_fontsize = self.edit_area_fs_field.getText() # Get the user selected font and background colours bg_color = self.bg_color_combo.getSelectedItem() font_color = self.font_color_combo.getSelectedItem() validated = self.validate_all_inputs(working_dir, console_fontsize, edit_area_fontsize, bg_color, font_color) # The server format is "name: url:port". We only need "name" server = self.combo.getSelectedItem().split(':')[0] self.controller.update_config(validated[0], server, validated[1], validated[2], validated[3], int(validated[4])) # If no values have been changed, print that settings have been # updated without errors if validated[5]: self.logger.info("Settings have been successfully updated.") # On saving settings, update the console and edit area properties self.controller.refreshConsole() self.controller.refreshEditArea() # Close window self.dispose() # Refresh the syntax highlighting in a separate thread so it updates # after everything else has been done. runSwingLater(self.controller.controller.initHighlighting) def browse(self, event=None): ''' Open new dialog for the user to select a path as default working dir. ''' default_path = self.wd_field.getText() if not os.path.isdir(default_path): default_path = os.getcwd() fileChooser = JFileChooser(default_path) fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) # Fixed showDialog bug using showOpenDialog instead. The former was # duplicating the last folder name in the path due to a Java bug in # OSX in the implementation of JFileChooser! status = fileChooser.showOpenDialog(self) if status == JFileChooser.APPROVE_OPTION: self.wd_field.setText(fileChooser.getSelectedFile().toString())
class JTabPanel(JSplitPane, ActionListener, FocusListener): def __init__(self, ui): JSplitPane.__init__(self, JSplitPane.HORIZONTAL_SPLIT) self._ui = ui # create the executor object self._executor = Executor(self, ui.callbacks) #### # start Left Top split layout jLeftTopPanel = JPanel() jMenuPanel = JPanel() #Load button self.jLoad = JButton(Strings.jLoad_text) self.jLoad.addActionListener(self) #File name text field self.jFileName = JTextField(Strings.jFileName_default, 30) self.jFileName.setHorizontalAlignment(JTextField.CENTER) self.jFileName.setEditable(False) #Save button self.jSave = JButton(Strings.jSave_text) self.jSave.addActionListener(self) #Exit button self.jExit = JButton(Strings.jExit_text) self.jExit.addActionListener(self) #Wiki button (URL) self.jWiki = JButton(Strings.jWiki_title) self.jWiki.setToolTipText(Strings.jWiki_tooltip) self.jWiki.addActionListener(self) # make it borderless self.jWiki.setBorder(EmptyBorder(0, 0, 0, 0)) self.jWiki.setBorderPainted(False) self.jWiki.setContentAreaFilled(False) #Console text area jConsoleText = JTextArea() jConsoleText.setEditable(0) jConsoleText.setWrapStyleWord(1) jConsoleText.setRows(10) #set initial text jConsoleText.setText(Strings.jConsoleText_help) #make scrollable jScrollConsolePane = JScrollPane() jScrollConsolePane.setViewportView(jConsoleText) jMenuPanelLayout = GroupLayout(jMenuPanel) jMenuPanel.setLayout(jMenuPanelLayout) jMenuPanelLayout.setHorizontalGroup( jMenuPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addGroup(jMenuPanelLayout.createSequentialGroup().addContainerGap( ).addComponent(self.jLoad).addComponent( self.jFileName).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( self.jSave).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addComponent(self.jWiki).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( self.jExit).addContainerGap())) jMenuPanelLayout.setVerticalGroup( jMenuPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( jMenuPanelLayout.createSequentialGroup().addGroup( jMenuPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.jLoad).addComponent( self.jFileName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.jSave).addComponent( self.jWiki).addComponent( self.jExit)))) jLeftTopPanelLayout = GroupLayout(jLeftTopPanel) jLeftTopPanel.setLayout(jLeftTopPanelLayout) jLeftTopPanelLayout.setHorizontalGroup( jLeftTopPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( jMenuPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE).addComponent( jScrollConsolePane, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, 32767)) jLeftTopPanelLayout.setVerticalGroup( jLeftTopPanelLayout. createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, jLeftTopPanelLayout.createSequentialGroup().addComponent( jMenuPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( jScrollConsolePane, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, 32767))) # end Left Top split layout #### #### # start Left Down split layout jLeftDownPanel = JPanel() jMenu2Panel = JPanel() #Clear button self.jClear = JButton(Strings.jClear_text) self.jClear.setToolTipText(Strings.jClear_tooltip) self.jClear.addActionListener(self) #Run button self.jRun = JButton(Strings.jRun_text) self.jRun.setToolTipText(Strings.jRun_tooltip) self.jRun.addActionListener(self) #Variables text area jVarsPane = JTextPane() jVarsPane.setFont(Font('Monospaced', Font.PLAIN, 11)) jVarsPane.addFocusListener(self) # set initial value jVarsPane.setText(Strings.jVarsPane_header) # make scrollable jScrollpaneLeftDown = JScrollPane() jScrollpaneLeftDown.setViewportView(jVarsPane) jMenu2PanelLayout = GroupLayout(jMenu2Panel) jMenu2Panel.setLayout(jMenu2PanelLayout) jMenu2PanelLayout.setHorizontalGroup( jMenu2PanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( jMenu2PanelLayout.createSequentialGroup().addContainerGap( ).addComponent(self.jClear).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED, 100, 32767).addComponent(self.jRun).addContainerGap())) jMenu2PanelLayout.setVerticalGroup( jMenu2PanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( jMenu2PanelLayout.createSequentialGroup().addGroup( jMenu2PanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.jClear).addComponent(self.jRun)))) jLeftDownPanelLayout = GroupLayout(jLeftDownPanel) jLeftDownPanel.setLayout(jLeftDownPanelLayout) jLeftDownPanelLayout.setHorizontalGroup( jLeftDownPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( jMenu2Panel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE).addComponent( jScrollpaneLeftDown, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, 32767)) jLeftDownPanelLayout.setVerticalGroup( jLeftDownPanelLayout. createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, jLeftDownPanelLayout.createSequentialGroup().addComponent( jMenu2Panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( jScrollpaneLeftDown, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, 32767))) # end Left Down split layout #### #### # start Left layout jSplitPaneLeft = JSplitPane(JSplitPane.VERTICAL_SPLIT, jLeftTopPanel, jLeftDownPanel) jSplitPaneLeft.setDividerLocation(300) # end Left layout #### #### # start Right layout jScriptPane = JTextPane() jScriptPane.setFont(Font('Monospaced', Font.PLAIN, 11)) # set initial value jScriptPane.setText(Strings.jScriptPane_header) #jScriptPane.addMouseListener(self) jScrollPaneRight = JScrollPane() jScrollPaneRight.setViewportView(jScriptPane) # end Right layout #### self.setLeftComponent(jSplitPaneLeft) self.setRightComponent(jScrollPaneRight) self.setDividerLocation(450) #Exported variables self.jConsoleText = jConsoleText self.jScrollConsolePane = jScrollConsolePane self.jScriptPane = jScriptPane self.jVarsPane = jVarsPane def actionPerformed(self, event): #Load button was clicked #> opens the file chooser #> opens and parses the file #> populates the persistand value and script panes #> display path inside FileName field if self.jLoad == event.getSource(): if self.jFileName.getText() == Strings.jFileName_default: jFileChooser = JFileChooser() else: jFileChooser = JFileChooser(self.jFileName.getText()) result = jFileChooser.showOpenDialog(None) if result == JFileChooser.APPROVE_OPTION: selectedFile = jFileChooser.getSelectedFile() #Update the Tab Title if it contains a file name or default name currentTitle = self._ui.getTabName(self) currentFile = FileSystems.getDefault().getPath( self.jFileName.getText()).getFileName().toString() if self.jFileName.getText( ) == Strings.jFileName_default or currentTitle == currentFile: self._ui.setTabName( self, selectedFile.toPath().getFileName().toString()) # read from file (vars, script) = FileUtils.read(selectedFile.toPath()) if vars is None or script is None: # content could not be parsed JOptionPane.showMessageDialog(None, Strings.FileUtils_error, Strings.FileUtils_error, JOptionPane.ERROR_MESSAGE) else: # update var and scipt content self.jVarsPane.setText(vars) self.jScriptPane.setText(script) self._executor.init(vars) # update the File Name to the current choosen file self.jFileName.setText(selectedFile.getAbsolutePath()) #Save button clicked #> open the file chooser #> creates the file content #> writes the file on disk if self.jSave == event.getSource(): if self.jFileName.getText() == Strings.jFileName_default: jFileChooser = JFileChooser() else: jFileChooser = JFileChooser(self.jFileName.getText()) #self.jFileName.setText(selectedFile.getAbsolutePath()) result = jFileChooser.showSaveDialog(None) if result == JFileChooser.APPROVE_OPTION: selectedFile = jFileChooser.getSelectedFile() self.jFileName.setText(selectedFile.getAbsolutePath()) FileUtils.write(selectedFile.toPath(), self.jVarsPane.getText(), self.jScriptPane.getText()) #Wiki button clicked if self.jWiki == event.getSource(): uri = URI.create("https://github.com/DanNegrea/PyRules") if uri and Desktop.isDesktopSupported() and Desktop.getDesktop( ).isSupported(Desktop.Action.BROWSE): Desktop.getDesktop().browse(uri) #Exit button clicked if self.jExit == event.getSource(): result = JOptionPane.showConfirmDialog( None, Strings.jExit_confim_question, Strings.jExit_confim_title, JOptionPane.YES_NO_OPTION) if result == 0: self._ui.deleteTab(self) #Clear button clicked if self.jClear == event.getSource(): self.jConsoleText.setText("") self.log(self._executor.getVars(), "state") #Run once button clicked if self.jRun == event.getSource(): if self.isRequestFocusEnabled(): print "is RequestFocusEnabled" else: print "is NOT RequestFocusEnabled" if self.isFocusOwner(): print "is FocusOwner" else: print "is NOT FocusOwner" # request to init the vars (if edited) self.initVars() # request execution with toolFlag set to 999 (Run once) self.execute(999) def focusGained(self, event): pass #Reinitialize the state variables (Vars) def focusLost(self, event): if self.jVarsPane == event.getSource(): self.initVars() #Init the vars (persistant variables) def initVars(self): # get the text from the Vars pane end = self.jVarsPane.document.length varsText = self.jVarsPane.document.getText(0, end) # the executor initializes Vals if required self._executor.init(varsText) #Call the executor def execute(self, toolFlag, messageIsRequest=None, messageInfo=None): end = self.jScriptPane.document.length scriptText = self.jScriptPane.document.getText(0, end) self._executor.execute(scriptText, toolFlag, messageIsRequest, messageInfo) #Log the information into the console screen # type can be: # err - when printing errors # state - when printing the state variables (Vars) def log(self, obj, type=""): if type == "err": self.jConsoleText.append(Strings.jConsoleText_error) if type == "state": self.jConsoleText.append(Strings.jConsoleText_state) # if string just append. else use pformat from pprint if isinstance(obj, str): self.jConsoleText.append(obj + "\n") else: self.jConsoleText.append(pformat(obj) + "\n") # scroll to bottom verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar() verticalScrollBar.setValue(verticalScrollBar.getMaximum())
def createStudentFeeForm(stFeeObj): global tfStudentId global tfStudentName global tfTotalAmount global tfPaidAmount global tfRemainingAmount global frame frame = JFrame("Student Fee Form ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,500) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,500) panel.setLocation(0,0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("STUDENT FEE") heading.setBounds(200,30,150,40) lbStudentId = JLabel(" Student id") lbStudentName = JLabel(" student name") lbTotalAmount = JLabel("Total Amount ") lbPaidAmount = JLabel("Paid Amount") lbRemainingAmount = JLabel("Remaining amount") studentId =getattr(stFeeObj,'studentId') studentName =getattr(stFeeObj,'studentName') totalAmount =getattr(stFeeObj,'totalAmount') paidAmount =getattr(stFeeObj,'paidAmount') remainingAmount =getattr(stFeeObj,'remainingAmount') tfStudentId = JTextField(str(studentId)) tfStudentName = JTextField(str(studentName)) tfTotalAmount = JTextField(str(totalAmount)) tfPaidAmount = JTextField(str(paidAmount)) tfRemainingAmount = JTextField(str(remainingAmount)) tfStudentId.setEditable(False) tfStudentName.setEditable(False) tfTotalAmount.setEditable(False) tfRemainingAmount.setEditable(False) lbStudentId.setBounds(70,100,130,30) lbStudentName.setBounds(70,150,130,30) lbTotalAmount.setBounds(70,200,130,30) lbPaidAmount.setBounds(70,250,130,30) lbRemainingAmount.setBounds(70,300,130,30) tfStudentId.setBounds(220,100,130,30) tfStudentName.setBounds(220,150,130,30) tfTotalAmount.setBounds(220,200,130,30) tfPaidAmount.setBounds(220,250,130,30) tfRemainingAmount.setBounds(220,300,130,30) btnPay = JButton("Paid",actionPerformed=clickPay) btnPay.setBounds(350,410,100,40) btnCancel = JButton("Cancel",actionPerformed=clickbtnCancelForm) btnCancel.setBounds(50,410,100,40) panel.add(heading) panel.add(lbStudentId) panel.add(lbStudentName) panel.add(lbTotalAmount) panel.add(lbPaidAmount) panel.add(lbRemainingAmount) panel.add(tfStudentId) panel.add(tfStudentName) panel.add(tfTotalAmount) panel.add(tfPaidAmount) panel.add(tfRemainingAmount) panel.add(btnPay) panel.add(btnCancel) frame.add(panel)
class BurpExtender(IBurpExtender, ITab, IProxyListener): def exec_module(self, messageIsRequest=0, message=None): module_path = M_PATH if M_PATH else str( self.fc.getSelectedFile()) + "/" sys.meta_path = [ moduleImporter(module_path, messageIsRequest, message) ] modules = [m[1] for m in self.dataModel.getDataVector() if m[0]] #modules = os.listdir(module_path) for module in modules: module_name = module[:-3] if module[-3:] == ".py" else module exec("import " + module_name) return sys.meta_path[0].message def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("Module Importer") self.out = callbacks.getStdout() self.tab = JPanel(GridBagLayout()) self.tableData = [] colNames = ('Enabled', 'Module') self.dataModel = MyTableModel(self.tableData, colNames) self.table = JTable(self.dataModel) self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 4 c.gridheight = 6 c.gridwidth = 6 c.weightx = 0.6 c.weighty = 0.5 self.tab.add(self.tablecont, c) self.fc = JFileChooser() self.fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) label_for_openDirectory = JLabel("Module Importer") c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 self.tab.add(label_for_openDirectory, c) label_plugin_desc = JLabel( "This module makes your development of Burp Suite Plugin easier.") label_plugin_desc.setPreferredSize(Dimension(400, 50)) c = GridBagConstraints() c.gridx = 0 c.gridy = 1 self.tab.add(label_plugin_desc, c) label_for_openDirectory = JLabel("Module Path:") c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 2 self.tab.add(label_for_openDirectory, c) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 3 self.input_id = JTextField(40) self.input_id.setEditable(java.lang.Boolean.FALSE) self.tab.add(self.input_id, c) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 3 self.openButton = JButton("Open Directory", actionPerformed=self.openDialog) self.tab.add(self.openButton, c) if M_PATH: self.set_fixed_module_path() #callbacks.customizeUiComponent(self.tab) #callbacks.customizeUiComponent(self.table) #callbacks.customizeUiComponent(self.tablecont) callbacks.addSuiteTab(self) callbacks.registerProxyListener(self) return def getTabCaption(self): return ("ModuleImporter") def getUiComponent(self): return self.tab def openDialog(self, e): returnVal = self.fc.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: self.dataModel.setRowCount(0) self.input_id.text = str(self.fc.getSelectedFile()) modules = os.listdir(self.input_id.text) for module in modules: M_VALUABLES[module[:-3]] = {} if module.split('.')[-1] == "py": table_list = [java.lang.Boolean.TRUE, module] self.dataModel.insertRow(0, table_list) else: print("Open command cancelled by user.\n") def set_fixed_module_path(self): self.input_id.text = M_PATH modules = os.listdir(self.input_id.text) for module in modules: M_VALUABLES[module[:-3]] = {} if module.split('.')[-1] == "py": table_list = [java.lang.Boolean.TRUE, module] self.dataModel.insertRow(0, table_list) def processProxyMessage(self, messageIsRequest, message): if messageIsRequest: request = message.getMessageInfo().getRequest() readabled = self._helpers.bytesToString(request) modified_string_message = self.exec_module(messageIsRequest, readabled) modified_byte_message = self._helpers.stringToBytes( modified_string_message) message.getMessageInfo().setRequest(modified_byte_message) else: response = message.getMessageInfo().getResponse() readabled = self._helpers.bytesToString(response) modified_string_message = self.exec_module(messageIsRequest, readabled) modified_byte_message = self._helpers.stringToBytes( modified_string_message) message.getMessageInfo().setResponse(modified_byte_message)