def __init__(self, parent, title, modal, app): border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) #Intro falsePositivePng = File.separator.join( [app.SCRIPTDIR, "images", "icons", "not_error36.png"]) introLbl = JMultilineLabel( app.strings.getString("manual_false_positives_info")) introLbl.setMaxWidth(600) #Table table = JTable() columns = [ app.strings.getString("Tool"), app.strings.getString("Check"), app.strings.getString("Error_id"), app.strings.getString("OSM_id") ] self.tableModel = MyTableModel([], columns) table.setModel(self.tableModel) scrollPane = JScrollPane(table) scrollPane.setAlignmentX(0.0) #OK button btnPanel = JPanel(FlowLayout(FlowLayout.CENTER)) okBtn = JButton("OK", ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) btnPanel.add(okBtn) btnPanel.setAlignmentX(0.0) #Layout headerPnl = JPanel() headerPnl.setLayout(BoxLayout(headerPnl, BoxLayout.X_AXIS)) headerPnl.add(JLabel(ImageIcon(falsePositivePng))) headerPnl.add(Box.createRigidArea(Dimension(10, 0))) headerPnl.add(introLbl) headerPnl.setAlignmentX(0.0) self.add(headerPnl) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(scrollPane) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(btnPanel) self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) self.pack()
def __init__(self, parent, title, modal, app): border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) #Intro falsePositivePng = File.separator.join([app.SCRIPTDIR, "images", "icons", "not_error36.png"]) introLbl = JMultilineLabel(app.strings.getString("manual_false_positives_info")) introLbl.setMaxWidth(600) #Table table = JTable() columns = [app.strings.getString("Tool"), app.strings.getString("Check"), app.strings.getString("Error_id"), app.strings.getString("OSM_id")] self.tableModel = MyTableModel([], columns) table.setModel(self.tableModel) scrollPane = JScrollPane(table) scrollPane.setAlignmentX(0.0) #OK button btnPanel = JPanel(FlowLayout(FlowLayout.CENTER)) okBtn = JButton("OK", ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) btnPanel.add(okBtn) btnPanel.setAlignmentX(0.0) #Layout headerPnl = JPanel() headerPnl.setLayout(BoxLayout(headerPnl, BoxLayout.X_AXIS)) headerPnl.add(JLabel(ImageIcon(falsePositivePng))) headerPnl.add(Box.createRigidArea(Dimension(10, 0))) headerPnl.add(introLbl) headerPnl.setAlignmentX(0.0) self.add(headerPnl) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(scrollPane) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(btnPanel) self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) self.pack()
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 EmployeeDetails(JPanel): def __init__(self, employees, dateprovider): JPanel.__init__(self, preferredSize=(400, 200)) layout = BoxLayout(self, BoxLayout.Y_AXIS) self.setLayout(layout) self._employees = employees self._dateprovider = dateprovider employees.add_change_listener(self) self._create_status_label() self._create_name_editor() self._create_start_date_editor() self._create_save_button() self._create_vacation_display() self._adding_employee = False def _create_status_label(self): self._status_label = JLabel(name="status_label", font=Font(Font.SANS_SERIF, Font.PLAIN, 11)) self.add(self._status_label) self._add_with_padding(self._status_label, 5) def _create_name_editor(self): self.add(JLabel(text="Employee Name:")) self._name_editor = FixedHeightTextField("name_input") self._add_with_padding(self._name_editor, 5) def _create_start_date_editor(self): self.add(JLabel(text="Start Date (yyyy-mm-dd):")) self._start_date_editor = FixedHeightTextField("start_input") self._add_with_padding(self._start_date_editor, 5) def _create_save_button(self): self._save_button = JButton("Save", name="save_button", visible=False) self._save_button.addActionListener(ListenerFactory(ActionListener, self._save_button_pushed)) self._add_with_padding(self._save_button, 5) def _create_vacation_display(self): self._display = JTable(name="vacation_display") self._header = self._display.getTableHeader() self.add(self._header) self.add(self._display) def _add_with_padding(self, component, padding): self.add(component) self.add(Box.createRigidArea(Dimension(0, padding))) def show_employee(self, employee): self._name_editor.setText(employee.name) self._start_date_editor.setText(str(employee.startdate)) self._name_editor.setEditable(False) self._start_date_editor.setEditable(False) self._save_button.setVisible(False) if self._adding_employee: self._adding_employee = False else: self._status_label.setText("") self._display.setVisible(True) self._display.setModel(VacationTableModel(employee, self._dateprovider)) self._header.setVisible(True) def edit_new_employee(self): self._name_editor.setText("") self._start_date_editor.setText("") self._name_editor.setEditable(True) self._start_date_editor.setEditable(True) self._save_button.setVisible(True) self._display.setVisible(False) self._header.setVisible(False) self._adding_employee = True def _save_button_pushed(self, event): self._employees.add(self._name_editor.getText(), self._start_date_editor.getText()) def employee_added(self, employee): self._status_label.setForeground(Color.BLACK) self._status_label.setText("Employee '%s' was added successfully." % employee.name) self._save_button.setVisible(False) def adding_employee_failed(self, reason): self._status_label.setForeground(Color.RED) self._status_label.setText(reason)
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)
class PropertyEditor(WindowAdapter): """ Edits Tabular Properties of a given WindowAdapter """ instances = {} last_location = None locations = {} last_size = None sizes = {} NEW_WINDOW_OFFSET = 32 offset = NEW_WINDOW_OFFSET @staticmethod def get_instance(text="Property Editor", columns=None, data=None, empty=None, add_actions=True, actions=None): """ Singleton Method based on the text property. It tries to generate only one property configuration page per text. :param text: getinstance key :param columns: proparty columns it should be an array alike :param data: it contains the current property rows :param empty: empty row property when adding a new one :param add_actions: include or not new actions :param actions: default set of actions to be appended to Add and Delete Rows :return: a new instance of PropertyEditor or a reused one. """ if not actions: actions = [] if not columns: columns = [] if data == None: data = [] if not empty: empty = [] try: PropertyEditor.instances[text] except KeyError: PropertyEditor.instances[text] = \ PropertyEditor().__private_init__(text, columns, data, empty, add_actions, actions) try: PropertyEditor.instances[text].this.setLocation( PropertyEditor.locations[text]) except KeyError: if PropertyEditor.last_location: PropertyEditor.instances[text].this.setLocation( PropertyEditor.last_location.x + PropertyEditor.offset, PropertyEditor.last_location.y + PropertyEditor.offset) PropertyEditor.offset = PropertyEditor.NEW_WINDOW_OFFSET try: PropertyEditor.instances[text].this.setSize( PropertyEditor.sizes[text]) except KeyError: if PropertyEditor.last_size: PropertyEditor.instances[text].this.setSize( PropertyEditor.last_size) PropertyEditor.last_location = PropertyEditor.instances[ text].this.getLocation() PropertyEditor.last_size = PropertyEditor.instances[ text].this.getSize() ## Hack ON: Bring on Front PropertyEditor.instances[text].this.setAlwaysOnTop(True) PropertyEditor.instances[text].this.setAlwaysOnTop(False) ## Hack OFF return PropertyEditor.instances[text] def __private_init__(self, text="Property Editor", columns=None, data=None, empty=None, add_actions=True, actions=None): if not actions: actions = [] if not columns: columns = [] if data == None: data = [] if not empty: empty = [] self._text = text self.this = JFrame(text) self._table = JTable() self._dtm = DefaultTableModel(0, 0) self._dtm.setColumnIdentifiers(columns) self._table.setModel(self._dtm) self._data = data for d in data: self._dtm.addRow(d) self._pane = JScrollPane(self._table) self.this.add(self._pane) self._empty = empty self.this.addWindowListener(self) self._dtm.addTableModelListener(lambda _: self._update_model()) self.this.setLocation(PropertyEditor.NEW_WINDOW_OFFSET, PropertyEditor.NEW_WINDOW_OFFSET) if add_actions: self._popup = JPopupMenu() self._pane.setComponentPopupMenu(self._popup) inherits_popup_menu(self._pane) self._actions = actions self._actions.append( ExecutorAction('Remove Selected Rows', action=lambda e: self._remove_row())) self._actions.append( ExecutorAction('Add New Row', action=lambda e: self._add_row())) for action in self._actions: self._popup.add(action.menuitem) self.this.setForeground(Color.black) self.this.setBackground(Color.lightGray) self.this.pack() self.this.setVisible(True) self.this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) return self def _add_row(self): """ Add a new row the selection :return: None """ self._dtm.addRow(self._empty) def _remove_row(self): """ Remove all the selected rows from the selection :return: """ rows = self._table.getSelectedRows() for i in range(0, len(rows)): self._dtm.removeRow(rows[i] - i) def windowClosing(self, evt): """ Overrides WindowAdapter method :param evt: unused :return: None """ PropertyEditor.locations[self._text] = self.this.getLocation() PropertyEditor.sizes[self._text] = self.this.getSize() PropertyEditor.last_location = self.this.getLocation() PropertyEditor.last_size = self.this.getSize() PropertyEditor.offset = 0 self.this.setVisible(False) self.this.dispose() del PropertyEditor.instances[self._text] def _update_model(self): """ Update the data content with the updated rows :return: None """ del self._data[:] nRow = self._dtm.getRowCount() nCol = self._dtm.getColumnCount() for i in range(0, nRow): self._data.append([None] * nCol) for j in range(0, nCol): d = str(self._dtm.getValueAt(i, j)).lower() if d == 'none' or d == '': self._data[i][j] = None elif d == 'true' or d == 't': self._data[i][j] = True elif d == 'false' or d == 'f': self._data[i][j] = False else: try: self._data[i][j] = int(self._dtm.getValueAt(i, j)) except ValueError: self._data[i][j] = self._dtm.getValueAt(i, j)
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 NBPanel(): """Represents the converted frame from NetBeans.""" # mostly converted generated code def __init__(self): self.jScrollPane1 = JScrollPane() self.jTable1 = JTable() self.jPanel1 = JPanel() self.labelName = JLabel() self.textName = JTextField() self.labelSeverity = JLabel() self.comboSeverity = None self.labelHost = JLabel() self.labelPath = JLabel() self.textHost = JTextField() self.textPath = JTextField() self.tabIssue = JTabbedPane() self.panelDescription = JPanel() self.panelRequest = JPanel() self.panelResponse = JPanel() self.panelRemediation = JPanel() # setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) # setting up the table # initial data in the table tableData = [[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]] tableColumns = ["#", "Issue Type/Name", "Severity", "Host", "Path"] # create the table model tableModel = table.DefaultTableModel(tableData, tableColumns) # model.types = array.array([java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class], java.lang.Class) # model.canEdit = array.array([False, False, False, False, False], java.lang.Boolean) # public Class getColumnClass(int columnIndex) { # return types [columnIndex] # } # # public boolean isCellEditable(int rowIndex, int columnIndex) { # return canEdit [columnIndex] # } # set the table model # if this fails, we have to use self.jTable1.setModel(tableModel) self.jTable1.setAutoCreateRowSorter(True) # wrap the table in a scrollpane self.jScrollPane1.setViewportView(self.jTable1) # top panel containing the table from java.awt import Color self.jPanel1.setBorder(BorderFactory.createLineBorder(Color(0, 0, 0))) # create the labels and textfields self.labelName.text = "Issue Type/Name" self.textName.text = "Issue Name/Type" self.labelSeverity.text = "Severity" # create and populate the combobox self.comboSeverity = JComboBox( ["Critical", "High", "Medium", "Low", "Info"]) self.labelHost.text = "Host" self.labelPath.text = "Path" self.textHost.text = "Issue Host" self.textPath.text = "Issue Path" from java.lang import Short # description panel panelDescriptionLayout = GroupLayout(self.panelDescription) self.panelDescription.setLayout(panelDescriptionLayout) panelDescriptionLayout.setHorizontalGroup( panelDescriptionLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 948, Short.MAX_VALUE)) panelDescriptionLayout.setVerticalGroup( panelDescriptionLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 287, Short.MAX_VALUE)) self.tabIssue.addTab("Description", self.panelDescription) # request tab panelRequestLayout = GroupLayout(self.panelRequest) self.panelRequest.setLayout(panelRequestLayout) panelRequestLayout.setHorizontalGroup( panelRequestLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 948, Short.MAX_VALUE)) panelRequestLayout.setVerticalGroup( panelRequestLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 287, Short.MAX_VALUE)) self.tabIssue.addTab("Request", self.panelRequest) # response tab panelResponseLayout = GroupLayout(self.panelResponse) self.panelResponse.setLayout(panelResponseLayout) panelResponseLayout.setHorizontalGroup( panelResponseLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 948, Short.MAX_VALUE)) panelResponseLayout.setVerticalGroup( panelResponseLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 287, Short.MAX_VALUE)) self.tabIssue.addTab("Response", self.panelResponse) # remediation tab panelRemediationLayout = GroupLayout(self.panelRemediation) self.panelRemediation.setLayout(panelRemediationLayout) panelRemediationLayout.setHorizontalGroup( panelRemediationLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 948, Short.MAX_VALUE)) panelRemediationLayout.setVerticalGroup( panelRemediationLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGap(0, 287, Short.MAX_VALUE)) self.tabIssue.addTab("Remediation", self.panelRemediation) # jpanel1? jPanel1Layout = GroupLayout(self.jPanel1) self.jPanel1.setLayout(jPanel1Layout) jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING). addGroup(jPanel1Layout.createSequentialGroup().addContainerGap( ).addGroup( jPanel1Layout.createParallelGroup( GroupLayout.Alignment.LEADING). addGroup(jPanel1Layout.createSequentialGroup().addGroup( jPanel1Layout.createParallelGroup( GroupLayout.Alignment.TRAILING).addComponent( self.labelHost).addComponent( self.labelSeverity).addComponent( self.labelName) ).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addGroup( jPanel1Layout.createParallelGroup( GroupLayout.Alignment.LEADING). addComponent(self.textName).addGroup( jPanel1Layout.createSequentialGroup().addComponent( self.comboSeverity, GroupLayout.PREFERRED_SIZE, 98, GroupLayout.PREFERRED_SIZE).addGap( 0, 0, Short.MAX_VALUE)). addGroup( jPanel1Layout.createSequentialGroup().addComponent( self.textHost, GroupLayout.PREFERRED_SIZE, 330, GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18). addComponent(self.labelPath).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(self.textPath)))).addComponent( self.tabIssue)).addContainerGap())) jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING). addGroup(jPanel1Layout.createSequentialGroup().addContainerGap( ).addGroup( jPanel1Layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.labelName).addComponent( self.textName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( jPanel1Layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.labelSeverity).addComponent( self.comboSeverity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( jPanel1Layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.labelHost).addComponent( self.labelPath).addComponent( self.textHost, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.textPath, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)). addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( self.tabIssue).addContainerGap())) # create the main panel self.panel = JPanel() layout = GroupLayout(self.panel) self.panel.setLayout(layout) layout.setAutoCreateGaps(True) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addContainerGap().addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( self.jScrollPane1)).addContainerGap())) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addContainerGap().addComponent( self.jScrollPane1, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE).addGap( 18, 18, 18).addComponent(self.jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap()))
class EmployeeDetails(JPanel): def __init__(self, employees, dateprovider): JPanel.__init__(self, preferredSize=(400, 200)) layout = BoxLayout(self, BoxLayout.Y_AXIS) self.setLayout(layout) self._employees = employees self._dateprovider = dateprovider employees.add_change_listener(self) self._create_status_label() self._create_name_editor() self._create_start_date_editor() self._create_save_button() self._create_vacation_display() self._adding_employee = False def _create_status_label(self): self._status_label = JLabel(name='status_label', font=Font(Font.SANS_SERIF, Font.PLAIN, 11)) self.add(self._status_label) self._add_with_padding(self._status_label, 5) def _create_name_editor(self): self.add(JLabel(text='Employee Name:')) self._name_editor = FixedHeightTextField('name_input') self._add_with_padding(self._name_editor, 5) def _create_start_date_editor(self): self.add(JLabel(text='Start Date (yyyy-mm-dd):')) self._start_date_editor = FixedHeightTextField('start_input') self._add_with_padding(self._start_date_editor, 5) def _create_save_button(self): self._save_button = JButton('Save', name='save_button', visible=False) self._save_button.addActionListener( ListenerFactory(ActionListener, self._save_button_pushed)) self._add_with_padding(self._save_button, 5) def _create_vacation_display(self): self._display = JTable(name='vacation_display') self._header = self._display.getTableHeader() self.add(self._header) self.add(self._display) def _add_with_padding(self, component, padding): self.add(component) self.add(Box.createRigidArea(Dimension(0, padding))) def show_employee(self, employee): self._name_editor.setText(employee.name) self._start_date_editor.setText(str(employee.startdate)) self._name_editor.setEditable(False) self._start_date_editor.setEditable(False) self._save_button.setVisible(False) if self._adding_employee: self._adding_employee = False else: self._status_label.setText('') self._display.setVisible(True) self._display.setModel(VacationTableModel(employee, self._dateprovider)) self._header.setVisible(True) def edit_new_employee(self): self._name_editor.setText('') self._start_date_editor.setText('') self._name_editor.setEditable(True) self._start_date_editor.setEditable(True) self._save_button.setVisible(True) self._display.setVisible(False) self._header.setVisible(False) self._adding_employee = True def _save_button_pushed(self, event): self._employees.add(self._name_editor.getText(), self._start_date_editor.getText()) def employee_added(self, employee): self._status_label.setForeground(Color.BLACK) self._status_label.setText("Employee '%s' was added successfully." % employee.name) self._save_button.setVisible(False) def adding_employee_failed(self, reason): self._status_label.setForeground(Color.RED) self._status_label.setText(reason)
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 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)