def run(self): frame = JFrame('Table7', size=(300, 150), locationRelativeTo=None, defaultCloseOperation=JFrame.EXIT_ON_CLOSE) headings = 'T/F,Date,Integer,Float,Double'.split(',') model = myTM(self.data, headings) table = JTable(model, selectionMode=ListSelectionModel.SINGLE_SELECTION) table.getColumnModel().getColumn(model.getColumnCount() - 1 # i.e., last column ).setCellRenderer(myRenderer()) #---------------------------------------------------------- # Adjust the width of the columns using only header text #---------------------------------------------------------- hRenderer = table.getTableHeader().getDefaultRenderer() for col in range(model.getColumnCount()): column = table.getColumnModel().getColumn(col) comp = hRenderer.getTableCellRendererComponent( None, # Table column.getHeaderValue(), # value 0, # isSelected = false 0, # hasFocus = false -1, # row # col # col # ) width = comp.getPreferredSize().width # print 'col: %d previous: %d current: %d' % ( col, column.getPreferredWidth(), width ) column.setPreferredWidth(width) frame.add(JScrollPane(table)) frame.setVisible(1)
def run(self): frame = JFrame('Table6c', size=(300, 150), locationRelativeTo=None, defaultCloseOperation=JFrame.EXIT_ON_CLOSE) headings = 'T/F,Date,Integer,Float,Double'.split(',') model = myTM(self.data, headings) table = JTable(model, selectionMode=ListSelectionModel.SINGLE_SELECTION) table.getColumnModel().getColumn(model.getColumnCount() - 1 # i.e., last column ).setCellRenderer(myRenderer()) frame.add(JScrollPane(table)) frame.setVisible(1)
def create_scanner_table(self, scanner_pane, issue_name, issue_param): scanner_table_model = self.get_scanner_table_model( issue_name, issue_param) scanner_table = JTable(scanner_table_model) scanner_table.getColumnModel().getColumn(0).setMaxWidth(10) scanner_table.putClientProperty("terminateEditOnFocusLost", True) scanner_table_listener = ScannerTableListener(self, scanner_table, issue_name, issue_param) scanner_table_model.addTableModelListener(scanner_table_listener) scanner_table_list_listener = IssueListener(self, scanner_table, scanner_pane, issue_name, issue_param) scanner_table.getSelectionModel().addListSelectionListener( scanner_table_list_listener) return scanner_table
def create_scanner_pane(self, scanner_pane, issue_name, issue_param): scanner_issues = self.get_scanner_issues() request_table_pane = scanner_pane.getTopComponent() scanner_table_model = ScannerTableModel() scanner_table_model.addColumn("Checked") scanner_table_model.addColumn("Host") scanner_table_model.addColumn("Path") # Search all issues for the correct issue. Once found, add it into # the scanner table model to be showed in the UI. for scanner_issue in scanner_issues: is_same_name = scanner_issue.getIssueName() == issue_name is_same_param = scanner_issue.getParameter() == issue_param is_same_issue = is_same_name and is_same_param if is_same_issue: scanner_table_model.addRow([ False, scanner_issue.getHttpService().getHost(), scanner_issue.getUrl() ]) scanner_table = JTable(scanner_table_model) scanner_table.getColumnModel().getColumn(0).setCellEditor( DefaultCellEditor(JCheckBox())) scanner_table.putClientProperty("terminateEditOnFocusLost", True) scanner_table_listener = ScannerTableListener(self, scanner_table, issue_name, issue_param) scanner_table_model.addTableModelListener(scanner_table_listener) scanner_table_list_listener = IssueListener(self, scanner_table, scanner_pane, issue_name, issue_param) scanner_table.getSelectionModel().addListSelectionListener( scanner_table_list_listener) self.set_scanner_table(scanner_pane, scanner_table) request_table_pane.getViewport().setView(scanner_table) request_table_pane.revalidate() request_table_pane.repaint()
def _constructResultsPanel(self, insets): resultsPanel = JPanel(GridBagLayout()) self._progressBar = JProgressBar() self._progressBar.setStringPainted(True) self._progressBar.setMinimum(0) progressBarContraints = GridBagConstraints() progressBarContraints.gridx = 0 progressBarContraints.gridy = 0 progressBarContraints.fill = GridBagConstraints.HORIZONTAL resultsPanel.add(self._progressBar, progressBarContraints) self._resultsTableModel = ResultsTableModel(COLUMNS, 0) resultsTable = JTable(self._resultsTableModel) resultsTable.setAutoCreateRowSorter(True) cellRenderer = ColoredTableCellRenderer() for index in [5, 6, 7, 8]: column = resultsTable.columnModel.getColumn(index) column.cellRenderer = cellRenderer resultsTable.getColumnModel().getColumn(0).setPreferredWidth(99999999) resultsTable.getColumnModel().getColumn(1).setMinWidth(160) resultsTable.getColumnModel().getColumn(2).setMinWidth(100) resultsTable.getColumnModel().getColumn(3).setMinWidth(80) resultsTable.getColumnModel().getColumn(4).setMinWidth(80) resultsTable.getColumnModel().getColumn(5).setMinWidth(110) resultsTable.getColumnModel().getColumn(6).setMinWidth(110) resultsTable.getColumnModel().getColumn(7).setMinWidth(110) resultsTable.getColumnModel().getColumn(8).setMinWidth(110) resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS) resultsScrollPane = JScrollPane(resultsTable) resultsScrollPaneConstraints = GridBagConstraints() resultsScrollPaneConstraints.gridx = 0 resultsScrollPaneConstraints.gridy = 1 resultsScrollPaneConstraints.weightx = 1 resultsScrollPaneConstraints.weighty = 1 resultsScrollPaneConstraints.fill = GridBagConstraints.BOTH resultsPanel.add(resultsScrollPane, resultsScrollPaneConstraints) return resultsPanel
def createAnyTable(self, table_model, table_number, min_size): _table = JTable(table_model) _table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS) for i in range(2): column = _table.getColumnModel().getColumn(i) if i == 0: column.setPreferredWidth(250) else: column.setPreferredWidth(50) _scrolltable = JScrollPane(_table) _scrolltable.setMinimumSize(min_size) return _scrolltable
def initProfilesTable(self): profile_table = JTable() self.profile_table_model = self.ProfileTableModel() profile_table.setModel(self.profile_table_model) cm = profile_table.getColumnModel() # Set column widths for i in range(0, 4): width = self.profile_table_model.column_widths.get(i) if width is not None: column = cm.getColumn(i) column.setPreferredWidth(width) column.setMaxWidth(width) profile_table.setFillsViewportHeight(True) def doAction(event): print event # Add the actions dropdown actionCol = cm.getColumn(3) actions = JComboBox() actions.addItem("Activate") actions.addItem("Unactivate") actions.addItem("Edit") actions.addItem("Export to Script") actions.addItem("Delete") actionCol.setCellEditor(DefaultCellEditor(actions)) self.profile_table_model.actions_combo = actions renderer = self.ComboBoxTableCellRenderer() actionCol.setCellRenderer(renderer) actions.addActionListener(self.ComboActionListener(self)) return profile_table
class WS_Data_Analysis_Controller: """ This controller manages the WS data analysis. Its panel is in the WS_LW_Acquisition_Controller panel. """ def __init__(self,ws_lw_acquisition_controller): self.ws_lw_acquisition_controller = ws_lw_acquisition_controller self.local_gauss_fitter = Local_Gauss_Fitter() self.main_panel = JPanel(BorderLayout()) self.ws_records_table_model = WS_Records_Table_Model() #----etched border etched_border = BorderFactory.createEtchedBorder() #---make the WS_Records_JTable + Graph Panel self.records_table = JTable(self.ws_records_table_model) self.records_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.records_table.setFillsViewportHeight(true) #----set up records_table columns width columnModel = self.records_table.getColumnModel() columnModel.getColumn(0).setPreferredWidth(30) columnModel.getColumn(1).setPreferredWidth(160) columnModel.getColumn(2).setPreferredWidth(40) columnModel.getColumn(3).setPreferredWidth(40) columnModel.getColumn(4).setPreferredWidth(80) columnModel.getColumn(5).setPreferredWidth(70) columnModel.getColumn(6).setPreferredWidth(70) #--------------------------------------------------- records_panel = JPanel(BorderLayout()) records_panel.add(JScrollPane(self.records_table), BorderLayout.CENTER) knobs_gauss_panel = JPanel(BorderLayout()) records_panel.add(knobs_gauss_panel, BorderLayout.SOUTH) records_panel.setBorder(etched_border) #---records knobs --------------------------------------------- records_knobs_panel = JPanel(FlowLayout(FlowLayout.CENTER,5,5)) guess_and_fit_button = JButton("Guess and Fit") analysis_all_button = JButton("G&F All") fit_button = JButton("Fit") fit_all_button = JButton("Fit All") send_to_twiss_button = JButton("Send to Twiss Analysis") records_knobs_panel.add(guess_and_fit_button) records_knobs_panel.add(analysis_all_button) records_knobs_panel.add(fit_button) records_knobs_panel.add(fit_all_button) records_knobs_panel.add(send_to_twiss_button) guess_and_fit_button.addActionListener(Guess_And_Fit_Listener(self.ws_lw_acquisition_controller)) fit_button.addActionListener(Fit_Listener(self.ws_lw_acquisition_controller)) fit_all_button.addActionListener(Fit_All_Listener(self.ws_lw_acquisition_controller)) analysis_all_button.addActionListener(Guess_And_Fit_All_Listener(self.ws_lw_acquisition_controller)) send_to_twiss_button.addActionListener(SendToAnalysis_Listener(self.ws_lw_acquisition_controller)) self.gauss_fit_param_panel = GaussFitDataPanel() knobs_gauss_panel.add(records_knobs_panel, BorderLayout.NORTH) knobs_gauss_panel.add(self.gauss_fit_param_panel, BorderLayout.SOUTH) #--------------------------------------------------------- self.record_analysis_panel = JPanel(BorderLayout()) border = BorderFactory.createTitledBorder(etched_border,"WS/LW Wave Form Analysis") self.record_analysis_panel.setBorder(border) self.record_analysis_panel.add(records_panel, BorderLayout.WEST) self.gpanel_WF = FunctionGraphsJPanel() self.gpanel_WF.setLegendButtonVisible(true) self.gpanel_WF.setChooseModeButtonVisible(true) self.gpanel_WF.setName("Profile") self.gpanel_WF.setAxisNames("pos, [mm]","Amp, [arb. units]") self.gpanel_WF.setBorder(etched_border) self.gpanel_WF.addVerticalLine(-1.0e+30,Color.red) self.gpanel_WF.addVerticalLine(+1.0e+30,Color.red) self.gpanel_WF.setVerLinesButtonVisible(true) self.gpanel_WF.addDraggedVerLinesListener(Position_Limits_Listener(self.ws_lw_acquisition_controller)) self.record_analysis_panel.add(self.gpanel_WF, BorderLayout.CENTER) self.main_panel.add(self.record_analysis_panel, BorderLayout.CENTER) #---set up Listeners self.records_table.getSelectionModel().addListSelectionListener(WS_Record_Table_Selection_Listener(self.ws_lw_acquisition_controller)) def setDataToGraphPanel(self,ws_record): self.gpanel_WF.removeAllGraphData() self.gpanel_WF.addGraphData(ws_record.gd_wf) self.gpanel_WF.addGraphData(ws_record.gd_fit_wf)
class QatDialog(ToggleDialog): """ToggleDialog for error type selection and buttons for reviewing errors in sequence """ def __init__(self, name, iconName, tooltip, shortcut, height, app): ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height) self.app = app tools = app.tools #Main panel of the dialog mainPnl = JPanel(BorderLayout()) mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1)) ### First tab: errors selection and download ########################### #ComboBox with tools names self.toolsComboModel = DefaultComboBoxModel() for tool in tools: self.add_data_to_models(tool) self.toolsCombo = JComboBox(self.toolsComboModel, actionListener=ToolsComboListener(app)) renderer = ToolsComboRenderer(self.app) renderer.setPreferredSize(Dimension(20, 20)) self.toolsCombo.setRenderer(renderer) self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool")) #ComboBox with categories names ("views"), of the selected tool self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app)) self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error")) #Popup for checks table self.checkPopup = JPopupMenu() #add favourite check self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites")) self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons", "tool_16.png"]))) self.menuItemAdd.addActionListener(PopupActionListener(self.app)) self.checkPopup.add(self.menuItemAdd) #remove favourite check self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites")) self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons", "black_tool_16.png"]))) self.menuItemRemove.addActionListener(PopupActionListener(self.app)) self.checkPopup.add(self.menuItemRemove) #Help link for selected check self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help")) self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR, "images", "icons", "info_16.png"]))) self.checkPopup.add(self.menuItemHelp) self.menuItemHelp.addActionListener(PopupActionListener(self.app)) #Table with checks of selected tool and view self.checksTable = JTable() self.iconrenderer = IconRenderer() self.iconrenderer.setHorizontalAlignment(JLabel.CENTER) scrollPane = JScrollPane(self.checksTable) self.checksTable.setFillsViewportHeight(True) tableSelectionModel = self.checksTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ChecksTableListener(app)) self.checksTable.addMouseListener(ChecksTableClickListener(app, self.checkPopup, self.checksTable)) #Favourite area status indicator self.favAreaIndicator = JLabel() self.update_favourite_zone_indicator() self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app)) #label with OSM id of the object currently edited and number of #errors still to review self.checksTextFld = JTextField("", editable=0, border=None, background=None) #checks buttons btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"]) downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"])) self.downloadBtn = JButton(downloadIcon, actionPerformed=app.on_downloadBtn_clicked, enabled=0) startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"])) self.startBtn = JButton(startIcon, actionPerformed=app.on_startBtn_clicked, enabled=0) self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area")) self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors")) #tab layout panel1 = JPanel(BorderLayout(0, 1)) comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0)) comboboxesPnl.add(self.toolsCombo) comboboxesPnl.add(self.viewsCombo) checksPnl = JPanel(BorderLayout(0, 1)) checksPnl.add(scrollPane, BorderLayout.CENTER) self.statsPanel = JPanel(BorderLayout(4, 0)) self.statsPanel_def_color = self.statsPanel.getBackground() self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER) self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START) checksPnl.add(self.statsPanel, BorderLayout.PAGE_END) checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0)) checksButtonsPnl.add(self.downloadBtn) checksButtonsPnl.add(self.startBtn) panel1.add(comboboxesPnl, BorderLayout.PAGE_START) panel1.add(checksPnl, BorderLayout.CENTER) panel1.add(checksButtonsPnl, BorderLayout.PAGE_END) ### Second tab: errors fixing ########################################## #label with error stats self.errorTextFld = JTextField("", editable=0, border=None, background=None) #label with current error description self.errorDesc = JLabel("") self.errorDesc.setAlignmentX(0.5) #error buttons errorInfoBtnIcon = ImageProvider.get("info") self.errorInfoBtn = JButton(errorInfoBtnIcon, actionPerformed=app.on_errorInfoBtn_clicked, enabled=0) notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"])) self.notErrorBtn = JButton(notErrorIcon, actionPerformed=app.on_falsePositiveBtn_clicked, enabled=0) ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"])) self.ignoreBtn = JButton(ignoreIcon, actionPerformed=app.on_ignoreBtn_clicked, enabled=0) correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"])) self.correctedBtn = JButton(correctedIcon, actionPerformed=app.on_correctedBtn_clicked, enabled=0) nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"])) self.nextBtn = JButton(nextIcon, actionPerformed=app.on_nextBtn_clicked, enabled=0) #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT) self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog")) self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive")) self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again")) self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error")) self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error")) #tab layout self.panel2 = JPanel(BorderLayout()) self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START) self.panel2.add(self.errorDesc, BorderLayout.CENTER) errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0)) errorButtonsPanel.add(self.errorInfoBtn) errorButtonsPanel.add(self.notErrorBtn) errorButtonsPanel.add(self.ignoreBtn) errorButtonsPanel.add(self.correctedBtn) errorButtonsPanel.add(self.nextBtn) self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END) #Layout self.tabbedPane = JTabbedPane() self.tabbedPane.addTab(self.app.strings.getString("Download"), None, panel1, self.app.strings.getString("download_tab")) mainPnl.add(self.tabbedPane, BorderLayout.CENTER) self.createLayout(mainPnl, False, None) def add_data_to_models(self, tool): """Add data of a tool to the models of the dialog components """ #tools combobox model if tool == self.app.favouritesTool: self.toolsComboModel.addElement(JSeparator()) self.toolsComboModel.addElement(tool) #views combobox model tool.viewsComboModel = DefaultComboBoxModel() for view in tool.views: tool.viewsComboModel.addElement(view.title) #checks table, one TableModel for each view, of each tool columns = ["", self.app.strings.getString("Check"), self.app.strings.getString("Errors")] for view in tool.views: tableRows = [] for check in view.checks: if check.icon is not None: icon = check.icon else: icon = "" errorsNumber = "" tableRows.append([icon, check.title, errorsNumber]) view.tableModel = MyTableModel(tableRows, columns) def update_favourite_zone_indicator(self): #icon if self.app.favZone is not None: self.favAreaIndicator.setIcon(self.app.favZone.icon) #tooltip messageArguments = array([self.app.favZone.name], String) formatter = MessageFormat("") formatter.applyPattern(self.app.strings.getString("favAreaIndicator_tooltip")) msg = formatter.format(messageArguments) self.favAreaIndicator.setToolTipText(msg) #status self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus) def set_checksTextFld_color(self, color): """Change color of textField under checksTable """ colors = {"white": (255, 255, 255), "black": (0, 0, 0), "green": (100, 200, 0), "red": (200, 0, 0)} if color == "default": self.statsPanel.background = self.statsPanel_def_color self.checksTextFld.foreground = colors["black"] else: self.statsPanel.background = colors[color] self.checksTextFld.foreground = colors["white"] def change_selection(self, source): """Change comboboxes and checks table selections after a selection has been made by the user """ if source in ("menu", "layer", "add favourite"): self.app.selectionChangedFromMenuOrLayer = True self.toolsCombo.setSelectedItem(self.app.selectedTool) self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel) self.viewsCombo.setSelectedItem(self.app.selectedView.title) self.checksTable.setModel(self.app.selectedTableModel) self.refresh_checksTable_columns_geometries() for i, c in enumerate(self.app.selectedView.checks): if c == self.app.selectedChecks[0]: break self.checksTable.setRowSelectionInterval(i, i) self.app.selectionChangedFromMenuOrLayer = False else: self.app.selectionChangedFromMenuOrLayer = False if source == "toolsCombo": self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel) self.viewsCombo.setSelectedIndex(0) elif source == "viewsCombo": self.checksTable.setModel(self.app.selectedTableModel) self.refresh_checksTable_columns_geometries() if self.app.selectedView.checks != []: # favourite checks may be none self.checksTable.setRowSelectionInterval(0, 0) def refresh_checksTable_columns_geometries(self): self.checksTable.getColumnModel().getColumn(0).setCellRenderer(self.iconrenderer) self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25) self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60) def activate_error_tab(self, status): if status: if self.tabbedPane.getTabCount() == 1: self.tabbedPane.addTab(self.app.strings.getString("Fix"), None, self.panel2, self.app.strings.getString("fix_tab")) else: if self.tabbedPane.getTabCount() == 2: self.tabbedPane.remove(1) def update_checks_buttons(self): """This method sets the status of downloadBtn and startBtn """ #none check selected if len(self.app.selectedChecks) == 0: self.downloadBtn.setEnabled(False) self.startBtn.setEnabled(False) else: #some check selected self.downloadBtn.setEnabled(True) if len(self.app.selectedChecks) > 1: self.startBtn.setEnabled(False) else: #only one check is selected self.app.errors = self.app.selectedChecks[0].errors if self.app.errors is None or len(self.app.errors) == 0: #errors file has not been downloaded and parsed yet self.startBtn.setEnabled(False) else: #errors file has been downloaded and parsed if self.app.selectedChecks[0].toDo == 0: #all errors have been corrected self.startBtn.setEnabled(False) else: self.startBtn.setEnabled(True) #self.nextBtn.setEnabled(True) def update_error_buttons(self, mode): """This method sets the status of: ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn """ if mode == "new error": status = True else: status = False if self.app.selectedChecks[0].tool.fixedFeedbackMode is None: self.correctedBtn.setEnabled(False) else: self.correctedBtn.setEnabled(status) if self.app.selectedChecks[0].tool.falseFeedbackMode is None: self.notErrorBtn.setEnabled(False) else: self.notErrorBtn.setEnabled(status) self.errorInfoBtn.setEnabled(status) self.ignoreBtn.setEnabled(status) if mode in ("reset", "review end"): self.nextBtn.setEnabled(False) elif mode in ("errors downloaded", "show stats", "new error"): self.nextBtn.setEnabled(True) def update_text_fields(self, mode, errorInfo=""): """This method updates the text in: checksTextFld, errorDesc, errorTextFld """ self.errorDesc.text = "" if mode == "review end": cheksTextColor = "green" checksText = self.app.strings.getString("All_errors_reviewed.") errorText = self.app.strings.getString("All_errors_reviewed.") elif mode == "reset": cheksTextColor = "default" checksText = "" errorText = "" elif mode == "show stats": cheksTextColor = "default" checksText = "%s %d / %s" % ( self.app.strings.getString("to_do"), self.app.selectedChecks[0].toDo, len(self.app.selectedChecks[0].errors)) #print "checks text", checksText errorText = "%s%s %d / %s" % ( errorInfo, self.app.strings.getString("to_do"), self.app.selectedChecks[0].toDo, len(self.app.selectedChecks[0].errors)) #print "error text", errorText if self.app.selectedError is not None and self.app.selectedError.desc != "": self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc self.set_checksTextFld_color(cheksTextColor) self.checksTextFld.text = checksText self.errorTextFld.text = errorText self.update_statsPanel_status() def update_statsPanel_status(self): if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus: self.statsPanel.setVisible(False) else: self.statsPanel.setVisible(True)
def _initializeGui(self, callbacks): tab = JPanel() jLabel1 = JLabel("Original Hash:") jLabel2 = JLabel("Original message:") jLabel3 = JLabel("Message to append:") jLabel5 = JLabel("Max key length:") jTextField1 = JTextField("") jTextField2 = JTextField("") jTextField3 = JTextField("") jTextField4 = JTextField("128") jLabel4 = JLabel("Hashing functions") jCheckBox1 = JCheckBox("MD4") jCheckBox2 = JCheckBox("MD5") jCheckBox3 = JCheckBox("SHA1") jCheckBox4 = JCheckBox("SHA256") jCheckBox5 = JCheckBox("SHA512") jCheckBox1.setEnabled(False) jCheckBox2.setEnabled(False) jCheckBox3.setEnabled(False) jCheckBox4.setEnabled(False) jCheckBox5.setEnabled(False) jScrollPane1 = JScrollPane() jTable1 = JTable() jButton1 = JButton("Generate", actionPerformed=self.generate_attack) jButton1.setEnabled(False) jButton2 = JButton("Copy messages", actionPerformed=self.copy_messages) jButton3 = JButton("Copy hashes", actionPerformed=self.copy_hashes) self._tab = tab self._textfields = { "original_hash": jTextField1, "original_msg": jTextField2, "append_msg": jTextField3, "max_key_len": jTextField4, } self._checkboxes = { md4: jCheckBox1, md5: jCheckBox2, sha1: jCheckBox3, sha256: jCheckBox4, sha512: jCheckBox5, } self._table = jTable1 self._extensions = {} self._hashes, self._messages = [], [] # Hash field change event jTextField1.getDocument().addDocumentListener( HashChangeListener(self._checkboxes, self._textfields['original_hash'], jButton1)) # Table columns jTable1.setModel( DefaultTableModel([], ["#", "Type", "New Message", "Hash"])) jScrollPane1.setViewportView(jTable1) # Table column width jTable1.getColumnModel().getColumn(0).setMaxWidth(50) jTable1.getColumnModel().getColumn(1).setMaxWidth(60) layout = GroupLayout(tab) tab.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(24, 24, 24).addGroup( layout.createParallelGroup( GroupLayout.Alignment.TRAILING).addComponent(jLabel5). addComponent(jLabel1).addComponent(jLabel2). addComponent(jLabel3)).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( jTextField3, GroupLayout.DEFAULT_SIZE, 425, 32767).addComponent(jTextField2). addComponent(jTextField1).addGroup( layout.createSequentialGroup().addComponent( jTextField4, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE).addGap( 0, 0, 32767))).addGap(30, 30, 30). addGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING). addGroup(layout.createSequentialGroup( ).addComponent(jCheckBox1).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(jCheckBox2).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(jCheckBox3).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(jCheckBox4).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( jCheckBox5)).addComponent(jLabel4).addGroup( layout.createSequentialGroup().addComponent( jButton1).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(jButton3).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(jButton2))).addGap( 167, 167, 167)).addComponent(jScrollPane1)) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(26, 26, 26).addGroup( layout.createParallelGroup(GroupLayout.Alignment.BASELINE). addComponent(jLabel1).addComponent( jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(jLabel4)). addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE). addComponent(jLabel2).addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( jCheckBox2).addComponent(jCheckBox3). addComponent(jCheckBox1).addComponent(jCheckBox4). addComponent(jCheckBox5))).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( jTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(jLabel3) ).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE). addComponent(jLabel5).addComponent( jTextField4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(jButton2). addComponent(jButton3).addComponent(jButton1)).addGap( 13, 13, 13).addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 971, 32767))) callbacks.customizeUiComponent(tab) callbacks.addSuiteTab(self)
class Transverse_Twiss_Analysis_Controller: def __init__(self,linac_wizard_document): #--- linac_wizard_document the parent document for all controllers self.linac_wizard_document = linac_wizard_document #---- fit_param_index = 0,1,2 gauss, custom gauss, custom rms self.fit_param_index = 0 #-------------------------------------------------------------- self.accStatesKeeper = AccStatesKeeper(self.linac_wizard_document) self.main_panel = JPanel(BorderLayout()) #----etched border etched_border = BorderFactory.createEtchedBorder() #---------hor. ver. graph panels self.graphs_panel = Graphs_Panel(self) #---------quads' and cavities' parameters tables panels self.quad_cav_params_tables_panel = Quad_and_Cav_Params_Table_Panel(self) #-------- tabbed panel with graphs and tables self.graphs_and_tables_tabbed_panel = JTabbedPane() self.graphs_and_tables_tabbed_panel.add("Hor. Ver. Long. Plots",self.graphs_panel) self.graphs_and_tables_tabbed_panel.add("Cavities and Quads Tables",self.quad_cav_params_tables_panel) #------ sets selection table self.dict_panel = QuadCavDictSelection_Panel(self) #---------H and V Size Tables hor_size_table_border = BorderFactory.createTitledBorder(etched_border,"Horizontal") ver_size_table_border = BorderFactory.createTitledBorder(etched_border,"Vertical") self.hor_size_table_model = Tr_Size_Table_Model(WS_DIRECTION_HOR,self) self.hor_size_table = JTable(self.hor_size_table_model) self.hor_size_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.hor_size_table.setFillsViewportHeight(true) hor_size_panel = JPanel(BorderLayout()) hor_size_panel.setBorder(hor_size_table_border) hor_size_panel.add(JScrollPane(self.hor_size_table), BorderLayout.CENTER) self.ver_size_table_model = Tr_Size_Table_Model(WS_DIRECTION_VER,self) self.ver_size_table = JTable(self.ver_size_table_model) self.ver_size_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.ver_size_table.setFillsViewportHeight(true) ver_size_panel = JPanel(BorderLayout()) ver_size_panel.setBorder(ver_size_table_border) ver_size_panel.add(JScrollPane(self.ver_size_table), BorderLayout.CENTER) sizes_table_panel = JPanel(GridLayout(3,1)) #-----------column sizes --------- columnModel = self.hor_size_table.getColumnModel() columnModel.getColumn(0).setPreferredWidth(30) columnModel.getColumn(1).setPreferredWidth(120) columnModel.getColumn(2).setPreferredWidth(60) columnModel.getColumn(3).setPreferredWidth(30) columnModel.getColumn(4).setPreferredWidth(50) columnModel.getColumn(5).setPreferredWidth(50) columnModel.getColumn(6).setPreferredWidth(50) columnModel = self.ver_size_table.getColumnModel() columnModel.getColumn(0).setPreferredWidth(30) columnModel.getColumn(1).setPreferredWidth(120) columnModel.getColumn(2).setPreferredWidth(60) columnModel.getColumn(3).setPreferredWidth(30) columnModel.getColumn(4).setPreferredWidth(50) columnModel.getColumn(5).setPreferredWidth(50) columnModel.getColumn(6).setPreferredWidth(50) sizes_table_panel.add(self.dict_panel.getMainPanel()) sizes_table_panel.add(hor_size_panel) sizes_table_panel.add(ver_size_panel) #---------Transverse Fitting Controller self.transverse_twiss_fitting_controller = Transverse_Twiss_Fitting_Controller(self.linac_wizard_document) #----add panels to the main self.main_panel.add(self.graphs_and_tables_tabbed_panel, BorderLayout.CENTER) self.main_panel.add(sizes_table_panel, BorderLayout.WEST) self.main_panel.add(self.transverse_twiss_fitting_controller.getMainPanel(), BorderLayout.SOUTH) def getMainPanel(self): return self.main_panel def makeWS_LW_Size_Record(self): return WS_LW_Size_Record()
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener): """Dialog with preferences """ def __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText( self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText( self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel( self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont( Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText( self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder( ) self.maxErrorsNumberTextField.getDocument().addDocumentListener( ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox( self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText( self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = [ "", self.app.strings.getString("Type"), self.app.strings.getString("Name") ] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText( self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack() def windowClosing(self, windowEvent): self.on_cancelBtn_clicked() def hyperlinkUpdate(self, e): if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED: OpenBrowser.displayUrl(e.getURL().toString()) def itemStateChanged(self, e): """A ttol has been activated/deactivated. Check if at least one tool is on. """ if all(not button.isSelected() for button in self.toolsCBtns): JOptionPane.showMessageDialog( Main.parent, self.app.strings.getString("tools_disabled_warning"), self.app.strings.getString("tools_disabled_warning_title"), JOptionPane.WARNING_MESSAGE) source = e.getItemSelectable() source.setSelected(True) def actionPerformed(self, e=None): """Enable/disable favourite zones panel """ for container in (self.scrollPane, self.buttonsPanel): self.enableComponents(container, self.favZoneStatusCBtn.isSelected()) if self.favZoneStatusCBtn.isSelected(): self.check_removeBtn_status() def enableComponents(self, container, enable): components = container.getComponents() for component in components: component.setEnabled(enable) if isinstance(component, Container): self.enableComponents(component, enable) def on_downloadBtn_clicked(self, e): update_checker.Updater(self.app, "manual") def clean_map(self): """Remove all rectangles and polygons from the map """ self.zonesMap.removeAllMapRectangles() self.zonesMap.removeAllMapPolygons() def update_gui_from_preferences(self): """Update gui status of preferences frame from config file """ #print "\n- updating Preferences gui" onOff = {"on": True, "off": False} #1 Tab #check for update self.updateCBtn.setSelected(onOff[self.app.checkUpdate]) #tools status, enabled or not for toolIndex, tool in enumerate(self.app.realTools): if "tool.%s" % tool.name in self.app.properties.keys(): configstatus = self.app.properties.getProperty("tool.%s" % tool.name) else: configstatus = "on" # new tool self.toolsCBtns[toolIndex].setSelected(onOff[configstatus]) #layers preferences for mode, button in self.layersRBtns.iteritems(): button.setSelected(mode == self.app.layersMode) #max errors number self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber)) #stats panel self.app.dlg.update_favourite_zone_indicator() #2 Tab #favourite area self.update_favourite_area_gui_from_preferences() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: tool.prefsGui.update_gui(tool.prefs) def update_favourite_area_gui_from_preferences(self): #status self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus) #table #store zones to a temporary list, used to store changes #and save them when preferences dialog is closed self.app.tempZones = list(self.app.zones) self.zonesTable.getModel().setNumRows(0) for zone in self.app.tempZones: self.zonesTable.getModel().addRow( [zone.country, zone.icon, zone.name]) if self.app.favZone is not None: selectedRow = self.app.tempZones.index(self.app.favZone) self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow) self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30) self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50) #enable or disable favourite zone buttons self.actionPerformed() ### fav area editing buttons ########################################### def on_removeBtn_clicked(self, e): rowsNum = self.zonesTable.getSelectedRows() rowsNum.reverse() for rowNum in rowsNum: del self.app.tempZones[rowNum] self.zonesTable.getModel().removeRow(rowNum) if len(self.app.tempZones) != 0: if rowNum == 0: self.zonesTable.setRowSelectionInterval(0, 0) else: self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1) self.check_removeBtn_status() def check_removeBtn_status(self): if self.app.tempZones != [] and len( self.zonesTable.getSelectedRows()) != 0: self.removeBtn.setEnabled(True) else: self.removeBtn.setEnabled(False) self.clean_map() def on_newBtn_clicked(self, e): try: self.newZoneDialog except AttributeError: self.newZoneDialog = NewZoneDialog(self.app) bbox = self.app.get_frame_bounds() self.app.newZone = Zone(self.app, self.app.strings.getString("New_zone"), "rectangle", ",".join(["%0.4f" % x for x in bbox]), "") self.newZoneDialog.update_gui_from_preferences() self.newZoneDialog.show() ### Exit from preferences ############################################## def on_cancelBtn_clicked(self, event=None): if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible(): self.newZoneDialog.close_dialog() self.dispose() def on_saveBtn_clicked(self, event): """Read preferences from gui and save them to config.properties file """ #print "\n- saving preferences to config file" onOff = {True: "on", False: "off"} #1 Tab #check for update self.app.properties.setProperty("check_for_update", onOff[self.updateCBtn.isSelected()]) #tools status for toolIndex, tool in enumerate(self.app.realTools): prop = "tool.%s" % tool.name toolCBtn = self.toolsCBtns[toolIndex] self.app.properties.setProperty(prop, onOff[toolCBtn.isSelected()]) #layers preferences for mode, button in self.layersRBtns.iteritems(): if button.isSelected(): self.app.properties.setProperty("layers_mode", mode) break #max errors number try: num = Integer.parseInt(self.maxErrorsNumberTextField.getText()) except NumberFormatException: num = "" self.app.properties.setProperty("max_errors_number", str(num)) #2 Tab #Favourite zones changes = { "new": [z for z in self.app.tempZones if not z in self.app.zones], "deleted": [z for z in self.app.zones if not z in self.app.tempZones] } #delete files of removed favourite zones for zone in changes["deleted"]: f = File( File.separator.join([ self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name ])) f.delete() #create files for new favourite zones for zone in changes["new"]: print "\nsave new zone", zone.name fileName = File.separator.join([ self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name ]) f = open(fileName, "w") zoneData = zone.geomString if zone.country != "": zoneData += "|" + zone.country f.write(zoneData.encode("utf-8")) f.close() self.app.zones = self.app.tempZones if len(self.app.zones) == 0: self.app.favZone = None self.app.properties.setProperty("favourite_area.name", "") self.favZoneStatusCBtn.setSelected(False) else: if len(self.zonesTable.getSelectedRows()) == 0: self.app.favZone = self.app.zones[0] else: self.app.favZone = self.app.zones[ self.zonesTable.getSelectedRows()[0]] self.app.properties.setProperty("favourite_area.name", self.app.favZone.name) favZoneStatus = self.favZoneStatusCBtn.isSelected() self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus]) self.app.favouriteZoneStatus = favZoneStatus #stats panel self.app.dlg.update_favourite_zone_indicator() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: for pref, value in tool.prefsGui.read_gui().iteritems(): prefKey = "tool.%s.%s" % (tool.name, pref) self.app.properties.setProperty(prefKey, value) self.app.save_config() self.dispose()
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener): """Dialog with preferences """ def __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder() self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = ["", self.app.strings.getString("Type"), self.app.strings.getString("Name")] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack() def windowClosing(self, windowEvent): self.on_cancelBtn_clicked() def hyperlinkUpdate(self, e): if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED: OpenBrowser.displayUrl(e.getURL().toString()) def itemStateChanged(self, e): """A ttol has been activated/deactivated. Check if at least one tool is on. """ if all(not button.isSelected() for button in self.toolsCBtns): JOptionPane.showMessageDialog( Main.parent, self.app.strings.getString("tools_disabled_warning"), self.app.strings.getString("tools_disabled_warning_title"), JOptionPane.WARNING_MESSAGE) source = e.getItemSelectable() source.setSelected(True) def actionPerformed(self, e=None): """Enable/disable favourite zones panel """ for container in (self.scrollPane, self.buttonsPanel): self.enableComponents(container, self.favZoneStatusCBtn.isSelected()) if self.favZoneStatusCBtn.isSelected(): self.check_removeBtn_status() def enableComponents(self, container, enable): components = container.getComponents() for component in components: component.setEnabled(enable) if isinstance(component, Container): self.enableComponents(component, enable) def on_downloadBtn_clicked(self, e): update_checker.Updater(self.app, "manual") def clean_map(self): """Remove all rectangles and polygons from the map """ self.zonesMap.removeAllMapRectangles() self.zonesMap.removeAllMapPolygons() def update_gui_from_preferences(self): """Update gui status of preferences frame from config file """ #print "\n- updating Preferences gui" onOff = {"on": True, "off": False} #1 Tab #check for update self.updateCBtn.setSelected(onOff[self.app.checkUpdate]) #tools status, enabled or not for toolIndex, tool in enumerate(self.app.realTools): if "tool.%s" % tool.name in self.app.properties.keys(): configstatus = self.app.properties.getProperty("tool.%s" % tool.name) else: configstatus = "on" # new tool self.toolsCBtns[toolIndex].setSelected(onOff[configstatus]) #layers preferences for mode, button in self.layersRBtns.iteritems(): button.setSelected(mode == self.app.layersMode) #max errors number self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber)) #stats panel self.app.dlg.update_favourite_zone_indicator() #2 Tab #favourite area self.update_favourite_area_gui_from_preferences() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: tool.prefsGui.update_gui(tool.prefs) def update_favourite_area_gui_from_preferences(self): #status self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus) #table #store zones to a temporary list, used to store changes #and save them when preferences dialog is closed self.app.tempZones = list(self.app.zones) self.zonesTable.getModel().setNumRows(0) for zone in self.app.tempZones: self.zonesTable.getModel().addRow([zone.country, zone.icon, zone.name]) if self.app.favZone is not None: selectedRow = self.app.tempZones.index(self.app.favZone) self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow) self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30) self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50) #enable or disable favourite zone buttons self.actionPerformed() ### fav area editing buttons ########################################### def on_removeBtn_clicked(self, e): rowsNum = self.zonesTable.getSelectedRows() rowsNum.reverse() for rowNum in rowsNum: del self.app.tempZones[rowNum] self.zonesTable.getModel().removeRow(rowNum) if len(self.app.tempZones) != 0: if rowNum == 0: self.zonesTable.setRowSelectionInterval(0, 0) else: self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1) self.check_removeBtn_status() def check_removeBtn_status(self): if self.app.tempZones != [] and len(self.zonesTable.getSelectedRows()) != 0: self.removeBtn.setEnabled(True) else: self.removeBtn.setEnabled(False) self.clean_map() def on_newBtn_clicked(self, e): try: self.newZoneDialog except AttributeError: self.newZoneDialog = NewZoneDialog(self.app) bbox = self.app.get_frame_bounds() self.app.newZone = Zone(self.app, self.app.strings.getString("New_zone"), "rectangle", ",".join(["%0.4f" % x for x in bbox]), "") self.newZoneDialog.update_gui_from_preferences() self.newZoneDialog.show() ### Exit from preferences ############################################## def on_cancelBtn_clicked(self, event=None): if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible(): self.newZoneDialog.close_dialog() self.dispose() def on_saveBtn_clicked(self, event): """Read preferences from gui and save them to config.properties file """ #print "\n- saving preferences to config file" onOff = {True: "on", False: "off"} #1 Tab #check for update self.app.properties.setProperty("check_for_update", onOff[self.updateCBtn.isSelected()]) #tools status for toolIndex, tool in enumerate(self.app.realTools): prop = "tool.%s" % tool.name toolCBtn = self.toolsCBtns[toolIndex] self.app.properties.setProperty(prop, onOff[toolCBtn.isSelected()]) #layers preferences for mode, button in self.layersRBtns.iteritems(): if button.isSelected(): self.app.properties.setProperty("layers_mode", mode) break #max errors number try: num = Integer.parseInt(self.maxErrorsNumberTextField.getText()) except NumberFormatException: num = "" self.app.properties.setProperty("max_errors_number", str(num)) #2 Tab #Favourite zones changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones], "deleted": [z for z in self.app.zones if not z in self.app.tempZones]} #delete files of removed favourite zones for zone in changes["deleted"]: f = File(File.separator.join([self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name])) f.delete() #create files for new favourite zones for zone in changes["new"]: print "\nsave new zone", zone.name fileName = File.separator.join([self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name]) f = open(fileName, "w") zoneData = zone.geomString if zone.country != "": zoneData += "|" + zone.country f.write(zoneData.encode("utf-8")) f.close() self.app.zones = self.app.tempZones if len(self.app.zones) == 0: self.app.favZone = None self.app.properties.setProperty("favourite_area.name", "") self.favZoneStatusCBtn.setSelected(False) else: if len(self.zonesTable.getSelectedRows()) == 0: self.app.favZone = self.app.zones[0] else: self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]] self.app.properties.setProperty("favourite_area.name", self.app.favZone.name) favZoneStatus = self.favZoneStatusCBtn.isSelected() self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus]) self.app.favouriteZoneStatus = favZoneStatus #stats panel self.app.dlg.update_favourite_zone_indicator() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: for pref, value in tool.prefsGui.read_gui().iteritems(): prefKey = "tool.%s.%s" % (tool.name, pref) self.app.properties.setProperty(prefKey, value) self.app.save_config() self.dispose()
class BurpExtender(IBurpExtender, ISessionHandlingAction, ITab, IContextMenuFactory, IContextMenuInvocation, ActionListener, ITextEditor): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): # save the helpers for later self.helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Custom Request Handler") callbacks.registerSessionHandlingAction(self) callbacks.registerContextMenuFactory(self) self._text_editor = callbacks.createTextEditor() self._text_editor.setEditable(False) #How much loaded the table row self.current_column_id = 0 #GUI self._split_main = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._split_top = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._split_top.setPreferredSize(Dimension(100, 50)) self._split_top.setDividerLocation(700) self._split_center = JSplitPane(JSplitPane.VERTICAL_SPLIT) boxVertical = swing.Box.createVerticalBox() box_top = swing.Box.createHorizontalBox() boxHorizontal = swing.Box.createHorizontalBox() buttonHorizontal = swing.Box.createHorizontalBox() boxVertical.add(boxHorizontal) box_regex = swing.Box.createVerticalBox() border = BorderFactory.createTitledBorder(LineBorder(Color.BLACK), "Extract target strings", TitledBorder.LEFT, TitledBorder.TOP) box_regex.setBorder(border) self._add_btn = JButton("Add") self._add_btn.addActionListener(self) self._remove_btn = JButton("Remove") self._remove_btn.addActionListener(self) items = [ 'JSON', 'Header', ] self._dropdown = JComboBox(items) type_panel = JPanel(FlowLayout(FlowLayout.LEADING)) type_panel.add(JLabel('Type:')) type_panel.add(self._dropdown) self._jLabel_param = JLabel("Name:") self._param_error = JLabel("Name is required") self._param_error.setVisible(False) self._param_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12)) self._param_error.setForeground(Color.red) regex_checkbox = JPanel(FlowLayout(FlowLayout.LEADING)) self._is_use_regex = JCheckBox("Extract from regex group") regex_checkbox.add(self._is_use_regex) self._jTextIn_param = JTextField(20) self._jLabel_regex = JLabel("Regex:") self._jTextIn_regex = JTextField(20) self._regex_error = JLabel("No group defined") self._regex_error.setVisible(False) self._regex_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12)) self._regex_error.setForeground(Color.red) self._param_panel = JPanel(FlowLayout(FlowLayout.LEADING)) self._param_panel.add(self._jLabel_param) self._param_panel.add(self._jTextIn_param) self._param_panel.add(self._param_error) self._regex_panel = JPanel(FlowLayout(FlowLayout.LEADING)) self._regex_panel.add(self._jLabel_regex) self._regex_panel.add(self._jTextIn_regex) self._regex_panel.add(self._regex_error) button_panel = JPanel(FlowLayout(FlowLayout.LEADING)) #padding button_panel.add(JPanel()) button_panel.add(JPanel()) button_panel.add(JPanel()) button_panel.add(self._add_btn) button_panel.add(self._remove_btn) box_regex.add(type_panel) box_regex.add(self._param_panel) box_regex.add(regex_checkbox) box_regex.add(self._regex_panel) buttonHorizontal.add(button_panel) box_regex.add(buttonHorizontal) boxVertical.add(box_regex) box_top.add(boxVertical) box_file = swing.Box.createHorizontalBox() checkbox_panel = JPanel(FlowLayout(FlowLayout.LEADING)) border = BorderFactory.createTitledBorder( LineBorder(Color.BLACK), 'Payload Sets [Simple list]', TitledBorder.LEFT, TitledBorder.TOP) box_file.setBorder(border) box_param = swing.Box.createVerticalBox() box_param.add(checkbox_panel) file_column_names = [ "Type", "Name", "Payload", ] data = [] self.file_table_model = DefaultTableModel(data, file_column_names) self.file_table = JTable(self.file_table_model) self.file_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF) column_model = self.file_table.getColumnModel() for count in xrange(column_model.getColumnCount()): column = column_model.getColumn(count) column.setPreferredWidth(160) self.file_table.preferredScrollableViewportSize = Dimension(500, 70) self.file_table.setFillsViewportHeight(True) panel_dropdown = JPanel(FlowLayout(FlowLayout.LEADING)) self._file_dropdown = JComboBox(items) panel_dropdown.add(JLabel('Type:')) panel_dropdown.add(self._file_dropdown) box_param.add(panel_dropdown) box_param.add(JScrollPane(self.file_table)) callbacks.customizeUiComponent(self.file_table) file_param_panel = JPanel(FlowLayout(FlowLayout.LEADING)) self._file_param = JLabel("Name:") self._file_param_text = JTextField(20) file_param_panel.add(self._file_param) file_param_panel.add(self._file_param_text) self._error_message = JLabel("Name is required") self._error_message.setVisible(False) self._error_message.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12)) self._error_message.setForeground(Color.red) file_param_panel.add(self._error_message) box_param.add(file_param_panel) box_button_file = swing.Box.createVerticalBox() self._file_load_btn = JButton("Load") self._file_clear_btn = JButton("Clear") self._file_clear_btn.addActionListener(self) self._file_load_btn.addActionListener(self) box_button_file.add(self._file_load_btn) box_button_file.add(self._file_clear_btn) box_file.add(box_button_file) box_file.add(box_param) boxVertical.add(box_file) regex_column_names = [ "Type", "Name", "Regex", "Start at offset", "End at offset", ] #clear target.json with open("target.json", "w") as f: pass data = [] self.target_table_model = DefaultTableModel(data, regex_column_names) self.target_table = JTable(self.target_table_model) self.target_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF) column_model = self.target_table.getColumnModel() for count in xrange(column_model.getColumnCount()): column = column_model.getColumn(count) column.setPreferredWidth(100) self.target_table.preferredScrollableViewportSize = Dimension(500, 70) self.target_table.setFillsViewportHeight(True) callbacks.customizeUiComponent(self.target_table) callbacks.customizeUiComponent(boxVertical) table_panel = swing.Box.createVerticalBox() table_panel.add(JScrollPane(self.target_table)) box_top.add(table_panel) self._jScrollPaneOut = JScrollPane() #self._split_main.setBottomComponent(self._jScrollPaneOut) self._split_main.setBottomComponent(self._text_editor.getComponent()) self._split_main.setTopComponent(box_top) self._split_main.setDividerLocation(450) callbacks.customizeUiComponent(self._split_main) callbacks.addSuiteTab(self) return def getTabCaption(self): return "CRH" def getUiComponent(self): return self._split_main def createMenuItems(self, invocation): menu = [] ctx = invocation.getInvocationContext() menu.append( swing.JMenuItem("Send to CRH", None, actionPerformed=lambda x, inv=invocation: self. menu_action(inv))) return menu if menu else None # # Implementation of Menu Action # def menu_action(self, invocation): try: invMessage = invocation.getSelectedMessages() message = invMessage[0].getResponse() res_info = self.helpers.analyzeResponse(message) send_res = message.tostring() self._text_editor.setText(send_res) except: print('Failed to add data to CRH tab.') # # Implementation of event action # def actionPerformed(self, actionEvent): # onclick add button of extract from regex group if actionEvent.getSource() is self._add_btn: start, end = self._text_editor.getSelectionBounds() value = None regex = None item = self._dropdown.getSelectedItem() param = self._jTextIn_param.getText() if len(param) is 0: self._param_error.setVisible(True) return self._param_error.setVisible(False) is_selected = self._is_use_regex.isSelected() if is_selected: start = None end = None regex = self._jTextIn_regex.getText() if len(regex) is 0: self._regex_error.setVisible(True) return req = self._text_editor.getText() try: pattern = re.compile(regex) match = pattern.search(req) value = match.group(1) if match else None if value is None: raise IndexError except IndexError: self._regex_error.setVisible(True) return self._regex_error.setVisible(False) data = [ item, param, regex, start, end, ] self.target_table_model.addRow(data) with open("target.json", "r+") as f: try: json_data = json.load(f) except ValueError: json_data = dict() if is_selected: data = { param: [ item, regex, ] } else: data = { param: [ item, start, end, ] } json_data.update(data) self.write_file(f, json.dumps(json_data)) # onclick remove button of extract from regex group if actionEvent.getSource() is self._remove_btn: rowno = self.target_table.getSelectedRow() if rowno != -1: column_model = self.target_table.getColumnModel() param_name = self.target_table_model.getValueAt(rowno, 1) start = self.target_table_model.getValueAt(rowno, 3) self.target_table_model.removeRow(rowno) with open("target.json", 'r+') as f: try: json_data = json.load(f) except ValueError: json_data = dict() for key, value in json_data.items(): if value[1] == start and key == param_name: try: del json_data[key] except IndexError: print('Error: {0}: No such json key.'.format( key)) self.write_file(f, json.dumps(json_data)) # onclick load button of payload sets if actionEvent.getSource() is self._file_load_btn: #clear table self.remove_all(self.file_table_model) self.current_column_id = 0 target_param = self._file_param_text.getText() item = self._file_dropdown.getSelectedItem() if len(target_param) == 0: self._error_message.setVisible(True) return self._error_message.setVisible(False) chooser = JFileChooser() chooser.showOpenDialog(actionEvent.getSource()) file_path = chooser.getSelectedFile().getAbsolutePath() with open(file_path, 'r') as f: while True: line = f.readline().strip() if not line: break data = [ item, target_param, line, ] self.file_table_model.addRow(data) with open('target.json', 'r+') as f: try: json_data = json.load(f) except ValueError: json_data = dict() json_data.update({target_param: [ item, 'Set payload', ]}) self.write_file(f, json.dumps(json_data)) # onclick clear button of payload sets if actionEvent.getSource() is self._file_clear_btn: self.remove_all(self.file_table_model) self.current_column_id = 0 with open("target.json", 'r+') as f: try: json_data = json.load(f) except: json_data = dict() for key, value in json_data.items(): if isinstance(value[1], unicode): if value[1].encode('utf-8') == 'Set payload': try: del json_data[key] except IndexError: print('Error: {0}: No such json key.'.format( key)) self.write_file(f, json.dumps(json_data)) # # Implementaion of ISessionHandlingAction # def getActionName(self): return "custom request handler" def performAction(self, current_request, macro_items): if len(macro_items) == 0: return # extract the response headers final_response = macro_items[len(macro_items) - 1].getResponse() if final_response is None: return req = self.helpers.analyzeRequest(current_request) try: with open('target.json', 'r') as f: read_data = f.read() self.read_data = json.loads(read_data) except ValueError: sys.stderr.write('Error: json.loads()') return for key, value in self.read_data.items(): if value[0] == 'JSON': self.set_json_parameter(current_request, final_response, key, value) elif value[0] == 'Header': self.set_header(current_request, final_response, key, value) def set_json_parameter(self, current_request, final_response, key, value): req = self.helpers.analyzeRequest(current_request) if IRequestInfo.CONTENT_TYPE_JSON != req.getContentType(): return False body = current_request.getRequest()[req.getBodyOffset():].tostring() json_data = json.loads(body, object_pairs_hook=collections.OrderedDict) target_keys = filter(lambda x: x == key, json_data.keys()) if not target_keys: return req_data = json_data column_model = self.file_table.getColumnModel() row_count = self.file_table_model.getRowCount() for key in target_keys: if value[-1] == 'Set payload': if row_count > self.current_column_id: req_value = self.file_table_model.getValueAt( self.current_column_id, 2) self.current_column_id += 1 else: # No selected regex if len(value) > 2: start, end = value[1:] req_value = final_response[start:end].tostring() else: regex = value[1] match = re.search(regex, final_response.tostring()) req_value = match.group(1) if match else None req_data[key] = req_value req = current_request.getRequest() json_data_start = self.helpers.indexOf(req, bytearray(body), False, 0, len(req)) # glue together header + customized json of request current_request.setRequest( req[0:json_data_start] + self.helpers.stringToBytes(json.dumps(req_data))) def set_header(self, current_request, final_response, key, value): req = self.helpers.analyzeRequest(current_request) headers = req.getHeaders() target_keys = [] for header in headers: if header.startswith(key): target_keys += [key] if not target_keys: return column_model = self.file_table.getColumnModel() row_count = self.file_table_model.getRowCount() req = current_request.getRequest() for key in target_keys: if value[-1] == 'Set payload': if row_count > self.current_column_id: req_value = self.file_table_model.getValueAt( self.current_column_id, 2) self.current_column_id += 1 else: # No selected regex if len(value) > 2: start, end = value[1:] req_value = final_response[start:end].tostring() else: regex = value[1] match = re.search(regex, final_response.string()) req_value = match.group(1) if match else None key_start = self.helpers.indexOf(req, bytearray(key.encode('utf-8')), False, 0, len(req)) key_end = self.helpers.indexOf(req, bytearray('\r\n'), False, key_start, len(req)) keylen = len(key) # glue together first line + customized hedaer + rest of request current_request.setRequest( req[0:key_start] + self.helpers.stringToBytes("%s: %s" % (key.encode('utf-8'), req_value)) + req[key_end:]) # # Implementation of function for Remove all for specific table data # def remove_all(self, model): count = model.getRowCount() for i in xrange(count): model.removeRow(0) # # Implementaion of function for write data for specific file # def write_file(self, f, data): f.seek(0) f.write(data) f.truncate() return
class SessionFromRequestDialog(JDialog): def should_use(self, name): """Suggests if parameter with provided name should be used""" suggestions = ["session", "authenticity", "csrf", "xsrf"] name = name.lower() return any(map(lambda x: x in name, suggestions)) def save(self, evt): model = self.table.getModel() session = self._parent._extender.sm.selected_session session.reset() for r in range(model.getRowCount()): use = bool(model.getValueAt(r, 0)) type = str(model.getValueAt(r, 1)) name = model.getValueAt(r, 2) value = model.getValueAt(r, 3) if use: param = Parameter(type, Parameter.ACTION_MODIFY, name, self._parent._extender.helpers.urlDecode(value)) session.modify(param) self.setVisible(False) self.dispose() self._parent.refresh_sessions() self._parent.update_table() @attach_stack_trace def __init__(self, parent): self._parent = parent self.setTitle("Select Parameters/Headers for new Session") print "IN DIALOG!Q!!" self.table = JTable() columns = ["Use", "Type", "Name", "Value"] data = [] headers = self._parent._extender.headers parameters = self._parent._extender.parameters for header in headers[1:]: name, val = header.split(": ") data.append([self.should_use(name), "Header", name, val]) for param in parameters: data.append([self.should_use(param.getName()), Parameter.type_mapping[param.getType()], param.getName(), param.getValue()]) class CheckBoxTableModel(DefaultTableModel): def getColumnClass(self, x): if x == 0: return Boolean else: return String data_model = CheckBoxTableModel(data, columns) self.table.setModel(data_model) self.table.getColumnModel().getColumn(0).setMaxWidth(30) self.table.getColumnModel().getColumn(1).setMaxWidth(50) gridBagLayout = GridBagLayout() gridBagLayout.columnWidths = [ 0, 0, 0] gridBagLayout.rowHeights = [0, 0, 0] gridBagLayout.columnWeights = [0.0, 0.0, 0.0] gridBagLayout.rowWeights = [0.0, 1.0, 0.0] self.setLayout(gridBagLayout) self.getContentPane().add(JLabel("Select Parameters/Headers for new session:"), _new_grid_bag(0, 0, 3)) self.getContentPane().add(JScrollPane(self.table), _new_grid_bag(0, 1, 3)) self.getContentPane().add(JButton("Save", actionPerformed=self.save), _new_grid_bag(1, 2)) self.pack() self.setVisible(True)
class WS_Data_Analysis_Controller: """ This controller manages the WS data analysis. Its panel is in the WS_LW_Acquisition_Controller panel. """ def __init__(self,ws_lw_acquisition_controller): self.ws_lw_acquisition_controller = ws_lw_acquisition_controller self.local_gauss_fitter = Local_Gauss_Fitter() self.main_panel = JPanel(BorderLayout()) self.ws_records_table_model = WS_Records_Table_Model() #----etched border etched_border = BorderFactory.createEtchedBorder() #---make the WS_Records_JTable + Graph Panel self.records_table = JTable(self.ws_records_table_model) self.records_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.records_table.setFillsViewportHeight(true) #----set up records_table columns width columnModel = self.records_table.getColumnModel() columnModel.getColumn(0).setPreferredWidth(30) columnModel.getColumn(1).setPreferredWidth(160) columnModel.getColumn(2).setPreferredWidth(40) columnModel.getColumn(3).setPreferredWidth(40) columnModel.getColumn(4).setPreferredWidth(80) columnModel.getColumn(5).setPreferredWidth(70) columnModel.getColumn(6).setPreferredWidth(70) #--------------------------------------------------- records_panel = JPanel(BorderLayout()) records_panel.add(JScrollPane(self.records_table), BorderLayout.CENTER) knobs_gauss_panel = JPanel(BorderLayout()) records_panel.add(knobs_gauss_panel, BorderLayout.SOUTH) records_panel.setBorder(etched_border) #---records knobs --------------------------------------------- records_knobs_panel = JPanel(FlowLayout(FlowLayout.CENTER,5,5)) guess_and_fit_button = JButton("Guess and Fit") analysis_all_button = JButton("G&F All") fit_button = JButton("Fit") fit_all_button = JButton("Fit All") send_to_twiss_button = JButton("Send to Twiss Analysis") records_knobs_panel.add(guess_and_fit_button) records_knobs_panel.add(analysis_all_button) records_knobs_panel.add(fit_button) records_knobs_panel.add(fit_all_button) records_knobs_panel.add(send_to_twiss_button) guess_and_fit_button.addActionListener(Guess_And_Fit_Listener(self.ws_lw_acquisition_controller)) fit_button.addActionListener(Fit_Listener(self.ws_lw_acquisition_controller)) fit_all_button.addActionListener(Fit_All_Listener(self.ws_lw_acquisition_controller)) analysis_all_button.addActionListener(Guess_And_Fit_All_Listener(self.ws_lw_acquisition_controller)) send_to_twiss_button.addActionListener(SendToAnalysis_Listener(self.ws_lw_acquisition_controller)) self.gauss_fit_param_panel = GaussFitDataPanel() knobs_gauss_panel.add(records_knobs_panel, BorderLayout.NORTH) knobs_gauss_panel.add(self.gauss_fit_param_panel, BorderLayout.SOUTH) #--------------------------------------------------------- self.record_analysis_panel = JPanel(BorderLayout()) border = BorderFactory.createTitledBorder(etched_border,"WS/LW Wave Form Analysis") self.record_analysis_panel.setBorder(border) self.record_analysis_panel.add(records_panel, BorderLayout.WEST) self.gpanel_WF = FunctionGraphsJPanel() self.gpanel_WF.setLegendButtonVisible(true) self.gpanel_WF.setChooseModeButtonVisible(true) self.gpanel_WF.setName("Profile") self.gpanel_WF.setAxisNames("pos, [mm]","Amp, [arb. units]") self.gpanel_WF.setBorder(etched_border) self.gpanel_WF.addVerticalLine(-1.0e+30,Color.red) self.gpanel_WF.addVerticalLine(+1.0e+30,Color.red) self.gpanel_WF.setVerLinesButtonVisible(true) self.gpanel_WF.addDraggedVerLinesListener(Position_Limits_Listener(self.ws_lw_acquisition_controller)) write_waveforms_to_ascii_button = JButton("Write Waveforms to ASCII File") write_waveforms_to_ascii_button.addActionListener(Write_Waveforms_to_ASCII_Listener(self.ws_lw_acquisition_controller)) below_graph_panel = JPanel(FlowLayout(FlowLayout.LEFT,5,5)) below_graph_panel.add(write_waveforms_to_ascii_button) graph_panel_left = JPanel(BorderLayout()) graph_panel_left.add(self.gpanel_WF, BorderLayout.CENTER) graph_panel_left.add(below_graph_panel, BorderLayout.SOUTH) self.record_analysis_panel.add(graph_panel_left, BorderLayout.CENTER) self.main_panel.add(self.record_analysis_panel, BorderLayout.CENTER) #---set up Listeners self.records_table.getSelectionModel().addListSelectionListener(WS_Record_Table_Selection_Listener(self.ws_lw_acquisition_controller)) def setDataToGraphPanel(self,ws_record): self.gpanel_WF.removeAllGraphData() self.gpanel_WF.addGraphData(ws_record.gd_wf) self.gpanel_WF.addGraphData(ws_record.gd_fit_wf)
class SettingsTableFrame(JFrame): def __init__(self, *args, **kwargs): # do not create any class members before calling JFrame.__init__ ! s, size, title, savemode = None, None, None, False self.OKstatus = True if 'settings_config' in kwargs: s = kwargs.pop('settings_config') else: s = None if 'size' in kwargs: size = kwargs.pop('size') else: size = (300, 300) if 'widget' in kwargs: widget = kwargs.pop('widget') else: widget = None if 'savemode' in kwargs: savemode = kwargs.pop('savemode') defaultdir = None if 'defaultdir' in kwargs: defaultdir = kwargs.pop('defaultdir') if len(args) > 0: title = args[0] else: title = 'Save Settings' JFrame.__init__(self, title, size=size, **kwargs) self.widget = widget if self.widget == None: print "Need to pass keyword argument widget=widget when creating SettingsTableFrame" self.s = s self.savemode = savemode self.defaultdir = defaultdir # create FileChooser, make its window bigger and choose smaller font if self.defaultdir != None: self.fc = JFileChooser(self.defaultdir) else: self.fc = JFileChooser() self.fc.setPreferredSize(Dimension(800, 600)) smallfont = Font("Lucida Sans", Font.PLAIN, 12) SetFontRecursively(self.fc.getComponents(), smallfont) filefilter = FileNameExtensionFilter("Settings Files", (DEFAULT_EXTENSION, )) self.fc.setFileFilter(filefilter) # fill the table, in save mode only with the current values, in load mode with current and setting values self.prepare_tabledata() # if not savemode, we first pop up a filechooser to select a loadable setting if self.savemode == False: self.OKstatus = self.load_setting() if not self.OKstatus: return # listener for data edited by user, good for providing PV write access within the table to the user self.dataListener = MyTableModelListener(savemode=self.savemode) self.dataModel.addTableModelListener(self.dataListener) self.table = JTable(self.dataModel) # create Buttons self.bu_do_label = "Save" if self.savemode == True else "Load" self.bu_do_handler = self.bu_save_handler if self.savemode == True else self.bu_load_handler self.bu_do = JButton(self.bu_do_label, actionPerformed=self.bu_do_handler) self.bu_cancel = JButton("Cancel", actionPerformed=self.bu_cancel_handler) # BEGIN visual adaptations of JTable self.table.setRowHeight(24) self.table.getColumnModel().getColumn(0).setMinWidth(200) if self.savemode: self.table.getColumnModel().getColumn(3).setMaxWidth(60) else: self.table.getColumnModel().getColumn(4).setMaxWidth(60) smallfontr = MyTableCellRenderer(font=FONT_FAMILY, style=Font.PLAIN, fontsize=10) smallfontr.setHorizontalAlignment(JLabel.CENTER) bigfontplainr = MyTableCellRenderer(font=FONT_FAMILY, style=Font.PLAIN, fontsize=18) bigfontplainr.setHorizontalAlignment(JLabel.CENTER) bigfontr = MyTableCellRenderer(font=FONT_FAMILY, style=Font.BOLD, fontsize=18) bigfontr.setHorizontalAlignment(JLabel.CENTER) self.table.getColumnModel().getColumn(0).setCellRenderer(smallfontr) self.table.getColumnModel().getColumn(1).setCellRenderer(bigfontplainr) self.table.getColumnModel().getColumn(2).setCellRenderer(bigfontr) if not self.savemode: self.table.getColumnModel().getColumn(3).setCellRenderer(bigfontr) # END visual adaptations of JTable ## BEGIN layout of window (JFrame) self.getContentPane().setLayout(BorderLayout()) self.add(JScrollPane(self.table)) self.bottompanel = JPanel() self.bottompanel.setLayout( BoxLayout(self.bottompanel, BoxLayout.LINE_AXIS)) self.bottompanel.add(Box.createHorizontalGlue()) self.bottompanel.add(self.bu_do) self.bottompanel.add(Box.createRigidArea(Dimension(20, 0))) self.bottompanel.add(self.bu_cancel) self.bottompanel.add(Box.createHorizontalGlue()) self.add(self.bottompanel, BorderLayout.SOUTH) # END layout of window (JFrame) def bu_cancel_handler(self, event): self.dispose() def bu_save_handler(self, event): dlg_answer = self.fc.showSaveDialog(self) if dlg_answer == self.fc.CANCEL_OPTION: return if dlg_answer == self.fc.APPROVE_OPTION: # user clicked SAVE f = self.fc.getSelectedFile().getAbsolutePath() if not str(f).endswith("." + DEFAULT_EXTENSION): f = f + "." + DEFAULT_EXTENSION if os.path.exists( f): # file already exists, let user confirm overwriting choice = JOptionPane.showConfirmDialog( self, "The file exists, overwrite?", "Existing file", JOptionPane.YES_NO_CANCEL_OPTION) if choice in (JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION): return if choice == JOptionPane.YES_OPTION: self.do_save(f) self.dispose() else: # file does not exist, yet -> don't need to ask self.do_save(f) self.dispose() def bu_load_handler(self, event): for i in range(self.dataModel.getRowCount()): if self.dataModel.getValueAt(i, RESTORE_COL_LOADMODE) == False: continue curval = self.dataModel.getValueAt(i, VALUE_COLUMN) setval = self.dataModel.getValueAt(i, SETTING_COLUMN) if curval == '---' or setval == '---': # either PV does not exist or value missing in the settings file continue pvname = self.dataModel.getValueAt(i, PV_COLUMN) writejob = BackgroundPVWriter(pvname, setval) writejob.schedule() self.dispose() def load_setting(self): dlg_answer = self.fc.showOpenDialog(self) if dlg_answer == self.fc.CANCEL_OPTION: return False if dlg_answer == self.fc.APPROVE_OPTION: f = self.fc.getSelectedFile().getAbsolutePath() self.parse_setting(f) return True def parse_setting(self, fpath): # compatible to old set files with open(fpath, "r") as f: idxset = set(range(self.dataModel.getRowCount())) #lbuf = [l for l in f] # need to create a file buffer to traverse twice through the file for l in f: if len(l) == 0 or l.startswith('#'): continue els = l.split() idstr = els[0] checkcolumn = ID_COLUMN for i in idxset: if self.dataModel.getValueAt(i, checkcolumn) == idstr: self.dataModel.setValueAt(els[1], i, SETTING_COLUMN) idxset.remove(i) # remove restore flag for PVs that were missing in the settings file for i in idxset: self.dataModel.setValueAt(False, i, RESTORE_COL_LOADMODE) def parse_setting_pvtable_format(self, fpath): with open(fpath, "r") as f: idxset = set(range(self.dataModel.getRowCount())) lbuf = [ l for l in f ] # need to create a file buffer to traverse twice through the file # parse ID PVNAME mappings if present mapping_header_found = False pv_to_id = dict() for l in lbuf: if not mapping_header_found: if l.startswith("### Mapping ID to PV"): mapping_header_found = True continue if not l.startswith("# "): continue els = l.split() idstr = els[1] pvstr = " ".join( els[2:] ) # tango PVs may contain blanks if additional parameters were included pv_to_id[pvstr] = idstr # second run through file: fill our table with values read from the file for l in lbuf: if len(l) == 0 or l.startswith('#'): continue els = l.split() # default to PVNAME comparison if no PVNAME->ID mapping exists idstr = els[0] checkcolumn = PV_COLUMN # check if mapping exists, and override if so if idstr in pv_to_id: idstr = pv_to_id[idstr] # (set idstr to the mapped ID) checkcolumn = ID_COLUMN # (tell the following code that ID_COLUMN has to be compared) for i in idxset: if self.dataModel.getValueAt(i, checkcolumn) == idstr: self.dataModel.setValueAt(els[1], i, SETTING_COLUMN) idxset.remove(i) # remove restore flag for PVs that were missing in the settings file for i in idxset: self.dataModel.setValueAt(False, i, RESTORE_COL_LOADMODE) def do_save(self, filepath): # creates something compatible to older set files now = datetime.datetime.now() with open(filepath, "w") as f: f.write("### ------------------------------------\n") f.write("### SETTING saved from CSS\n") f.write("### " + now.strftime("Date: %Y-%m-%d Time: %H:%M") + "\n") f.write("### ------------------------------------\n") for row_index in range(self.dataModel.getRowCount()): IDstr = str(self.dataModel.getValueAt(row_index, ID_COLUMN)) valstr = str(self.dataModel.getValueAt(row_index, VALUE_COLUMN)) f.write("%s %s\n" % (IDstr, valstr)) f.write("### Mapping ID to PV\n") for row_index in range(self.dataModel.getRowCount()): IDstr = str(self.dataModel.getValueAt(row_index, ID_COLUMN)) PVstr = str(self.dataModel.getValueAt(row_index, PV_COLUMN)) f.write("# %s %s\n" % (IDstr, PVstr)) def do_save_pvtableformat(self, filepath): now = datetime.datetime.now() with open(filepath, "w") as f: f.write("# save/restore file generated by CSS PVTable, " + now.strftime("%Y-%m-%d %H:%M:0.0") + "\n") for row_index in range(self.dataModel.getRowCount()): PVstr = str(self.dataModel.getValueAt(row_index, PV_COLUMN)) valstr = str(self.dataModel.getValueAt(row_index, VALUE_COLUMN)) f.write("%s %s\n" % (PVstr, valstr)) f.write("<END>\n") f.write("### ------------------------------------\n") f.write("### SETTING saved from CSS\n") f.write("### " + now.strftime("Date: %Y-%m-%d Time: %H:%M") + "\n") f.write("### ------------------------------------\n") f.write("### Mapping ID to PV\n") for row_index in range(self.dataModel.getRowCount()): IDstr = str(self.dataModel.getValueAt(row_index, ID_COLUMN)) PVstr = str(self.dataModel.getValueAt(row_index, PV_COLUMN)) f.write("# %s %s\n" % (IDstr, PVstr)) def prepare_tabledata(self): if self.s == None: self.tableData = [['', '', '', '', False]] else: self.tableData = [] for l in self.s: idstr = l[0] pvname = l[1] # read PV value curval = "---" restore_flag = l[2] try: ipv = PVUtil.createPV(pvname, self.widget) curval = PVUtil.getString(ipv) except: restore_flag = False if self.savemode: self.tableData.append( [pvname, idstr, curval, restore_flag]) else: self.tableData.append( [pvname, idstr, curval, '---', restore_flag]) if self.savemode: self.colNames = TABLE_HEADER_SAVEMODE else: self.colNames = TABLE_HEADER_LOADMODE self.dataModel = MyTableModel(self.tableData, self.colNames, savemode=self.savemode)
class SessionFromRequestDialog(JDialog): def should_use(self, name): """Suggests if parameter with provided name should be used""" suggestions = ["session", "authenticity", "csrf", "xsrf"] name = name.lower() return any(map(lambda x: x in name, suggestions)) def save(self, evt): model = self.table.getModel() session = self._parent._extender.sm.selected_session session.reset() for r in range(model.getRowCount()): use = bool(model.getValueAt(r, 0)) type = str(model.getValueAt(r, 1)) name = model.getValueAt(r, 2) value = model.getValueAt(r, 3) if use: param = Parameter( type, Parameter.ACTION_MODIFY, name, self._parent._extender.helpers.urlDecode(value)) session.modify(param) self.setVisible(False) self.dispose() self._parent.refresh_sessions() self._parent.update_table() @attach_stack_trace def __init__(self, parent): self._parent = parent self.setTitle("Select Parameters/Headers for new Session") print "IN DIALOG!Q!!" self.table = JTable() columns = ["Use", "Type", "Name", "Value"] data = [] headers = self._parent._extender.headers parameters = self._parent._extender.parameters for header in headers[1:]: name, val = header.split(": ") data.append([self.should_use(name), "Header", name, val]) for param in parameters: data.append([ self.should_use(param.getName()), Parameter.type_mapping[param.getType()], param.getName(), param.getValue() ]) class CheckBoxTableModel(DefaultTableModel): def getColumnClass(self, x): if x == 0: return Boolean else: return String data_model = CheckBoxTableModel(data, columns) self.table.setModel(data_model) self.table.getColumnModel().getColumn(0).setMaxWidth(30) self.table.getColumnModel().getColumn(1).setMaxWidth(50) gridBagLayout = GridBagLayout() gridBagLayout.columnWidths = [0, 0, 0] gridBagLayout.rowHeights = [0, 0, 0] gridBagLayout.columnWeights = [0.0, 0.0, 0.0] gridBagLayout.rowWeights = [0.0, 1.0, 0.0] self.setLayout(gridBagLayout) self.getContentPane().add( JLabel("Select Parameters/Headers for new session:"), _new_grid_bag(0, 0, 3)) self.getContentPane().add(JScrollPane(self.table), _new_grid_bag(0, 1, 3)) self.getContentPane().add(JButton("Save", actionPerformed=self.save), _new_grid_bag(1, 2)) self.pack() self.setVisible(True)
def _initializeGui(self, callbacks): tab = JPanel() jLabel1 = JLabel("Original Hash:") jLabel2 = JLabel("Original message:") jLabel3 = JLabel("Message to append:") jLabel5 = JLabel("Max key length:") jTextField1 = JTextField("") jTextField2 = JTextField("") jTextField3 = JTextField("") jTextField4 = JTextField("128") jLabel4 = JLabel("Hashing functions") jCheckBox1 = JCheckBox("MD4") jCheckBox2 = JCheckBox("MD5") jCheckBox3 = JCheckBox("SHA1") jCheckBox4 = JCheckBox("SHA256") jCheckBox5 = JCheckBox("SHA512") jCheckBox1.setEnabled(False) jCheckBox2.setEnabled(False) jCheckBox3.setEnabled(False) jCheckBox4.setEnabled(False) jCheckBox5.setEnabled(False) jScrollPane1 = JScrollPane() jTable1 = JTable() jButton1 = JButton("Generate", actionPerformed=self.generate_attack) jButton1.setEnabled(False) jButton2 = JButton("Copy messages", actionPerformed=self.copy_messages) jButton3 = JButton("Copy hashes", actionPerformed=self.copy_hashes) self._tab = tab self._textfields = { "original_hash": jTextField1, "original_msg": jTextField2, "append_msg": jTextField3, "max_key_len": jTextField4, } self._checkboxes = { md4: jCheckBox1, md5: jCheckBox2, sha1: jCheckBox3, sha256: jCheckBox4, sha512: jCheckBox5, } self._table = jTable1 self._extensions = {} self._hashes, self._messages = [], [] # Hash field change event jTextField1.getDocument().addDocumentListener(HashChangeListener(self._checkboxes, self._textfields['original_hash'], jButton1)) # Table columns jTable1.setModel(DefaultTableModel([],["#", "Type","New Message", "Hash"])) jScrollPane1.setViewportView(jTable1) # Table column width jTable1.getColumnModel().getColumn(0).setMaxWidth(50) jTable1.getColumnModel().getColumn(1).setMaxWidth(60) layout = GroupLayout(tab) tab.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(jLabel5) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(jTextField3, GroupLayout.DEFAULT_SIZE, 425, 32767) .addComponent(jTextField2) .addComponent(jTextField1) .addGroup(layout.createSequentialGroup() .addComponent(jTextField4, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 32767))) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jCheckBox1) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox2) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox3) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox4) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox5)) .addComponent(jLabel4) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2))) .addGap(167, 167, 167)) .addComponent(jScrollPane1) ) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(jCheckBox2) .addComponent(jCheckBox3) .addComponent(jCheckBox1) .addComponent(jCheckBox4) .addComponent(jCheckBox5))) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(jTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton1)) .addGap(13, 13, 13) .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 971, 32767)) ) callbacks.customizeUiComponent(tab) callbacks.addSuiteTab(self)
class QatDialog(ToggleDialog): """ToggleDialog for error type selection and buttons for reviewing errors in sequence """ def __init__(self, name, iconName, tooltip, shortcut, height, app): ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height) self.app = app tools = app.tools #Main panel of the dialog mainPnl = JPanel(BorderLayout()) mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1)) ### First tab: errors selection and download ########################### #ComboBox with tools names self.toolsComboModel = DefaultComboBoxModel() for tool in tools: self.add_data_to_models(tool) self.toolsCombo = JComboBox(self.toolsComboModel, actionListener=ToolsComboListener(app)) renderer = ToolsComboRenderer(self.app) renderer.setPreferredSize(Dimension(20, 20)) self.toolsCombo.setRenderer(renderer) self.toolsCombo.setToolTipText( app.strings.getString("Select_a_quality_assurance_tool")) #ComboBox with categories names ("views"), of the selected tool self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app)) self.viewsCombo.setToolTipText( app.strings.getString("Select_a_category_of_error")) #Popup for checks table self.checkPopup = JPopupMenu() #add favourite check self.menuItemAdd = JMenuItem( self.app.strings.getString("Add_to_favourites")) self.menuItemAdd.setIcon( ImageIcon( File.separator.join([ self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons", "tool_16.png" ]))) self.menuItemAdd.addActionListener(PopupActionListener(self.app)) self.checkPopup.add(self.menuItemAdd) #remove favourite check self.menuItemRemove = JMenuItem( self.app.strings.getString("Remove_from_favourites")) self.menuItemRemove.setIcon( ImageIcon( File.separator.join([ self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons", "black_tool_16.png" ]))) self.menuItemRemove.addActionListener(PopupActionListener(self.app)) self.checkPopup.add(self.menuItemRemove) #Help link for selected check self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help")) self.menuItemHelp.setIcon( ImageIcon( File.separator.join( [self.app.SCRIPTDIR, "images", "icons", "info_16.png"]))) self.checkPopup.add(self.menuItemHelp) self.menuItemHelp.addActionListener(PopupActionListener(self.app)) #Table with checks of selected tool and view self.checksTable = JTable() self.iconrenderer = IconRenderer() self.iconrenderer.setHorizontalAlignment(JLabel.CENTER) scrollPane = JScrollPane(self.checksTable) self.checksTable.setFillsViewportHeight(True) tableSelectionModel = self.checksTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ChecksTableListener(app)) self.checksTable.addMouseListener( ChecksTableClickListener(app, self.checkPopup, self.checksTable)) #Favourite area status indicator self.favAreaIndicator = JLabel() self.update_favourite_zone_indicator() self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app)) #label with OSM id of the object currently edited and number of #errors still to review self.checksTextFld = JTextField("", editable=0, border=None, background=None) #checks buttons btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"]) downloadIcon = ImageIcon( File.separator.join([btnsIconsDir, "download.png"])) self.downloadBtn = JButton(downloadIcon, actionPerformed=app.on_downloadBtn_clicked, enabled=0) startIcon = ImageIcon( File.separator.join([btnsIconsDir, "start_fixing.png"])) self.startBtn = JButton(startIcon, actionPerformed=app.on_startBtn_clicked, enabled=0) self.downloadBtn.setToolTipText( app.strings.getString("Download_errors_in_this_area")) self.startBtn.setToolTipText( app.strings.getString("Start_fixing_the_selected_errors")) #tab layout panel1 = JPanel(BorderLayout(0, 1)) comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0)) comboboxesPnl.add(self.toolsCombo) comboboxesPnl.add(self.viewsCombo) checksPnl = JPanel(BorderLayout(0, 1)) checksPnl.add(scrollPane, BorderLayout.CENTER) self.statsPanel = JPanel(BorderLayout(4, 0)) self.statsPanel_def_color = self.statsPanel.getBackground() self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER) self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START) checksPnl.add(self.statsPanel, BorderLayout.PAGE_END) checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0)) checksButtonsPnl.add(self.downloadBtn) checksButtonsPnl.add(self.startBtn) panel1.add(comboboxesPnl, BorderLayout.PAGE_START) panel1.add(checksPnl, BorderLayout.CENTER) panel1.add(checksButtonsPnl, BorderLayout.PAGE_END) ### Second tab: errors fixing ########################################## #label with error stats self.errorTextFld = JTextField("", editable=0, border=None, background=None) #label with current error description self.errorDesc = JLabel("") self.errorDesc.setAlignmentX(0.5) #error buttons errorInfoBtnIcon = ImageProvider.get("info") self.errorInfoBtn = JButton( errorInfoBtnIcon, actionPerformed=app.on_errorInfoBtn_clicked, enabled=0) notErrorIcon = ImageIcon( File.separator.join([btnsIconsDir, "not_error.png"])) self.notErrorBtn = JButton( notErrorIcon, actionPerformed=app.on_falsePositiveBtn_clicked, enabled=0) ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"])) self.ignoreBtn = JButton(ignoreIcon, actionPerformed=app.on_ignoreBtn_clicked, enabled=0) correctedIcon = ImageIcon( File.separator.join([btnsIconsDir, "corrected.png"])) self.correctedBtn = JButton( correctedIcon, actionPerformed=app.on_correctedBtn_clicked, enabled=0) nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"])) self.nextBtn = JButton(nextIcon, actionPerformed=app.on_nextBtn_clicked, enabled=0) #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT) self.errorInfoBtn.setToolTipText( app.strings.getString("open_error_info_dialog")) self.notErrorBtn.setToolTipText( app.strings.getString("flag_false_positive")) self.ignoreBtn.setToolTipText( app.strings.getString("Skip_and_don't_show_me_this_error_again")) self.correctedBtn.setToolTipText( app.strings.getString("flag_corrected_error")) self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error")) #tab layout self.panel2 = JPanel(BorderLayout()) self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START) self.panel2.add(self.errorDesc, BorderLayout.CENTER) errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0)) errorButtonsPanel.add(self.errorInfoBtn) errorButtonsPanel.add(self.notErrorBtn) errorButtonsPanel.add(self.ignoreBtn) errorButtonsPanel.add(self.correctedBtn) errorButtonsPanel.add(self.nextBtn) self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END) #Layout self.tabbedPane = JTabbedPane() self.tabbedPane.addTab(self.app.strings.getString("Download"), None, panel1, self.app.strings.getString("download_tab")) mainPnl.add(self.tabbedPane, BorderLayout.CENTER) self.createLayout(mainPnl, False, None) def add_data_to_models(self, tool): """Add data of a tool to the models of the dialog components """ #tools combobox model if tool == self.app.favouritesTool: self.toolsComboModel.addElement(JSeparator()) self.toolsComboModel.addElement(tool) #views combobox model tool.viewsComboModel = DefaultComboBoxModel() for view in tool.views: tool.viewsComboModel.addElement(view.title) #checks table, one TableModel for each view, of each tool columns = [ "", self.app.strings.getString("Check"), self.app.strings.getString("Errors") ] for view in tool.views: tableRows = [] for check in view.checks: if check.icon is not None: icon = check.icon else: icon = "" errorsNumber = "" tableRows.append([icon, check.title, errorsNumber]) view.tableModel = MyTableModel(tableRows, columns) def update_favourite_zone_indicator(self): #icon if self.app.favZone is not None: self.favAreaIndicator.setIcon(self.app.favZone.icon) #tooltip messageArguments = array([self.app.favZone.name], String) formatter = MessageFormat("") formatter.applyPattern( self.app.strings.getString("favAreaIndicator_tooltip")) msg = formatter.format(messageArguments) self.favAreaIndicator.setToolTipText(msg) #status self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus) def set_checksTextFld_color(self, color): """Change color of textField under checksTable """ colors = { "white": (255, 255, 255), "black": (0, 0, 0), "green": (100, 200, 0), "red": (200, 0, 0) } if color == "default": self.statsPanel.background = self.statsPanel_def_color self.checksTextFld.foreground = colors["black"] else: self.statsPanel.background = colors[color] self.checksTextFld.foreground = colors["white"] def change_selection(self, source): """Change comboboxes and checks table selections after a selection has been made by the user """ if source in ("menu", "layer", "add favourite"): self.app.selectionChangedFromMenuOrLayer = True self.toolsCombo.setSelectedItem(self.app.selectedTool) self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel) self.viewsCombo.setSelectedItem(self.app.selectedView.title) self.checksTable.setModel(self.app.selectedTableModel) self.refresh_checksTable_columns_geometries() for i, c in enumerate(self.app.selectedView.checks): if c == self.app.selectedChecks[0]: break self.checksTable.setRowSelectionInterval(i, i) self.app.selectionChangedFromMenuOrLayer = False else: self.app.selectionChangedFromMenuOrLayer = False if source == "toolsCombo": self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel) self.viewsCombo.setSelectedIndex(0) elif source == "viewsCombo": self.checksTable.setModel(self.app.selectedTableModel) self.refresh_checksTable_columns_geometries() if self.app.selectedView.checks != []: # favourite checks may be none self.checksTable.setRowSelectionInterval(0, 0) def refresh_checksTable_columns_geometries(self): self.checksTable.getColumnModel().getColumn(0).setCellRenderer( self.iconrenderer) self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25) self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60) def activate_error_tab(self, status): if status: if self.tabbedPane.getTabCount() == 1: self.tabbedPane.addTab(self.app.strings.getString("Fix"), None, self.panel2, self.app.strings.getString("fix_tab")) else: if self.tabbedPane.getTabCount() == 2: self.tabbedPane.remove(1) def update_checks_buttons(self): """This method sets the status of downloadBtn and startBtn """ #none check selected if len(self.app.selectedChecks) == 0: self.downloadBtn.setEnabled(False) self.startBtn.setEnabled(False) else: #some check selected self.downloadBtn.setEnabled(True) if len(self.app.selectedChecks) > 1: self.startBtn.setEnabled(False) else: #only one check is selected self.app.errors = self.app.selectedChecks[0].errors if self.app.errors is None or len(self.app.errors) == 0: #errors file has not been downloaded and parsed yet self.startBtn.setEnabled(False) else: #errors file has been downloaded and parsed if self.app.selectedChecks[0].toDo == 0: #all errors have been corrected self.startBtn.setEnabled(False) else: self.startBtn.setEnabled(True) #self.nextBtn.setEnabled(True) def update_error_buttons(self, mode): """This method sets the status of: ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn """ if mode == "new error": status = True else: status = False if self.app.selectedChecks[0].tool.fixedFeedbackMode is None: self.correctedBtn.setEnabled(False) else: self.correctedBtn.setEnabled(status) if self.app.selectedChecks[0].tool.falseFeedbackMode is None: self.notErrorBtn.setEnabled(False) else: self.notErrorBtn.setEnabled(status) self.errorInfoBtn.setEnabled(status) self.ignoreBtn.setEnabled(status) if mode in ("reset", "review end"): self.nextBtn.setEnabled(False) elif mode in ("errors downloaded", "show stats", "new error"): self.nextBtn.setEnabled(True) def update_text_fields(self, mode, errorInfo=""): """This method updates the text in: checksTextFld, errorDesc, errorTextFld """ self.errorDesc.text = "" if mode == "review end": cheksTextColor = "green" checksText = self.app.strings.getString("All_errors_reviewed.") errorText = self.app.strings.getString("All_errors_reviewed.") elif mode == "reset": cheksTextColor = "default" checksText = "" errorText = "" elif mode == "show stats": cheksTextColor = "default" checksText = "%s %d / %s" % ( self.app.strings.getString("to_do"), self.app.selectedChecks[0].toDo, len(self.app.selectedChecks[0].errors)) #print "checks text", checksText errorText = "%s%s %d / %s" % ( errorInfo, self.app.strings.getString("to_do"), self.app.selectedChecks[0].toDo, len(self.app.selectedChecks[0].errors)) #print "error text", errorText if self.app.selectedError is not None and self.app.selectedError.desc != "": self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc self.set_checksTextFld_color(cheksTextColor) self.checksTextFld.text = checksText self.errorTextFld.text = errorText self.update_statsPanel_status() def update_statsPanel_status(self): if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus: self.statsPanel.setVisible(False) else: self.statsPanel.setVisible(True)