Beispiel #1
0
    def __init__(self, cattr):
	self.attr = cattr
	self.cbox = JColorChooser(self.attr.color)
	self.sym_panel = EditSymbolAttr(cattr.sym_prop)
	self.thickness_field = JTextField(str(cattr.thickness),2)
	self.draw_symbol_box = JCheckBox("Draw Symbol?",cattr.draw_symbol)
	self.dps_field = JTextField(str(self.attr.data_per_symbol),2)
	self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys())
	self.dash_box.setSelectedItem(self.attr.dash_type)
	self.dash_box.setBorder(BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)"))
	tpanelx = JPanel()
	tpanelx.add(self.thickness_field)
	tpanelx.setBorder(BorderFactory.createTitledBorder("curve thickness (integer)"))
	tpanely = JPanel()
	tpanely.add(self.dps_field)
	tpanely.setBorder(BorderFactory.createTitledBorder("data per symbol(integer)"))
	tpanel = JPanel();tpanel.setLayout(GridLayout(2,2));
	tpanel.add(self.draw_symbol_box); tpanel.add(tpanelx);
	tpanel.add(tpanely); tpanel.add(self.dash_box);
	panel1 = JPanel()
	panel1.setLayout(BorderLayout())
	panel1.add(self.cbox,BorderLayout.CENTER)
	panel1.add(tpanel, BorderLayout.SOUTH)
	panel2 = JPanel()
	panel2.setLayout(BorderLayout())
	panel2.add(self.sym_panel,BorderLayout.CENTER)
	tp1 = JTabbedPane()
	tp1.addTab("Curve Attributes",panel1)
	tp1.addTab("Symbol Attributes",panel2)
	tp1.setSelectedComponent(panel1)
	self.setLayout(BorderLayout())
	self.add(tp1,BorderLayout.CENTER)
Beispiel #2
0
    def helpMenu(self,event):
        self._helpPopup = JFrame('JWT Fuzzer', size=(550, 450) );
        self._helpPopup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        helpPanel = JPanel()
        helpPanel.setPreferredSize(Dimension(550, 450))
        helpPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        self._helpPopup.setContentPane(helpPanel)
        helpHeadingText = JLabel("<html><h2>JWT Fuzzer</h2></html>")
        authorText = JLabel("<html><p>@author: &lt;pinnace&gt;</p></html>")
        aboutText = JLabel("<html><br /> <p>This extension adds an Intruder payload processor for JWTs.</p><br /></html>")
        repositoryText = JLabel("<html>Documentation and source code:</html>")
        repositoryLink = JLabel("<html>- <a href=\"https://github.com/pinnace/burp-jwt-fuzzhelper-extension\">https://github.com/pinnace/burp-jwt-fuzzhelper-extension</a></html>")
        licenseText = JLabel("<html><br/><p>JWT Fuzzer uses a GPL 3 license. This license does not apply to the dependency below:<p></html>") 
        dependencyLink = JLabel("<html>- <a href=\"https://github.com/jpadilla/pyjwt/blob/master/LICENSE\">pyjwt</a></html>")
        dependencyLink.addMouseListener(ClickListener())
        dependencyLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        repositoryLink.addMouseListener(ClickListener())
        repositoryLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        
        helpPanel.add(helpHeadingText)
        helpPanel.add(authorText)
        helpPanel.add(aboutText)
        helpPanel.add(repositoryText)
        helpPanel.add(repositoryLink)
        helpPanel.add(licenseText)
        helpPanel.add(dependencyLink)

        self._helpPopup.setSize(Dimension(550, 450))
        self._helpPopup.pack()
        self._helpPopup.setLocationRelativeTo(None)
        self._helpPopup.setVisible(True)
        return
    def createEditorComponent(self, properties):
        p = JPanel(GridBagLayout())
        p.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3))

        gbc = GridBagConstraints()
        gbc.gridx = 0
        gbc.gridy = 0
        gbc.weightx = 0.0
        gbc.weighty = 0.0
        gbc.fill = GridBagConstraints.HORIZONTAL
        gbc.insets = Insets(3, 3, 3, 3)

        p.add(JLabel("Prompt:"), gbc)
        gbc.gridx = 1
        editor = NodePropertiesDialog.createTextArea(properties, self.PROMPT)
        p.add(editor, gbc)

        gbc.gridx, gbc.gridy = 1, 0
        p.add(
            NodePropertiesDialog.createCheckBox(properties, self.WAIT,
                                                "Wait until done"), gbc)

        jtp = JTabbedPane()
        jtp.addTab("Output", p)
        return jtp
Beispiel #4
0
    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)
Beispiel #5
0
    def createButtonPane(self):
        """Create a new button pane for the message editor tab"""
        self._button_listener = EditorButtonListener(self)

        panel = JPanel()
        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
        panel.setBorder(EmptyBorder(5, 5, 5, 5))

        panel.add(Box.createRigidArea(Dimension(0, 5)))
        type_scroll_pane = JScrollPane(self._type_list_component)
        type_scroll_pane.setMaximumSize(Dimension(200, 100))
        type_scroll_pane.setMinimumSize(Dimension(150, 100))
        panel.add(type_scroll_pane)
        panel.add(Box.createRigidArea(Dimension(0, 3)))

        new_type_panel = JPanel()
        new_type_panel.setLayout(BoxLayout(new_type_panel, BoxLayout.X_AXIS))
        new_type_panel.add(self._new_type_field)
        new_type_panel.add(Box.createRigidArea(Dimension(3, 0)))
        new_type_panel.add(
            self.createButton(
                "New", "new-type", "Save this message's type under a new name"
            )
        )
        new_type_panel.setMaximumSize(Dimension(200, 20))
        new_type_panel.setMinimumSize(Dimension(150, 20))

        panel.add(new_type_panel)

        button_panel = JPanel()
        button_panel.setLayout(FlowLayout())
        if self._editable:
            button_panel.add(
                self.createButton(
                    "Validate", "validate", "Validate the message can be encoded."
                )
            )
        button_panel.add(
            self.createButton("Edit Type", "edit-type", "Edit the message type")
        )
        button_panel.add(
            self.createButton(
                "Reset Message", "reset", "Reset the message and undo changes"
            )
        )
        button_panel.add(
            self.createButton(
                "Clear Type", "clear-type", "Reparse the message with an empty type"
            )
        )
        button_panel.setMinimumSize(Dimension(100, 200))
        button_panel.setPreferredSize(Dimension(200, 1000))

        panel.add(button_panel)

        return panel
Beispiel #6
0
def makeUI(model):
    # Components:
    table = JTable(model)
    jsp = JScrollPane(table)
    regex_label = JLabel("Search: ")
    regex_field = JTextField(20)
    base_path_label = JLabel("Base path:")
    base_path_field = JTextField(50)
    if base_path is not None:
        base_path_field.setText(base_path)
    # Panel for all components
    all = JPanel()
    all.setBorder(EmptyBorder(20, 20, 20, 20))
    layout, c = GridBagLayout(), GC()
    all.setLayout(layout)
    # First row: label and regex text field
    add(all, regex_label, gridx=0, gridy=0)  # with default constraints
    add(all, regex_field, gridx=1, gridy=0, fill=GC.HORIZONTAL, weightx=1.0)
    # Second row: the table
    add(all,
        jsp,
        gridx=0,
        gridy=1,
        fill=GC.BOTH,
        gridwidth=2,
        weightx=1.0,
        weighty=1.0)  # full weights so it stretches when resizing
    # Third row: the base path
    add(all, base_path_label, gridx=0, gridy=2)
    add(all,
        base_path_field,
        gridx=1,
        gridy=2,
        fill=GC.HORIZONTAL,
        weightx=1.0)
    # Window frame
    frame = JFrame("File paths")
    frame.getContentPane().add(all)
    #frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.addWindowListener(Closing())
    frame.pack()
    frame.setVisible(True)
    # Listeners
    regex_field.addKeyListener(EnterListener(table))
    table.addMouseListener(RowClickListener(base_path_field))
    al = ArrowListener(table, regex_field)
    table.addKeyListener(al)
    regex_field.addKeyListener(al)
    # Instead of a KeyListener, use the input vs action map
    table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                            "enter")
    table.getActionMap().put("enter", OpenImageFromTableCell())
    #
    return model, table, regex_field, frame
Beispiel #7
0
    def createPanel(scroll=False, ptop=0, pleft=0, pbottom=0, pright=0):
        panel = JPanel()
        panel.setLayout(BoxLayout(panel, BoxLayout.PAGE_AXIS))
        panel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel.setBorder(EmptyBorder(ptop, pleft, pbottom, pright))

        # if scroll:
        # scrollpane = JScrollPane(panel)
        # scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        # scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER)
        # return JPanel().add(scrollpane)

        return panel
class LowHangingFruitUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()

    def initComponents(self):
        self.panel = JPanel()
        self.panel.setLayout(BorderLayout())

        toolbar = JToolBar()
        openb = JButton("Select", actionPerformed=self.onClick)

        toolbar.add(openb)

        self.area = JTextArea()
        self.area.setBorder(BorderFactory.createEmptyBorder(10, 100, 10, 100))

        pane = JScrollPane()
        pane.getViewport().add(self.area)

        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
        self.panel.add(pane)
        self.add(self.panel)

        self.add(toolbar)

    def onClick(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("SQLite", ["sqlite"])
        chooseFile.addChoosableFileFilter(filter)

        ret = chooseFile.showDialog(self.panel, "Select SQLite")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            text = self.readPath(file)
            self.area.setText(text)

    def readPath(self, file):
        global filename
        filename = file.getCanonicalPath()
        return filename

    def getSettings(self):
        return self.local_settings
    def editRegex(self, event):
        selectedRowIdx = self.regexTable.getSelectedRow()
        if selectedRowIdx == -1: return False
        selectedRow = self.regexTableModel.data[selectedRowIdx]

        optionPane = JOptionPane()
        dialog = optionPane.createDialog(self._splitpane, "Edit RegEx")

        panel = JPanel(GridLayout(0, 2))
        panel.setBorder(EmptyBorder(10, 10, 10, 10))

        nameField = JTextField('', 15)
        nameField.text = selectedRow[0]
        panel.add(JLabel("Name:", SwingConstants.LEFT))
        panel.add(nameField)

        regexField = JTextField('', 15)
        regexField.text = selectedRow[1]
        panel.add(JLabel("RegEx:", SwingConstants.LEFT))
        panel.add(regexField)

        crawlField = JCheckBox()
        crawlField.setSelected(selectedRow[2])
        panel.add(JLabel("Crawl:", SwingConstants.LEFT))
        panel.add(crawlField)

        def closeDialog(event):
            if len(nameField.text) == 0 or len(regexField.text) == 0:
                JOptionPane.showMessageDialog(self._splitpane,
                                              "Name or RegEx can't be empty",
                                              "Error",
                                              JOptionPane.ERROR_MESSAGE)
                return
            self.regexTableModel.editRow(
                selectedRowIdx,
                [nameField.text, regexField.text,
                 crawlField.isSelected()])
            dialog.hide()

        editButton = JButton('OK', actionPerformed=closeDialog)
        panel.add(editButton)

        dialog.setSize(600, 200)
        dialog.setContentPane(panel)
        self._callbacks.customizeUiComponent(dialog)
        dialog.show()
        return True
Beispiel #10
0
def createParametersPanel(manager):
    global systemPanel, menuHandles, isTemporal
    systemPanel = SystemPanel(changeChartCI, isTemporal)
    global summPanel
    summPanel = SummPanel(isTemporal)
    global empiricalPanel, isDominant
    empiricalPanel = EmpiricalPanel(menuHandles, manager, isDominant,
            systemPanel, isTemporal)
    global simsDonePanel
    simsDonePanel = Meter(300, 120, 10)
    panel = JPanel()
    panel.setBorder(LineBorder(Color.GREEN))
    panel.add(systemPanel)
    panel.add(empiricalPanel)
    panel.add(summPanel)
    panel.add(simsDonePanel)
    return panel
Beispiel #11
0
class MatchMetaInfoUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()

    def initComponents(self):
        self.panel = JPanel()
        self.panel.setLayout(BorderLayout())

        toolbar = JToolBar()
        openb = JButton("Select", actionPerformed=self.onClick)

        toolbar.add(openb)

        self.area = JTextArea()
        self.area.setBorder(BorderFactory.createEmptyBorder(10, 100, 10, 100))

        pane = JScrollPane()
        pane.getViewport().add(self.area)

        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
        self.panel.add(pane)
        self.add(self.panel)

        self.add(toolbar)

    def onClick(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("SQLite", ["sqlite"])
        chooseFile.addChoosableFileFilter(filter)

        ret = chooseFile.showDialog(self.panel, "Select SQLite")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            text = self.readPath(file)
            self.area.setText(text)

    def readPath(self, file):
        global filename
        filename = file.getCanonicalPath()
        return filename

    def getSettings(self):
        return self.local_settings
Beispiel #12
0
 def __fillQuestions(self):
   panel = JPanel()
   panel.setLayout(GridBagLayout())
   panel.setBorder(None)
   c = GridBagConstraints()
   c.gridx = 0
   c.gridy = 0
   c.weightx = 1.0
   c.fill = GridBagConstraints.HORIZONTAL
   c.anchor = GridBagConstraints.PAGE_START
   line = 0
   for question in self.test.getQuestions():
     c.gridy = line
     panel.add(question.getPanel().asJComponent(),c)
     line += 1
   scrollPanel = JScrollPane(panel)
   scrollPanel.setBorder(None)
   self.questionsContainer.setLayout(BorderLayout())
   self.questionsContainer.add(scrollPanel, BorderLayout.CENTER)
    def build_gui(self):
        """Construct GUI elements."""
        panel = JPanel(BorderLayout(3, 3))
        panel.setBorder(EmptyBorder(160, 160, 160, 160))

        self.aws_access_key_inpt = JTextField(10)
        self.aws_secret_key_inpt = JTextField(10)
        self.aws_session_token_inpt = JTextField(10)
        self.gs_access_key_inpt = JTextField(10)
        self.gs_secret_key_inpt = JTextField(10)
        self.wordlist_path_inpt = JTextField(10)
        self.passive_mode = JCheckBox('Enabled')
        self.ssl_verification = JCheckBox('Enabled')

        save_btn = JButton('Save', actionPerformed=self.save_config)

        labels = JPanel(GridLayout(0, 1))
        inputs = JPanel(GridLayout(0, 1))
        panel.add(labels, BorderLayout.WEST)
        panel.add(inputs, BorderLayout.CENTER)

        top_label = JLabel('<html><b>Settings</b><br><br></html>')
        top_label.setHorizontalAlignment(JLabel.CENTER)
        panel.add(top_label, BorderLayout.NORTH)
        labels.add(JLabel('AWS Access Key:'))
        inputs.add(self.aws_access_key_inpt)
        labels.add(JLabel('AWS Secret Key:'))
        inputs.add(self.aws_secret_key_inpt)
        labels.add(JLabel('AWS Session Key (optional):'))
        inputs.add(self.aws_session_token_inpt)
        labels.add(JLabel('GS Access Key:'))
        inputs.add(self.gs_access_key_inpt)
        labels.add(JLabel('GS Secret Key:'))
        inputs.add(self.gs_secret_key_inpt)
        labels.add(JLabel('Wordlist Filepath (optional):'))
        inputs.add(self.wordlist_path_inpt)
        labels.add(JLabel('Passive Mode:'))
        inputs.add(self.passive_mode)
        labels.add(JLabel('SSL Verification:'))
        inputs.add(self.ssl_verification)
        panel.add(save_btn, BorderLayout.SOUTH)
        return panel
Beispiel #14
0
def show_gui():
    """
    Shows a GUI to select dss files to compare and select an input file
    """
    from javax.swing import JPanel, JFrame, JButton, SpringLayout, JTextBox
    from javax.swing.border import LineBorder
    textBox1 = JTextBox()
    textBox2 = JTextBox()
    file1ChooseButton = JButton("Choose File")
    file2ChooseButton = JButton("Choose File")
    contentPane = JPanel(SpringLayout())
    contentPane.setBorder(LineBorder(Color.blue))
    contentPane.add(JLabel("Alternative DSS File"))
    contentPane.add(textBox1)
    contentPane.add(file1ChooseButton)
    contentPane.add(JLabel("Base DSS File"))
    contentPane.add(textBox2)
    contentPane.add(file2ChooseButton)
    fr = JFrame("Calsim Report Generator")
    fr.contentPane().add(contentPane)
    fr.pack();fr.show();
Beispiel #15
0
class MainFrame(JFrame):

    def __init__(self):
        super(MainFrame, self).__init__()
        self.initUI()

    def initUI(self):
        if utils.isMac():
			self.setMinimumSize(Dimension(750, 600))
        else:
			self.setMinimumSize(Dimension(750, 700))
        self.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.setLocationRelativeTo(None)

        self.setBounds(100, 100, WINDOW_WIDTH, 600);
        self.content_pane = JPanel();
        self.content_pane.setBorder(EmptyBorder(0, 0, 0, 0));
        self.setContentPane(self.content_pane);
        self.content_pane.setLayout(BorderLayout(0, 0));

        self.setVisible(True)
Beispiel #16
0
def show_gui():
    """
    Shows a GUI to select dss files to compare and select an input file
    """
    from javax.swing import JPanel, JFrame, JButton, SpringLayout, JTextBox
    from javax.swing.border import LineBorder
    textBox1 = JTextBox()
    textBox2 = JTextBox()
    file1ChooseButton = JButton("Choose File")
    file2ChooseButton = JButton("Choose File")
    contentPane = JPanel(SpringLayout())
    contentPane.setBorder(LineBorder(Color.blue))
    contentPane.add(JLabel("Alternative DSS File"))
    contentPane.add(textBox1)
    contentPane.add(file1ChooseButton)
    contentPane.add(JLabel("Base DSS File"))
    contentPane.add(textBox2)
    contentPane.add(file2ChooseButton)
    fr = JFrame("Calsim Report Generator")
    fr.contentPane().add(contentPane)
    fr.pack();fr.show();
Beispiel #17
0
    def __init__(self, sattr):
	self.attr = sattr
	self.cbox = JColorChooser(self.attr.color)
	self.sz_field = JTextField(str(self.attr.size))
	szpanel = JPanel()
	szpanel.add(self.sz_field)
	szpanel.setBorder(BorderFactory.createTitledBorder("symbol size (integer)"))
	self.filled_box = JCheckBox("Filled ?:",self.attr.filled)
	self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys())
	self.shape_cbox.setSelectedItem(self.attr.shape)
	self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape"))
	panel1 = JPanel()
	panel1.setLayout(BorderLayout())
	panel1.add(szpanel,BorderLayout.NORTH)
	panel2 = JPanel()
	panel2.setLayout(GridLayout(1,2))
	panel2.add(self.shape_cbox)
	panel2.add(self.filled_box)
	panel1.add(panel2,BorderLayout.SOUTH)
	self.setLayout(BorderLayout())
	self.add(self.cbox,BorderLayout.CENTER)
	self.add(panel1,BorderLayout.SOUTH)
Beispiel #18
0
 def __init__(self, cattr):
     self.attr = cattr
     self.cbox = JColorChooser(self.attr.color)
     self.sym_panel = EditSymbolAttr(cattr.sym_prop)
     self.thickness_field = JTextField(str(cattr.thickness), 2)
     self.draw_symbol_box = JCheckBox("Draw Symbol?", cattr.draw_symbol)
     self.dps_field = JTextField(str(self.attr.data_per_symbol), 2)
     self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys())
     self.dash_box.setSelectedItem(self.attr.dash_type)
     self.dash_box.setBorder(
         BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)"))
     tpanelx = JPanel()
     tpanelx.add(self.thickness_field)
     tpanelx.setBorder(
         BorderFactory.createTitledBorder("curve thickness (integer)"))
     tpanely = JPanel()
     tpanely.add(self.dps_field)
     tpanely.setBorder(
         BorderFactory.createTitledBorder("data per symbol(integer)"))
     tpanel = JPanel()
     tpanel.setLayout(GridLayout(2, 2))
     tpanel.add(self.draw_symbol_box)
     tpanel.add(tpanelx)
     tpanel.add(tpanely)
     tpanel.add(self.dash_box)
     panel1 = JPanel()
     panel1.setLayout(BorderLayout())
     panel1.add(self.cbox, BorderLayout.CENTER)
     panel1.add(tpanel, BorderLayout.SOUTH)
     panel2 = JPanel()
     panel2.setLayout(BorderLayout())
     panel2.add(self.sym_panel, BorderLayout.CENTER)
     tp1 = JTabbedPane()
     tp1.addTab("Curve Attributes", panel1)
     tp1.addTab("Symbol Attributes", panel2)
     tp1.setSelectedComponent(panel1)
     self.setLayout(BorderLayout())
     self.add(tp1, BorderLayout.CENTER)
Beispiel #19
0
    def onExit(self, e):
        exit = JFrame()
        exit.setTitle("Exit Stylus")
        exit.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        exit.setSize(250, 225)
        exit.setLocationRelativeTo(None)
        exit.setVisible(True)
        exit.setResizable(False)

        panel = JPanel()
        panel.setBorder(BorderFactory.createEtchedBorder())
        panel.setLayout(GridLayout(0, 1))
        exit.getContentPane().add(panel)

        icon1 = ImageIcon("/icons/shutdown.png")
        poweroff = JButton("Shutdown", icon1, actionPerformed=self.shutdown)
        panel.add(poweroff)

        icon2 = ImageIcon("/icons/reboot.png")
        reboot = JButton("  Reboot    ", icon2, actionPerformed=self.reboot)
        panel.add(reboot)

        exit.add(panel)
Beispiel #20
0
 def __init__(self, sattr):
     self.attr = sattr
     self.cbox = JColorChooser(self.attr.color)
     self.sz_field = JTextField(str(self.attr.size))
     szpanel = JPanel()
     szpanel.add(self.sz_field)
     szpanel.setBorder(
         BorderFactory.createTitledBorder("symbol size (integer)"))
     self.filled_box = JCheckBox("Filled ?:", self.attr.filled)
     self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys())
     self.shape_cbox.setSelectedItem(self.attr.shape)
     self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape"))
     panel1 = JPanel()
     panel1.setLayout(BorderLayout())
     panel1.add(szpanel, BorderLayout.NORTH)
     panel2 = JPanel()
     panel2.setLayout(GridLayout(1, 2))
     panel2.add(self.shape_cbox)
     panel2.add(self.filled_box)
     panel1.add(panel2, BorderLayout.SOUTH)
     self.setLayout(BorderLayout())
     self.add(self.cbox, BorderLayout.CENTER)
     self.add(panel1, BorderLayout.SOUTH)
Beispiel #21
0
class HL7GUIFrame(JFrame):
   outputTextField = None


   def __init__(self):
       super(HL7GUIFrame, self).__init__()

       self.initUI()

   def initUI(self):

       global outputTextField
       self.panel = JPanel()
       self.panel.setLayout(BorderLayout())

       toolbar = JToolBar()
       openb = JButton("Choose input file", actionPerformed=self.onClick)
       outputLabel = JLabel("   Enter output file name:  ")
       outputTextField = JTextField("hl7OutputReport.txt", 5)
       print outputTextField.getText()


     


       toolbar.add(openb)
       toolbar.add(outputLabel)
       toolbar.add(outputTextField)
      

       self.area = JTextArea()
       self.area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
       self.area.setText("Select your HL7 ORU messages text file to be converted to tab-delimited flat \nfile with select HL7 fields.\n")
       self.area.append("You can enter the path + file name for your output file or it will default to the current \nfile name in the text field above in your current working directory.")

       pane = JScrollPane()
       pane.getViewport().add(self.area)

       self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
       self.panel.add(pane)
       self.add(self.panel)

       self.add(toolbar, BorderLayout.NORTH)


       self.setTitle("HL7 ORU Results Reporter")
       self.setSize(600, 300)
       self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
       self.setLocationRelativeTo(None)
       self.setVisible(True)
       return outputTextField.getText()


   def onClick(self, e):

       print outputTextField.getText()
       chooseFile = JFileChooser()
       filter = ExampleFileFilter()
       filter.addExtension("txt")
       filter.setDescription("txt HL7 input files")
       chooseFile.setFileFilter(filter)
       

       ##ret = chooseFile.showDialog(self.panel, "Choose file")
       ret = chooseFile.showOpenDialog(self.panel)

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           text = self.readFile(file)
           self.area.append(text)
           outputFile = outputTextField.getText()
           p1 = HL7RepClass.ParseORUClass(file.getCanonicalPath(), outputFile)
           p1.parseORU()
           print "\noutfile = ", outputFile

   def readFile(self, file):
       filename = file.getCanonicalPath()
       print "filename is now ", filename
       f = open(filename, "r")
       
       text = f.read()
     
       return text
class BurpExtender(IBurpExtender, ITab, IHttpListener):
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("burp-sensitive-param-extractor")
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        callbacks.registerHttpListener(self)
        #callbacks.registerMessageEditorTabFactory(self)
        print 'burp-sensitive-param-extractor loaded.\nAuthor:LSA\nhttps://github.com/theLSA/burp-sensitive-param-extractor'

        self.sensitiveParamR = getParamRegular()

        self._callbacks.customizeUiComponent(self.getUiComponent())
        self._callbacks.addSuiteTab(self)
        #self.endColors = []
        self.requestParamDict = {}
        self.resultSensitiveParamsDict = {}

    def getTabCaption(self):
        return 'BSPE'

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):

        if messageIsRequest and toolFlag == 4:
            self.requestParamDict['urlParams'] = []
            self.requestParamDict['BodyParams'] = []
            self.requestParamDict['cookieParams'] = []
            self.requestParamDict['jsonParams'] = []

            cookieParamFlag = 0

            service = messageInfo.getHttpService()
            request = messageInfo.getRequest()
            analyzeReq = self._helpers.analyzeRequest(service, request)
            reqUrl = self._helpers.analyzeRequest(messageInfo).getUrl()
            reqMethod = self._helpers.analyzeRequest(messageInfo).getMethod()

            reqParams = analyzeReq.getParameters()

            for param in reqParams:
                paramType = param.getType()

                if paramType == 0:
                    #self.outputTxtArea.append("\nurlParams-")

                    paramName = param.getName()
                    paramValue = param.getValue()
                    print 'urlParams:'
                    print paramName + ':' + paramValue
                    #self.outputTxtArea.append("[%s]" % paramName)
                    self.requestParamDict['urlParams'].append(
                        paramName.strip())

                if paramType == 1:
                    #self.outputTxtArea.append("\nBodyParams-")

                    paramName = param.getName()
                    paramValue = param.getValue()
                    print 'BodyParams:'
                    print paramName + ':' + paramValue
                    #self.outputTxtArea.append("[%s]\n" % paramName)
                    self.requestParamDict['BodyParams'].append(
                        paramName.strip())

                if paramType == 2:
                    #self.outputTxtArea.append("\ncookieParams-")

                    paramName = param.getName()
                    paramValue = param.getValue()
                    print 'CookieParams:'
                    print paramName + ':' + paramValue
                    #self.outputTxtArea.append("[%s]\n" % paramName)
                    self.requestParamDict['cookieParams'].append(
                        paramName.strip())
                    cookieParamFlag = 1

                if paramType == 6:
                    #self.outputTxtArea.append("\njsonParams-")

                    paramName = param.getName()
                    paramValue = param.getValue()
                    print 'JsonParams:'
                    print paramName + ':' + paramValue
                    #self.outputTxtArea.append("[%s]\n" % paramName)
                    self.requestParamDict['jsonParams'].append(
                        paramName.strip())

            self.resultSensitiveParamsDict = self.findSensitiveParam(
                self.requestParamDict)
            #print self.resultSensitiveParamsDict

            for rspdKey in self.resultSensitiveParamsDict.keys():
                if self.resultSensitiveParamsDict[rspdKey] != []:
                    print "[%s][%s]" % (reqMethod, reqUrl)
                    self.outputTxtArea.append(
                        "\n------------------------------------------------------\n"
                    )
                    self.outputTxtArea.append("[%s][%s]\n" %
                                              (reqMethod, reqUrl))
                    break

            for rspdKey in self.resultSensitiveParamsDict.keys():
                if self.resultSensitiveParamsDict[rspdKey] != []:
                    self.outputTxtArea.append(
                        "\n" + rspdKey + "--" +
                        str(self.resultSensitiveParamsDict[rspdKey]))

            self.write2file()

            #pass

        else:
            return

    def findSensitiveParam(self, requestParamDict):
        #sensitiveParamR = getParamRegular()
        resultSensitiveParamsDict = {}
        resultSensitiveParamsDict['urlParams'] = []

        resultSensitiveParamsDict['BodyParams'] = []

        resultSensitiveParamsDict['cookieParams'] = []

        resultSensitiveParamsDict['jsonParams'] = []

        #print requestParamDict

        for spr in self.sensitiveParamR:
            for key in requestParamDict.keys():
                for reqParam in requestParamDict[key]:
                    if len(spr) == 1:
                        if spr == reqParam.lower():
                            resultSensitiveParamsDict[key].append(reqParam)
                    else:
                        if spr in reqParam.lower():
                            print spr + ' in ' + reqParam
                            resultSensitiveParamsDict[key].append(reqParam)
        #print resultSensitiveParamsDict
        for key in resultSensitiveParamsDict.keys():
            resultSensitiveParamsDict[key] = {}.fromkeys(
                resultSensitiveParamsDict[key]).keys()
            #resultSensitiveParamsDict[key] = sorted(resultSensitiveParamsDict[key],key=resultSensitiveParamsDict[key].index)
        #print resultSensitiveParamsDict
        return resultSensitiveParamsDict

    def write2file(self):
        sensitiveParamsList = getSensitiveParamsFromFile()
        newSensitiveParamsList = []
        #print self.resultSensitiveParamsDict
        for rspdKey in self.resultSensitiveParamsDict.keys():
            if (self.resultSensitiveParamsDict[rspdKey] != []) and (set(
                    self.resultSensitiveParamsDict[rspdKey]).issubset(
                        set(sensitiveParamsList)) == False):
                newSensitiveParamsList.extend([
                    newSensitiveParam for newSensitiveParam in
                    self.resultSensitiveParamsDict[rspdKey]
                    if newSensitiveParam not in sensitiveParamsList
                ])
        #print str(newSensitiveParamsList)

        if newSensitiveParamsList != []:
            newSensitiveParamsList = {}.fromkeys(newSensitiveParamsList).keys()

            with open('sensitive-params.txt', 'a') as sps:
                for nsp in newSensitiveParamsList:
                    #print 'writeNewParams:'+nsp
                    sps.write('\n' + nsp)

    def addAndSaveNewParamRegular(self, event):
        NewParamRegular = self.addAndSaveNewParamRegularTextField.getText()
        if NewParamRegular not in self.sensitiveParamR:
            self.sensitiveParamR.append(NewParamRegular)
            with open(paramRegularFile, 'a') as prf:
                prf.write('\n' + NewParamRegular)
            self.alertSaveSuccess.showMessageDialog(self.spePanel,
                                                    "Add and save success!")
        else:
            self.alertSaveSuccess.showMessageDialog(self.tab,
                                                    "paramRegular existed.")

        self.sensitiveParamsRegularListPanel.setListData(self.sensitiveParamR)
        self.sensitiveParamsRegularListPanel.revalidate()

        #self.sensitiveParamR = getParamRegular()

    def delParamRegular(self, event):
        #delParamRegularsIndex = self.sensitiveParamsRegularListPanel.selectedIndex
        #if delParamRegularsIndex >= 0:
        #    print delParamRegularsIndex
        #    print self.sensitiveParamR[delParamRegularsIndex]
        for sprlp in self.sensitiveParamsRegularListPanel.getSelectedValuesList(
        ):
            #print sprlp
            self.sensitiveParamR.remove(sprlp)

        #with open(paramRegularFile,'r') as prf1:
        #    lines = prf1.readlines()

        with open(paramRegularFile, 'w') as prf2:
            #print self.sensitiveParamsRegularListPanel.getSelectedValuesList()
            #for line in lines:
            #    if line.strip() in self.sensitiveParamsRegularListPanel.getSelectedValuesList():
            #        print 'remove:'+line
            #        lines.remove(line)
            #for spr1 in lines:
            #    #print spr1
            #    prf2.write(spr1)
            for spr2i, spr2 in enumerate(self.sensitiveParamR):
                print spr2i
                print spr2
                if spr2i == len(self.sensitiveParamR) - 1:
                    prf2.write(spr2)
                else:
                    prf2.write(spr2 + '\n')

        self.sensitiveParamsRegularListPanel.setListData(self.sensitiveParamR)
        self.sensitiveParamsRegularListPanel.revalidate()

        #self.sensitiveParamR = getParamRegular()

    def clearRst(self, event):
        self.outputTxtArea.setText("")

    def exportRst(self, event):
        chooseFile = JFileChooser()
        ret = chooseFile.showDialog(self.logPane, "Choose file")
        filename = chooseFile.getSelectedFile().getCanonicalPath()
        print "\n" + "Export to : " + filename
        open(filename, 'w', 0).write(self.outputTxtArea.text)

    def getUiComponent(self):
        self.spePanel = JPanel()
        self.spePanel.setBorder(None)
        self.spePanel.setLayout(None)

        self.logPane = JScrollPane()
        self.outputTxtArea = JTextArea()
        self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12))
        self.outputTxtArea.setLineWrap(True)
        self.logPane.setViewportView(self.outputTxtArea)
        self.spePanel.add(self.logPane)

        self.clearBtn = JButton("Clear", actionPerformed=self.clearRst)
        self.exportBtn = JButton("Export", actionPerformed=self.exportRst)
        self.parentFrm = JFileChooser()

        self.spePanel.add(self.clearBtn)
        self.spePanel.add(self.exportBtn)

        self.logPane.setBounds(20, 50, 800, 600)

        self.clearBtn.setBounds(20, 650, 100, 30)
        self.exportBtn.setBounds(600, 650, 100, 30)

        self.sensitiveParamsRegularListPanel = JList(self.sensitiveParamR)
        self.sensitiveParamsRegularListPanel.setVisibleRowCount(
            len(self.sensitiveParamR))

        #self.spePanel.add(self.sensitiveParamsRegularListPanel)

        #self.sensitiveParamsRegularListPanel.setBounds(850,50,150,600)

        self.sensitiveParamsRegularListScrollPanel = JScrollPane()
        self.sensitiveParamsRegularListScrollPanel.setViewportView(
            self.sensitiveParamsRegularListPanel)
        self.spePanel.add(self.sensitiveParamsRegularListScrollPanel)
        self.sensitiveParamsRegularListScrollPanel.setBounds(850, 50, 150, 600)

        self.addAndSaveNewParamRegularButton = JButton(
            'add&&save', actionPerformed=self.addAndSaveNewParamRegular)
        self.spePanel.add(self.addAndSaveNewParamRegularButton)
        self.addAndSaveNewParamRegularButton.setBounds(1000, 50, 150, 30)

        self.addAndSaveNewParamRegularTextField = JTextField('NewParamRegular')
        self.spePanel.add(self.addAndSaveNewParamRegularTextField)
        self.addAndSaveNewParamRegularTextField.setBounds(1150, 50, 100, 30)

        self.alertSaveSuccess = JOptionPane()
        self.spePanel.add(self.alertSaveSuccess)

        self.delParamRegularButton = JButton(
            "delete", actionPerformed=self.delParamRegular)
        self.spePanel.add(self.delParamRegularButton)
        self.delParamRegularButton.setBounds(1000, 90, 100, 30)

        return self.spePanel
Beispiel #23
0
class ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener):
    """ generated source for class ConfigurableConfigPanel """
    serialVersionUID = 1L
    associatedFile = File()
    associatedFileField = JTextField()
    params = JSONObject()
    savedParams = str()
    loadButton = JButton()
    saveAsButton = JButton()
    saveButton = JButton()
    name = JTextField()
    strategy = JComboBox()
    metagameStrategy = JComboBox()
    stateMachine = JComboBox()
    cacheStateMachine = JCheckBox()
    maxPlys = JSpinner()
    heuristicFocus = JSpinner()
    heuristicMobility = JSpinner()
    heuristicOpponentFocus = JSpinner()
    heuristicOpponentMobility = JSpinner()
    mcDecayRate = JSpinner()
    rightPanel = JPanel()

    def __init__(self):
        """ generated source for method __init__ """
        super(ConfigurableConfigPanel, self).__init__(GridBagLayout())
        leftPanel = JPanel(GridBagLayout())
        leftPanel.setBorder(TitledBorder("Major Parameters"))
        self.rightPanel = JPanel(GridBagLayout())
        self.rightPanel.setBorder(TitledBorder("Minor Parameters"))
        self.strategy = JComboBox([None]*)
        self.metagameStrategy = JComboBox([None]*)
        self.stateMachine = JComboBox([None]*)
        self.cacheStateMachine = JCheckBox()
        self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1))
        self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1))
        self.name = JTextField()
        self.name.setColumns(20)
        self.name.setText("Player #" + Random().nextInt(100000))
        self.loadButton = JButton(loadButtonMethod())
        self.saveButton = JButton(saveButtonMethod())
        self.saveAsButton = JButton(saveAsButtonMethod())
        self.associatedFileField = JTextField()
        self.associatedFileField.setEnabled(False)
        buttons = JPanel()
        buttons.add(self.loadButton)
        buttons.add(self.saveButton)
        buttons.add(self.saveAsButton)
        nRow = 0
        leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_0 = nRow
        nRow += 1
        leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_1 = nRow
        nRow += 1
        leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_2 = nRow
        nRow += 1
        leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_3 = nRow
        nRow += 1
        leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        __nRow_4 = nRow
        nRow += 1
        leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0))
        leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0))
        layoutRightPanel()
        add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        self.params = JSONObject()
        syncJSONtoUI()
        self.strategy.addActionListener(self)
        self.metagameStrategy.addActionListener(self)
        self.stateMachine.addActionListener(self)
        self.cacheStateMachine.addActionListener(self)
        self.maxPlys.addChangeListener(self)
        self.heuristicFocus.addChangeListener(self)
        self.heuristicMobility.addChangeListener(self)
        self.heuristicOpponentFocus.addChangeListener(self)
        self.heuristicOpponentMobility.addChangeListener(self)
        self.mcDecayRate.addChangeListener(self)
        self.name.getDocument().addDocumentListener(self)

    def layoutRightPanel(self):
        """ generated source for method layoutRightPanel """
        nRow = 0
        self.rightPanel.removeAll()
        self.rightPanel.add(JLabel("State machine cache?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_5 = nRow
        nRow += 1
        self.rightPanel.add(self.cacheStateMachine, GridBagConstraints(1, __nRow_5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Heuristic":
        __nRow_6 = nRow
        nRow += 1
        __nRow_7 = nRow
        nRow += 1
        __nRow_8 = nRow
        nRow += 1
        __nRow_9 = nRow
        nRow += 1
        __nRow_10 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Max plys?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.maxPlys, GridBagConstraints(1, __nRow_6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicFocus, GridBagConstraints(1, __nRow_7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicMobility, GridBagConstraints(1, __nRow_8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentFocus, GridBagConstraints(1, __nRow_9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentMobility, GridBagConstraints(1, __nRow_10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Monte Carlo":
        __nRow_11 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Goal Decay Rate"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.mcDecayRate, GridBagConstraints(1, __nRow_11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_12 = nRow
        nRow += 1
        self.rightPanel.add(JLabel(), GridBagConstraints(2, __nRow_12, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        self.rightPanel.repaint()

    @SuppressWarnings("unchecked")
    def getParameter(self, name, defaultValue):
        """ generated source for method getParameter """
        try:
            if self.params.has(name):
                return self.params.get(name)
            else:
                return defaultValue
        except JSONException as je:
            return defaultValue

    def actionPerformed(self, arg0):
        """ generated source for method actionPerformed """
        if arg0.getSource() == self.strategy:
            self.layoutRightPanel()
        syncJSONtoUI()

    def changedUpdate(self, e):
        """ generated source for method changedUpdate """
        syncJSONtoUI()

    def insertUpdate(self, e):
        """ generated source for method insertUpdate """
        syncJSONtoUI()

    def removeUpdate(self, e):
        """ generated source for method removeUpdate """
        syncJSONtoUI()

    def stateChanged(self, arg0):
        """ generated source for method stateChanged """
        syncJSONtoUI()

    def syncJSONtoUI(self):
        """ generated source for method syncJSONtoUI """
        if settingUI:
            return
        self.params = getJSONfromUI()
        self.saveButton.setEnabled(self.savedParams == None or not self.params.__str__() == self.savedParams)

    def getJSONfromUI(self):
        """ generated source for method getJSONfromUI """
        newParams = JSONObject()
        try:
            if not self.name.getText().isEmpty():
                newParams.put("name", self.name.getText())
            newParams.put("strategy", self.strategy.getSelectedItem().__str__())
            newParams.put("metagameStrategy", self.metagameStrategy.getSelectedItem().__str__())
            newParams.put("stateMachine", self.stateMachine.getSelectedItem().__str__())
            newParams.put("cacheStateMachine", self.cacheStateMachine.isSelected())
            newParams.put("maxPlys", self.maxPlys.getModel().getValue())
            newParams.put("heuristicFocus", self.heuristicFocus.getModel().getValue())
            newParams.put("heuristicMobility", self.heuristicMobility.getModel().getValue())
            newParams.put("heuristicOpponentFocus", self.heuristicOpponentFocus.getModel().getValue())
            newParams.put("heuristicOpponentMobility", self.heuristicOpponentMobility.getModel().getValue())
            newParams.put("mcDecayRate", self.mcDecayRate.getModel().getValue())
        except JSONException as je:
            je.printStackTrace()
        return newParams

    settingUI = False

    def setUIfromJSON(self):
        """ generated source for method setUIfromJSON """
        self.settingUI = True
        try:
            if self.params.has("name"):
                self.name.setText(self.params.getString("name"))
            if self.params.has("strategy"):
                self.strategy.setSelectedItem(self.params.getString("strategy"))
            if self.params.has("metagameStrategy"):
                self.metagameStrategy.setSelectedItem(self.params.getString("metagameStrategy"))
            if self.params.has("stateMachine"):
                self.stateMachine.setSelectedItem(self.params.getString("stateMachine"))
            if self.params.has("cacheStateMachine"):
                self.cacheStateMachine.setSelected(self.params.getBoolean("cacheStateMachine"))
            if self.params.has("maxPlys"):
                self.maxPlys.getModel().setValue(self.params.getInt("maxPlys"))
            if self.params.has("heuristicFocus"):
                self.heuristicFocus.getModel().setValue(self.params.getInt("heuristicFocus"))
            if self.params.has("heuristicMobility"):
                self.heuristicMobility.getModel().setValue(self.params.getInt("heuristicMobility"))
            if self.params.has("heuristicOpponentFocus"):
                self.heuristicOpponentFocus.getModel().setValue(self.params.getInt("heuristicOpponentFocus"))
            if self.params.has("heuristicOpponentMobility"):
                self.heuristicOpponentMobility.getModel().setValue(self.params.getInt("heuristicOpponentMobility"))
            if self.params.has("mcDecayRate"):
                self.mcDecayRate.getModel().setValue(self.params.getInt("mcDecayRate"))
        except JSONException as je:
            je.printStackTrace()
        finally:
            self.settingUI = False

    def loadParamsJSON(self, fromFile):
        """ generated source for method loadParamsJSON """
        if not fromFile.exists():
            return
        self.associatedFile = fromFile
        self.associatedFileField.setText(self.associatedFile.getPath())
        self.params = JSONObject()
        try:
            try:
                while (line = br.readLine()) != None:
                    pdata.append(line)
            finally:
                br.close()
            self.params = JSONObject(pdata.__str__())
            self.savedParams = self.params.__str__()
            self.setUIfromJSON()
            self.syncJSONtoUI()
        except Exception as e:
            e.printStackTrace()

    def saveParamsJSON(self, saveAs):
        """ generated source for method saveParamsJSON """
        try:
            if saveAs or self.associatedFile == None:
                fc.setFileFilter(PlayerFilter())
                if returnVal == JFileChooser.APPROVE_OPTION and fc.getSelectedFile() != None:
                    if toFile.__name__.contains("."):
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__.substring(0, toFile.__name__.lastIndexOf(".")) + ".player")
                    else:
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__ + ".player")
                    self.associatedFileField.setText(self.associatedFile.getPath())
                else:
                    return
            bw.write(self.params.__str__())
            bw.close()
            self.savedParams = self.params.__str__()
            self.syncJSONtoUI()
        except IOException as ie:
            ie.printStackTrace()

    def saveButtonMethod(self):
        """ generated source for method saveButtonMethod """
        return AbstractAction("Save")

    def saveAsButtonMethod(self):
        """ generated source for method saveAsButtonMethod """
        return AbstractAction("Save As")

    def loadButtonMethod(self):
        """ generated source for method loadButtonMethod """
        return AbstractAction("Load")

    class PlayerFilter(FileFilter):
        """ generated source for class PlayerFilter """
        def accept(self, f):
            """ generated source for method accept """
            if f.isDirectory():
                return True
            return f.__name__.endsWith(".player")

        def getDescription(self):
            """ generated source for method getDescription """
            return "GGP Players (*.player)"
Beispiel #24
0
 def __init__(self):
     """ generated source for method __init__ """
     super(ConfigurableConfigPanel, self).__init__(GridBagLayout())
     leftPanel = JPanel(GridBagLayout())
     leftPanel.setBorder(TitledBorder("Major Parameters"))
     self.rightPanel = JPanel(GridBagLayout())
     self.rightPanel.setBorder(TitledBorder("Minor Parameters"))
     self.strategy = JComboBox([None]*)
     self.metagameStrategy = JComboBox([None]*)
     self.stateMachine = JComboBox([None]*)
     self.cacheStateMachine = JCheckBox()
     self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1))
     self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
     self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
     self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
     self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
     self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1))
     self.name = JTextField()
     self.name.setColumns(20)
     self.name.setText("Player #" + Random().nextInt(100000))
     self.loadButton = JButton(loadButtonMethod())
     self.saveButton = JButton(saveButtonMethod())
     self.saveAsButton = JButton(saveAsButtonMethod())
     self.associatedFileField = JTextField()
     self.associatedFileField.setEnabled(False)
     buttons = JPanel()
     buttons.add(self.loadButton)
     buttons.add(self.saveButton)
     buttons.add(self.saveAsButton)
     nRow = 0
     leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
     __nRow_0 = nRow
     nRow += 1
     leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
     leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
     __nRow_1 = nRow
     nRow += 1
     leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
     leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
     __nRow_2 = nRow
     nRow += 1
     leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
     leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
     __nRow_3 = nRow
     nRow += 1
     leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
     __nRow_4 = nRow
     nRow += 1
     leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0))
     leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0))
     layoutRightPanel()
     add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
     add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
     self.params = JSONObject()
     syncJSONtoUI()
     self.strategy.addActionListener(self)
     self.metagameStrategy.addActionListener(self)
     self.stateMachine.addActionListener(self)
     self.cacheStateMachine.addActionListener(self)
     self.maxPlys.addChangeListener(self)
     self.heuristicFocus.addChangeListener(self)
     self.heuristicMobility.addChangeListener(self)
     self.heuristicOpponentFocus.addChangeListener(self)
     self.heuristicOpponentMobility.addChangeListener(self)
     self.mcDecayRate.addChangeListener(self)
     self.name.getDocument().addDocumentListener(self)
Beispiel #25
0
 def __init__(self):
     '''
     Constructor
     '''
     #Create classifiers
     #Character classifier
     path_to_this_dir = File(str(inspect.getfile( inspect.currentframe() ))).getParent()
     character_classifier_file = open(File(path_to_this_dir,"character_classifier.dat").getPath(),'r')
     self.character_classifier = CharacterClassifier(from_string_string=character_classifier_file.read())
     character_classifier_file.close()
     #Word classifier
     word_classifier_file = open(File(path_to_this_dir,"word_classifier.dat").getPath(),'r')
     self.word_classifier= WordClassifier(from_string_string=word_classifier_file.read())
     word_classifier_file.close()
     #Set up window
     self.setTitle("HandReco Writer")
     self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     self.setLocationRelativeTo(None)
     self.setLayout(BorderLayout())
     #Set up menu
     menu_bar = JMenuBar()
     info_menu = JMenu("Info")
     def instructions(event):
         instr = '''
         The program can just recognise capital English characters.
         See Info -> Available Words... for available word corrections.
         
         Good Luck with the writing!'''
         JOptionPane.showMessageDialog(self, instr, 
                       "Instructions", 
                       JOptionPane.INFORMATION_MESSAGE)
     instructions_menu_item = JMenuItem("Instructions...",actionPerformed=instructions)
     info_menu.add(instructions_menu_item)
     def word_corrections(event):
         words_string = ""
         for word in self.word_classifier.words:
             words_string = words_string + word.upper() + "\n"
         text = "The words that can be corrected are:\n\n" +words_string
         dialog = JOptionPane(text, 
                              JOptionPane.INFORMATION_MESSAGE)
         dialog_wrapper = JDialog(self,"Available Words",False)
         dialog_wrapper.setContentPane(dialog)
         dialog_wrapper.pack()
         dialog_wrapper.setVisible(True)
     word_corrections_menu_item = JMenuItem("Available Words...",actionPerformed=word_corrections)
     info_menu.add(word_corrections_menu_item)
     menu_bar.add(info_menu)
     self.setJMenuBar(menu_bar)
     #Input panel
     input_panel = JPanel()
     input_panel.setLayout(BoxLayout(input_panel, BoxLayout.X_AXIS))
     input_panel.setBorder(BorderFactory.createTitledBorder("Input"))
     self.paint_area = PaintArea(100,100)
     input_panel.add(self.paint_area)
     input_options_panel = JPanel()
     input_options_panel.setLayout(BoxLayout(input_options_panel, BoxLayout.Y_AXIS))
     #Write Char
     write_char_panel = JPanel(BorderLayout())
     def write_char(event):
         char = self.character_classifier.classify_image(self.paint_area.image())
         self.text_area.setText(self.text_area.getText() + char)
         self.paint_area.clear()
     write_char_panel.add(JButton("Write Char", actionPerformed=write_char), BorderLayout.NORTH)
     input_options_panel.add(write_char_panel)
     #Space and Correct
     space_and_correct_panel = JPanel(BorderLayout())
     def space_and_correct(event):
         text = self.text_area.getText()
         words = text.split(" ")
         string = words[-1]
         try:
             word = self.word_classifier.classify(string.lower())
             words[-1] = word.upper()
         except:
             JOptionPane.showMessageDialog(self, "Have you entered a character which is not in the alphabet?", 
                           "Could not Correct", 
                           JOptionPane.ERROR_MESSAGE)
             self.text_area.setText(text + " ")
             return
         newText = ""
         for w in words:
             newText = newText + w + " "
         self.text_area.setText(newText)
     space_and_correct_panel.add(JButton("Space and Correct", actionPerformed=space_and_correct), BorderLayout.NORTH)
     input_options_panel.add(space_and_correct_panel)
     #Space
     space_panel = JPanel(BorderLayout())
     def space(event):
         self.text_area.setText(self.text_area.getText() + " ")
     space_panel.add(JButton("Space", actionPerformed=space), BorderLayout.NORTH)
     input_options_panel.add(space_panel)
     #Clear Input Area
     clear_input_area_panel = JPanel(BorderLayout())
     def clear(event):
         self.paint_area.clear()
     clear_input_area_panel.add(JButton("Clear Input Area", actionPerformed=clear), BorderLayout.NORTH)
     input_options_panel.add(clear_input_area_panel)
     input_panel.add(input_options_panel)
     self.add(input_panel, BorderLayout.NORTH)
     text_area_panel = JPanel()
     text_area_panel.setLayout(BorderLayout())
     text_area_panel.setBorder(BorderFactory.createTitledBorder("Text"))
     self.text_area = JTextArea()
     self.text_area.setLineWrap(True)
     #Increase font size
     font = self.text_area.getFont() 
     self.text_area.setFont(Font(font.getName(), Font.BOLD, 24))
     
     text_area_panel.add(JScrollPane(self.text_area), BorderLayout.CENTER)
     self.add(text_area_panel, BorderLayout.CENTER)
     self.pack()
     self.setSize(Dimension(300,300))
     self.setVisible(True)
Beispiel #26
0
class BobGui(JFrame):
    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        self.dir_path = dc.getDirectory()

        self.choose_dir_textField.setText(self.dir_path)

    def textField_al(self, e):
        self.dir_path = self.choose_dir_textField.getText()

    def run_button_al(self, e):
        print('run button al')
        self.exper = bob_py.Exper(self.dir_path)
        # self.exper.hsegs()[0].nuc_bin().show()
        self.make_tree()

    def make_tree(self):
        root = DefaultMutableTreeNode(self.exper.name)
        for hseg in self.exper.hsegs():
            hseg_node = DefaultMutableTreeNode(hseg.name)
            root.add(hseg_node)
            for file_suf in hseg.file_dict():
                hseg_node.add(DefaultMutableTreeNode(file_suf))
        self.tree = JTree(root)
        scrollPane = JScrollPane()
        scrollPane.getViewport().setView((self.tree))
        # scrollPane.setPreferredSize(Dimension(300,250))

        tree_panel = JPanel()
        tree_panel.add(scrollPane)
        box_layout = BoxLayout(self.panel, BoxLayout.Y_AXIS)
        self.panel.setLayout(box_layout)
        self.panel.add(tree_panel)
        self.revalidate()

    def __init__(self):
        self.dir_path = ''

        self.panel = JPanel()
        box_layout = BoxLayout(self.panel, BoxLayout.Y_AXIS)
        self.panel.setLayout(box_layout)
        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        self.choose_dir_label = JLabel('Experiment Folder:')
        self.choose_dir_textField = JTextField(30)
        self.choose_dir_textField.addActionListener(
            ActionListenerFactory(self, self.textField_al))
        self.choose_dir_button = JButton('open')
        self.choose_dir_button.addActionListener(
            ActionListenerFactory(self, self.choose_dir_al))

        self.choose_dir_panel = JPanel()
        self.choose_dir_panel.add(self.choose_dir_label)
        self.choose_dir_panel.add(self.choose_dir_textField)
        self.choose_dir_panel.add(self.choose_dir_button)

        self.panel.add(self.choose_dir_panel)

        # root = DefaultMutableTreeNode()

        # self.meta_data_mode_label = JLabel('Autogenerated meta_data file mode')
        # self.raw_stack_mode = JRadioButton('raw stack mode')
        # self.projection_mode = JRadioButton('projection files mode')
        #
        # self.meta_data_mode = ButtonGroup()
        # self.meta_data_mode.add(self.raw_stack_mode)
        # self.meta_data_mode.add(self.projection_mode)
        #
        # self.meta_data_mode_panel = JPanel(GridLayout(0, 1))
        # self.meta_data_mode_panel.add(self.meta_data_mode_label)
        # self.meta_data_mode_panel.add(self.raw_stack_mode)
        # self.meta_data_mode_panel.add(self.projection_mode)
        #
        # self.panel.add(self.meta_data_mode_panel)

        self.run_button = JButton('Run')
        self.run_button.addActionListener(
            ActionListenerFactory(self, self.run_button_al))
        self.panel.add(self.run_button)

        super(BobGui, self).__init__("BobPy")
        self.getContentPane().add(self.panel)
        self.pack()
        self.setLocationRelativeTo(None)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setVisible(True)
Beispiel #27
0
class BobGui(JFrame):
    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        self.dir_path = dc.getDirectory()

        self.choose_dir_textField.setText(self.dir_path)
        self.got_exper(self.dir_path)

    def textField_al(self, e):
        self.dir_path = self.choose_dir_textField.getText()
        self.got_exper(self.dir_path)

    def got_exper(self, dir_path):
        self.exper = bob_py.Exper(dir_path)
        self.make_tree()

    def make_tree(self):
        print('make_tree')
        root = DefaultMutableTreeNode(self.exper.name)

        sb = br.SimilarityBuilder()

        for hseg in self.exper.hsegs():
            all_file_dict = hseg.file_dict()
            all_file_dict.update(hseg.cell_file_dict())
            all_file_dict.update(hseg.bin_file_dict())
            sb.add_group(hseg.name, all_file_dict)

        simprofile, comparisons = sb.simprofile_comparison()

        sim_str = ''
        for val in simprofile:
            sim_str += str(val) + '\n'

        tp = JTextArea(sim_str)

        stp = JScrollPane()
        stp.getViewport().setView(tp)
        #
        # stp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        # stp.setPreferredSize(Dimension(250, 250));
        # tp.setPreferredSize(Dimension(250, 250))
        stp_panel = JPanel(BorderLayout())
        stp_panel.add(tp, BorderLayout.CENTER)

        # self.add(stp_panel, 'grow')

        for hseg in self.exper.hsegs():
            hseg_node = DefaultMutableTreeNode(hseg.name)
            root.add(hseg_node)
            if len(comparisons[hseg.name]) > 0:
                for definer, file_names in comparisons[hseg.name].items():
                    for file_name in file_names:
                        node_str = definer + ': ' + file_name
                        hseg_node.add(DefaultMutableTreeNode(node_str))
            # for file_suf in hseg.file_dict() :
            # hseg_node.add(DefaultMutableTreeNode(file_suf))

        self.tree = JTree(root)
        scrollPane = JScrollPane()
        scrollPane.getViewport().setView((self.tree))
        # scrollPan
        # scrollPane.setPreferredSize(Dimension(300,250))

        tree_panel = JPanel(BorderLayout())
        tree_panel.add(scrollPane, BorderLayout.CENTER)

        combo_panel = JPanel(GridLayout(0, 2, 10, 10))
        # combo_panel.setLayout(BoxLayout(combo_panel, BoxLayout.X_AXIS))
        combo_panel.add(stp_panel)  #, BorderLayout.LINE_START)
        combo_panel.add(tree_panel)  #, BorderLayout.LINE_END)
        self.panel.add(combo_panel)
        # self.add(scrollPane, 'grow')
        self.revalidate()

    def __init__(self):
        super(BobGui, self).__init__("BobPy")

        self.dir_path = ''

        # ml = MigLayout('fill')
        # self.setLayout(ml)
        self.panel = JPanel()
        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        box_layout = BoxLayout(self.panel, BoxLayout.Y_AXIS)

        self.panel.setLayout(box_layout)

        self.choose_dir_label = JLabel('Experiment Folder:')
        self.choose_dir_textField = JTextField(20)
        self.choose_dir_textField.addActionListener(
            ActionListenerFactory(self, self.textField_al))
        self.choose_dir_button = JButton('open')
        self.choose_dir_button.addActionListener(
            ActionListenerFactory(self, self.choose_dir_al))

        self.choose_dir_panel = JPanel()
        self.choose_dir_panel.add(self.choose_dir_label)
        self.choose_dir_panel.add(self.choose_dir_textField)
        self.choose_dir_panel.add(self.choose_dir_button)

        self.panel.add(self.choose_dir_panel)

        self.add(self.panel)
        self.setPreferredSize(Dimension(500, 300))

        self.pack()
        self.setLocationRelativeTo(None)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setVisible(True)
Beispiel #28
0
class MainPanel():
    """Represents the converted frame from NetBeans."""

    # default issue to populate the panel with
    defaultIssue = Issue(name="Name",
                         severity="Critical",
                         host="Host",
                         path="Path",
                         description="Description",
                         remediation="",
                         reqResp=RequestResponse(request="default request",
                                                 response="default response"))

    def loadPanel(self, issue):
        # type: (Issue) -> ()
        """Populates the panel with issue."""
        if issue is None:
            return

        # check if the input is the correct object
        assert isinstance(issue, Issue)

        # add selected issue to the panel to enable right-click stuff.
        self.selectedIssue = issue
        # set textfields and textareas
        self.textName.text = issue.name
        self.textHost.text = issue.host
        self.textPath.text = issue.path
        self.textAreaDescription.text = issue.description
        self.textAreaRemediation.text = issue.remediation
        self.textSeverity.text = issue.severity
        # request and response tabs
        self.panelRequest.setMessage(issue.getRequest(), True)
        self.panelResponse.setMessage(issue.getResponse(), False)

    # button actions
    def newIssueAction(self, event):
        """Pops up a frame to add a new issue."""
        frm = NewIssueDialog(callbacks=self.callbacks, title="New Issue")
        frm.display(self)

    def gotNewIssue(self, issue):
        """got a new issue."""
        self.tableIssue.addRow(issue)

    def editIssue(self, index, issue):
        """Issue has been edited."""
        self.tableIssue.editRow(index, issue)

    def deleteIssueAction(self, event):
        """Delete the currently selected issue."""
        # this is the button
        # btn = event.getSource()
        row = self.tableIssue.getTableSelectedRow()
        # YOLO
        self.tableIssue.deleteRow(row)
        # it works!

    def exportAction(self, event):
        """Export everything in the table to a file."""
        lastDir = ""
        try:
            # load the last used directory
            # this will probably change as we will use a base64 encoded json as the complete config?
            lastDir = self.callbacks.loadExtensionSetting("lastDir")
        except:
            # if there is not a last used directory in the settings, continue
            pass

        from Utils import saveFileDialog, writeFile
        selectedFile, usedDirectory = saveFileDialog(parent=self.panel,
                                                     startingDir=lastDir,
                                                     title="Export Issues",
                                                     extension="json")

        if selectedFile is not None:
            # write to the file
            writeFile(selectedFile.getAbsolutePath(),
                      self.tableIssue.exportIssues())

        if usedDirectory is not None:
            # overwrite the last used directory
            self.callbacks.saveExtensionSetting("lastDir", usedDirectory)

    def importAction(self, event):
        """Import a file to the table."""
        lastDir = ""
        try:
            # load the last used directory
            # this will probably change as we will use a base64 encoded json as the complete config?
            lastDir = self.callbacks.loadExtensionSetting("lastDir")
        except:
            # if there is not a last used directory in the settings, continue
            pass

        from Utils import openFileDialog
        selectedFile, usedDirectory = openFileDialog(parent=self.panel,
                                                     startingDir=lastDir,
                                                     title="Import Issues",
                                                     extension="json")

        # save the last directory
        self.callbacks.saveExtensionSetting("lastDir", usedDirectory)
        fi = open(selectedFile.getAbsolutePath(), "r")
        # read the file and create a list of Issues
        import json
        # newIssues = json.load(fi, object_hook=dictToIssue)
        # problem here is object_hook runs for every single object so newIssues
        # will have internal objects, even if we tag them

        from RequestResponse import RequestResponse, HttpService
        from base64 import b64decode
        issuesArray = json.load(fi)
        # now issuesArray is an array of dicts.
        # manual JSON deserialization - move this to a method/function?
        # also think about what happens if dictionaries are missing items
        newIssues = list()
        for eachissue in issuesArray:
            # now we have each issue
            # what if dictionaries are missing items?
            ht = HttpService(
                host=eachissue["reqResp"]["httpService"]["host"],
                port=eachissue["reqResp"]["httpService"]["port"],
                protocol=eachissue["reqResp"]["httpService"]["protocol"])
            rr = RequestResponse(
                request=b64decode(eachissue["reqResp"]["request"]),
                response=b64decode(eachissue["reqResp"]["response"]),
                comment=eachissue["reqResp"]["comment"],
                highlight=eachissue["reqResp"]["highlight"],
                httpService=ht)
            iss = Issue(name=eachissue["name"],
                        severity=eachissue["severity"],
                        host=eachissue["host"],
                        path=eachissue["path"],
                        description=eachissue["description"],
                        remediation=eachissue["remediation"],
                        reqResp=rr)

            # iss = Issue()
            # rr = RequestResponse()
            # ht = HttpService()
            newIssues.append(iss)

        # clear the table
        self.tableIssue.clear()
        # add the issues to the table
        # for iss in newIssues:
        #     self.tableIssue.addRow(iss)
        self.tableIssue.populate(newIssues)

    def newIssueFromBurp(self, invocation):
        """Create a New Issue from the context menu."""
        from Utils import getPath, bytesToString, burpToolName
        reqResp = invocation.getSelectedMessages()[0]
        host = str(reqResp.getHttpService())
        path = getPath(self.callbacks, reqResp)
        convertedReqResp = RequestResponse()
        convertedReqResp.fromIHttpRequestResponse(reqResp)
        tmpIssue = Issue(host=host, path=path, reqResp=convertedReqResp)
        # change the title to "New Issue from [TOOL]"?
        frameTitle = "New Issue from %s" % (burpToolName(
            invocation.getToolFlag()))
        frm = NewIssueDialog(callbacks=self.callbacks,
                             issue=tmpIssue,
                             title=frameTitle
                             #  , modality="application"
                             )
        frm.display(self)
        # FOCUS!
        frm.requestFocus()
        # print self.callbacks.getHelpers().bytesToString(reqResp[0].getRequest())

    # mostly converted generated code
    def __init__(self, callbacks, table=None):

        self.callbacks = callbacks
        self.jScrollPane1 = JScrollPane()
        self.jPanel1 = JPanel()
        self.labelName = JLabel("Name")
        self.textName = JTextField()
        self.labelSeverity = JLabel("Severity")
        self.textSeverity = JTextField()
        self.labelHost = JLabel("Host")
        self.labelPath = JLabel("Path")
        self.textHost = JTextField()
        self.textPath = JTextField()
        self.tabIssue = JTabbedPane()
        self.textAreaDescription = JTextArea()
        self.textAreaRemediation = JTextArea()
        # JScrollPanes to hold the two jTextAreas
        # put the textareas in JScrollPanes
        self.jsPaneDescription = JScrollPane(self.textAreaDescription)
        self.jsPaneRemediation = JScrollPane(self.textAreaRemediation)
        self.panelRequest = self.callbacks.createMessageEditor(None, False)
        self.panelResponse = self.callbacks.createMessageEditor(None, False)

        self.loadPanel(self.defaultIssue)

        # buttons
        self.buttonNewIssue = JButton("New Issue",
                                      actionPerformed=self.newIssueAction)
        self.buttonDeleteIssue = JButton(
            "Delete Issue", actionPerformed=self.deleteIssueAction)
        self.buttonImport = JButton("Import",
                                    actionPerformed=self.importAction)
        self.buttonExport = JButton("Export",
                                    actionPerformed=self.exportAction)

        if table is not None:
            self.tableIssue = table
        else:
            from IssueTable import IssueTable
            self.tableIssue = IssueTable()

        # wrap the table in a scrollpane
        self.jScrollPane1.setViewportView(self.tableIssue)

        # 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.textName.editable = False
        self.textName.setBackground(Color.LIGHT_GRAY)

        self.textSeverity.editable = False
        self.textSeverity.setBackground(Color.LIGHT_GRAY)

        self.textHost.editable = False
        self.textHost.setBackground(Color.LIGHT_GRAY)

        self.textPath.editable = False
        self.textPath.setBackground(Color.LIGHT_GRAY)

        # description textarea
        self.textAreaDescription.editable = False
        self.textAreaDescription.setLineWrap(True)
        self.textAreaDescription.setWrapStyleWord(True)
        self.tabIssue.addTab("Description", self.jsPaneDescription)

        # remediation textarea
        self.textAreaRemediation.editable = False
        self.textAreaRemediation.setLineWrap(True)
        self.textAreaRemediation.setWrapStyleWord(True)
        self.tabIssue.addTab("Remediation", self.jsPaneRemediation)

        # request tab
        self.panelRequest.setMessage("", True)
        self.tabIssue.addTab("Request", self.panelRequest.getComponent())

        # response tab
        self.panelResponse.setMessage("", False)
        self.tabIssue.addTab("Response", self.panelResponse.getComponent())

        # from java.lang import Short
        # jpanel1 is the bottom panel
        jPanel1Layout = GroupLayout(self.jPanel1)
        self.jPanel1.setLayout(jPanel1Layout)
        jPanel1Layout.setHorizontalGroup(
            # GroupLayout.Alignment.CENTER centers the group, in this case it
            # centers the buttons
            jPanel1Layout.createParallelGroup(
                GroupLayout.Alignment.CENTER
            ).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap(
            ).addGroup(
                jPanel1Layout.createParallelGroup(
                    GroupLayout.Alignment.LEADING).
                addGroup(jPanel1Layout.createSequentialGroup().addGroup(
                    jPanel1Layout.createParallelGroup(
                        GroupLayout.Alignment.TRAILING).addComponent(
                            self.labelHost).addComponent(self.labelName)
                ).addPreferredGap(
                    LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                        jPanel1Layout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addGroup(
                                jPanel1Layout.createSequentialGroup(
                                ).addComponent(self.textName).addPreferredGap(
                                    LayoutStyle.ComponentPlacement.UNRELATED).
                                addComponent(
                                    self.labelSeverity).addPreferredGap(
                                        LayoutStyle.ComponentPlacement.
                                        RELATED).addComponent(
                                            self.textSeverity,
                                            GroupLayout.PREFERRED_SIZE, 186,
                                            GroupLayout.PREFERRED_SIZE)).
                        addGroup(
                            jPanel1Layout.createSequentialGroup().addComponent(
                                self.textHost, GroupLayout.PREFERRED_SIZE, 330,
                                GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                    LayoutStyle.ComponentPlacement.RELATED
                                ).addComponent(self.labelPath).addPreferredGap(
                                    LayoutStyle.ComponentPlacement.RELATED).
                            addComponent(self.textPath)))).addComponent(
                                self.tabIssue)).addContainerGap()
                       ).addGroup(
                           jPanel1Layout.createSequentialGroup().addComponent(
                               self.buttonNewIssue).addComponent(
                                   self.buttonDeleteIssue).addComponent(
                                       self.buttonImport).addComponent(
                                           self.buttonExport)))

        # link size of buttons
        from javax.swing import SwingConstants
        jPanel1Layout.linkSize(SwingConstants.HORIZONTAL, [
            self.buttonDeleteIssue, self.buttonExport, self.buttonImport,
            self.buttonNewIssue
        ])

        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
        ).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).addComponent(
                                self.labelSeverity).addComponent(
                                    self.textSeverity,
                                    GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.PREFERRED_SIZE)
            ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(
                jPanel1Layout.createParallelGroup(
                    GroupLayout.Alignment.BASELINE).addComponent(
                        self.textHost, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE,
                        GroupLayout.PREFERRED_SIZE).addComponent(
                            self.labelPath).addComponent(
                                self.textPath, GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.labelHost)).addPreferredGap(
                                        LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(self.tabIssue).addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED).addGroup(
                    jPanel1Layout.createParallelGroup().addComponent(
                        self.buttonNewIssue).addComponent(
                            self.buttonDeleteIssue).addComponent(
                                self.buttonImport).addComponent(
                                    self.buttonExport)).addContainerGap()))

        # create the main panel
        self.panel = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # set the top component
        self.panel.leftComponent = self.jScrollPane1
        self.panel.rightComponent = self.jPanel1
        self.panel.setDividerLocation(150)
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        print "Loading..."

        self._callbacks = callbacks
        self._callbacks.setExtensionName('Burp SPA Explorer')
        # self._callbacks.registerScannerCheck(self)
        # self._callbacks.registerExtensionStateListener(self)
        self._helpers = callbacks.getHelpers()

        self.crawlingEvent = Event()
        self.crawlerThread = None

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20))

        # sub split pane (top)
        self._topPanel = JPanel(BorderLayout(10, 10))
        self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0))

        # Setup Panel :    [Target: ] [______________________] [START BUTTON]
        self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.setupPanel.add(JLabel("Target:", SwingConstants.LEFT),
                            BorderLayout.LINE_START)

        self.hostField = JTextField('', 50)
        self.setupPanel.add(self.hostField)

        self.toggleButton = JButton('Start crawling',
                                    actionPerformed=self.toggleCrawl)
        self.setupPanel.add(self.toggleButton)

        self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START)

        # Options Panel :    [Buttons]  [          RegEx           ]
        self.optionsPanel = JPanel()
        self.optionsPanel.setLayout(
            BoxLayout(self.optionsPanel, BoxLayout.LINE_AXIS))

        # Button options panel :    [Add][Edit][Up][Down][Remove]

        self.buttonOptionsPanel = JPanel()
        self.buttonOptionsPanel.setLayout(
            BoxLayout(self.buttonOptionsPanel, BoxLayout.PAGE_AXIS))

        self.addRegexButton = JButton('Add', actionPerformed=self.addRegex)
        self.buttonOptionsPanel.add(self.addRegexButton)

        self.editRegexButton = JButton('Edit', actionPerformed=self.editRegex)
        self.buttonOptionsPanel.add(self.editRegexButton)

        self.moveRegexUpButton = JButton('Move up',
                                         actionPerformed=self.moveRegexUp)
        self.buttonOptionsPanel.add(self.moveRegexUpButton)

        self.moveRegexDownButton = JButton('Move down',
                                           actionPerformed=self.moveRegexDown)
        self.buttonOptionsPanel.add(self.moveRegexDownButton)

        self.removeRegexButton = JButton('Remove',
                                         actionPerformed=self.removeRegex)
        self.buttonOptionsPanel.add(self.removeRegexButton)

        self.buttonOptionsPanel.add(Box.createVerticalGlue())

        self.optionsPanel.add(self.buttonOptionsPanel)

        self.optionsPanel.add(Box.createHorizontalStrut(20))

        self.regexTableModel = RegexTableModel([x for x in regex])
        self.regexTable = Table(self.regexTableModel)
        self.regexScrollPane = JScrollPane(self.regexTable)

        self.optionsPanel.add(self.regexScrollPane)

        self._topPanel.add(self.optionsPanel, BorderLayout.CENTER)
        self._splitpane.setTopComponent(self._topPanel)

        # Bottom Panel
        self._bottomPanel = JPanel(BorderLayout(10, 10))
        #self._bottomPanel.setLayout(BoxLayout(self._bottomPanel,BoxLayout.PAGE_AXIS))

        # Status bar
        self.crawlStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.crawlStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT))

        self.crawlStatusLabel = JLabel("Ready to crawl", SwingConstants.LEFT)
        self.crawlStatusPanel.add(self.crawlStatusLabel)

        # Result Table
        self.resultTableModel = Result([])
        self.resultTable = Table(self.resultTableModel)
        self.resultTable.setAutoCreateRowSorter(True)
        self.resultScrollPane = JScrollPane(self.resultTable)

        # Result Table popup menu
        def selectWhenRightClickEvent(event):
            def select(e):
                rowAtPoint = self.resultTable.rowAtPoint(
                    SwingUtilities.convertPoint(self.resultTablePopupMenu,
                                                Point(0, 0), self.resultTable))
                if rowAtPoint > -1:
                    self.resultTable.setRowSelectionInterval(
                        rowAtPoint, rowAtPoint)

            SwingUtilities.invokeLater(CrawlerRunnable(select, (event, )))

        self.resultTablePopupMenu = JPopupMenu(
            popupMenuWillBecomeVisible=selectWhenRightClickEvent)
        self.resultTablePopupMenu.add(
            JMenuItem("Send to scanner", actionPerformed=self.sendToScanner))
        self.resultTablePopupMenu.add(
            JMenuItem("Send to repeater", actionPerformed=self.sendToRepeater))
        self.resultTablePopupMenu.add(
            JMenuItem("Send to intruder", actionPerformed=self.sendToIntruder))
        self.resultTablePopupMenu.add(
            JMenuItem("Send to spider", actionPerformed=self.sendToSpider))

        self.resultTable.setComponentPopupMenu(self.resultTablePopupMenu)

        self._bottomPanel.add(self.resultScrollPane, BorderLayout.CENTER)
        self._bottomPanel.add(self.crawlStatusPanel, BorderLayout.SOUTH)

        self._splitpane.setBottomComponent(self._bottomPanel)
        self._splitpane.setDividerLocation(300 +
                                           self._splitpane.getInsets().left)

        callbacks.customizeUiComponent(self._splitpane)

        callbacks.addSuiteTab(self)

        explorerMenu = ExplorerMenu(self)
        callbacks.registerContextMenuFactory(explorerMenu)
        print "SPA Explorer custom menu loaded"

        #print "Loading chrome driver"
        #a = Test(os.path.dirname(os.path.realpath('selenium-client.jar')) + '/chromedriver.exe')
        #print "Chrome driver started"

        print "Burp SPA Explorer loaded"

    # Button Actions

    def getURLComponents(self, url):
        return (url.getHost(), (443 if url.getProtocol() == 'https' else 80)
                if url.getPort() == -1 else url.getPort(),
                url.getProtocol() == 'https')

    def sendToScanner(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        urlComp = self.getURLComponents(url)
        self._callbacks.doActiveScan(urlComp[0], urlComp[1], urlComp[2],
                                     self._helpers.buildHttpRequest(url))

    def sendToRepeater(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        urlComp = self.getURLComponents(url)
        self._callbacks.sendToRepeater(urlComp[0], urlComp[1], urlComp[2],
                                       self._helpers.buildHttpRequest(url),
                                       None)

    def sendToIntruder(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        urlComp = self.getURLComponents(url)
        self._callbacks.sendToIntruder(urlComp[0], urlComp[1], urlComp[2],
                                       self._helpers.buildHttpRequest(url))

    def sendToSpider(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        self._callbacks.sendToSpider(url)

    def addRegex(self, event):
        optionPane = JOptionPane()
        dialog = optionPane.createDialog(self._splitpane, "Add RegEx")

        panel = JPanel(GridLayout(0, 2))
        panel.setBorder(EmptyBorder(10, 10, 10, 10))

        nameField = JTextField('', 15)
        panel.add(JLabel("Name:", SwingConstants.LEFT))
        panel.add(nameField)

        regexField = JTextField('', 15)
        panel.add(JLabel("RegEx:", SwingConstants.LEFT))
        panel.add(regexField)

        crawlField = JCheckBox()
        panel.add(JLabel("Crawl:", SwingConstants.LEFT))
        panel.add(crawlField)

        def closeDialog(event):
            if len(nameField.text) == 0 or len(regexField.text) == 0:
                JOptionPane.showMessageDialog(self._splitpane,
                                              "Name or RegEx can't be empty",
                                              "Error",
                                              JOptionPane.ERROR_MESSAGE)
                return
            self.regexTableModel.addRow(
                [nameField.text, regexField.text,
                 crawlField.isSelected()])
            dialog.hide()

        addButton = JButton('OK', actionPerformed=closeDialog)
        panel.add(addButton)

        dialog.setSize(600, 200)
        dialog.setContentPane(panel)
        self._callbacks.customizeUiComponent(dialog)
        dialog.show()

        return True

    def editRegex(self, event):
        selectedRowIdx = self.regexTable.getSelectedRow()
        if selectedRowIdx == -1: return False
        selectedRow = self.regexTableModel.data[selectedRowIdx]

        optionPane = JOptionPane()
        dialog = optionPane.createDialog(self._splitpane, "Edit RegEx")

        panel = JPanel(GridLayout(0, 2))
        panel.setBorder(EmptyBorder(10, 10, 10, 10))

        nameField = JTextField('', 15)
        nameField.text = selectedRow[0]
        panel.add(JLabel("Name:", SwingConstants.LEFT))
        panel.add(nameField)

        regexField = JTextField('', 15)
        regexField.text = selectedRow[1]
        panel.add(JLabel("RegEx:", SwingConstants.LEFT))
        panel.add(regexField)

        crawlField = JCheckBox()
        crawlField.setSelected(selectedRow[2])
        panel.add(JLabel("Crawl:", SwingConstants.LEFT))
        panel.add(crawlField)

        def closeDialog(event):
            if len(nameField.text) == 0 or len(regexField.text) == 0:
                JOptionPane.showMessageDialog(self._splitpane,
                                              "Name or RegEx can't be empty",
                                              "Error",
                                              JOptionPane.ERROR_MESSAGE)
                return
            self.regexTableModel.editRow(
                selectedRowIdx,
                [nameField.text, regexField.text,
                 crawlField.isSelected()])
            dialog.hide()

        editButton = JButton('OK', actionPerformed=closeDialog)
        panel.add(editButton)

        dialog.setSize(600, 200)
        dialog.setContentPane(panel)
        self._callbacks.customizeUiComponent(dialog)
        dialog.show()
        return True

    def moveRegexDown(self, event):
        idxs = self.regexTable.getSelectedRows()
        if self.regexTableModel.getRowCount() - 1 in idxs: return False

        self.regexTable.clearSelection()
        for i in sorted(idxs)[::-1]:
            self.regexTableModel.moveDown(i)
            self.regexTable.addRowSelectionInterval(i + 1, i + 1)
        return True

    def moveRegexUp(self, event):
        idxs = self.regexTable.getSelectedRows()
        if 0 in idxs: return False

        self.regexTable.clearSelection()
        for i in sorted(idxs):
            self.regexTableModel.moveUp(i)
            self.regexTable.addRowSelectionInterval(i - 1, i - 1)
        return True

    def removeRegex(self, event):
        idx = self.regexTable.getSelectedRows()
        for i in sorted(idx)[::-1]:
            self.regexTableModel.removeRow(i)
        return True

    # Implement ITab

    def getTabCaption(self):
        return "SPA Explorer"

    def getUiComponent(self):
        return self._splitpane

    def crawl(self, event):
        print("Starting")

        host = self.hostField.text

        if host.find("://") == -1:
            host = "http://" + host

        try:
            self._callbacks.includeInScope(URL(host))
        except:
            JOptionPane.showMessageDialog(self._splitpane,
                                          "Can't add host to scope", "Error",
                                          JOptionPane.ERROR_MESSAGE)
            return

        self.resultTableModel.clearAllRow()

        self.crawlingEvent.set()
        self.crawlerThread = Thread(target=self.crawl_thread, args=(host, ))
        self.crawlerThread.start()
        print("Started")

    def stopCrawling(self, event):
        print("Clear event")
        self.crawlingEvent.clear()

        # Disable button
        if self.toggleButton.text == "Stop crawling":  # If button is still "Stop crawling" (Thread still running), disable button
            self.toggleButton.setEnabled(False)

    def toggleCrawl(self, event):
        if (self.crawlerThread == None or not self.crawlerThread.is_alive()):
            self.crawl(event)
            #self.toggleButton.setText("Start crawling")
        else:
            self.stopCrawling(event)
            #self.toggleButton.setText("Stop crawling")

    def crawl_thread(self, host):
        # print(self, host)
        print("Crawl thread started")

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.toggleButton.setText, ("Stop crawling", )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.addRegexButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.editRegexButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexUpButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexDownButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.removeRegexButton.setEnabled, (False, )))

        pageType = {}  # url -> type
        pageContentHash = {}  # hash -> url list

        def concatURL(baseURL, link):
            return URL(URL(baseURL), link).toString()

        def makeRequest(url):
            url = URL(url)

            if not self._callbacks.isInScope(url):
                #self.logger.addRow(url.toString()+" is out of scope")
                raise ValueError("URL is out of scope")

            prot = url.getProtocol()
            host = url.getHost()
            port = url.getPort()
            if port == -1:
                port = 80 if prot == "http" else 443

            httpService = self._helpers.buildHttpService(host, port, prot)

            reqRes = self._callbacks.makeHttpRequest(
                httpService, self._helpers.buildHttpRequest(url))
            self._callbacks.addToSiteMap(reqRes)
            resp = reqRes.getResponse()
            respInfo = self._helpers.analyzeResponse(resp)

            respBody = self._helpers.bytesToString(
                resp[respInfo.getBodyOffset():])
            return respBody

        def matchRegex(baseURL, res):
            toRet = []
            for (name, regStr, ret) in self.regexTableModel.data:
                matchObj = re.findall(regStr, res, re.M | re.I)
                for i in matchObj:
                    try:
                        if i.find('http://') == 0 or i.find('https://') == 0:
                            url = i
                        elif i[0] == '/':
                            url = host + i
                        else:
                            url = host + '/' + i

                        if url not in pageType:
                            pageType[url] = name
                            SwingUtilities.invokeLater(
                                CrawlerRunnable(self.resultTableModel.addRow,
                                                ([name, url], )))

                            if ret:
                                toRet.append(url)
                    except:
                        print("Error when trying to save result ", i,
                              sys.exc_info()[0],
                              sys.exc_info()[1])
            return toRet

        def getAllLink(url):
            toRet = []
            try:
                print("Making request", url)
                r = makeRequest(url)
                print("Done request", len(r))
                hash = hashlib.sha256(r.encode('utf-8')).hexdigest()
                #print(r.text)
                if hash in pageContentHash:
                    print("Content hash is the same as ",
                          pageContentHash[hash][0])
                    pageContentHash[hash].append(url)
                    return toRet
                else:
                    pageContentHash[hash] = [url]

                toRet += matchRegex(url, r)
            except BaseException as e:
                print("Error while making request to ", url, e)
            except:
                print("Error while making request to ", url,
                      sys.exc_info()[0],
                      sys.exc_info()[1])
            return toRet

        crawledPage = [host]
        crawledNow = 0

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.resultTableModel.addRow,
                            (["TARGET", host], )))

        while crawledNow < len(crawledPage):
            if self.crawlingEvent.is_set():
                print("Crawling", crawledPage[crawledNow])
                SwingUtilities.invokeLater(
                    CrawlerRunnable(self.crawlStatusLabel.setText,
                                    ("Crawling " + crawledPage[crawledNow], )))
                for i in getAllLink(crawledPage[crawledNow]):
                    if i not in crawledPage:
                        print("ADD:", i)
                        crawledPage.append(i)
                crawledNow += 1
            else:
                print("Stop Requested")
                break

        print(crawledNow, crawledPage)
        output = []

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.toggleButton.setText, ("Start crawling", )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.toggleButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.addRegexButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.editRegexButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexUpButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexDownButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.removeRegexButton.setEnabled, (True, )))

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.crawlStatusLabel.setText,
                            ("Ready to crawl", )))

        self.crawlingEvent.clear()
        print("Completed")
Beispiel #30
0
    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)
Beispiel #31
0
    class ConfigurationController(IMessageEditorController):
        def __init__(self, parent):
            self._parent = parent

        def getMainComponent(self):
            self._mainPanel = JPanel()
            #self._mainPanel.setLayout(BoxLayout(self._mainPanel, BoxLayout.Y_AXIS))
            self._mainPanel.setLayout(BorderLayout())
            self._titlePanel = JPanel(GridLayout(0, 1))
            self._titlePanel.setBorder(EmptyBorder(10, 20, 10, 10))
            self._titleText = JLabel("Mode configuration")
            self._titleText.setForeground(COLOR_BURP_TITLE_ORANGE)
            self._titleText.setFont(self._titleText.getFont().deriveFont(16.0))
            self._titleSubtitleText = JTextArea("Select a mode that works best for the type of exploit you are dealing with.")
            self._titleSubtitleText.setEditable(False)
            self._titleSubtitleText.setLineWrap(True)
            self._titleSubtitleText.setWrapStyleWord(True)
            self._titleSubtitleText.setHighlighter(None)
            self._titleSubtitleText.setBorder(None)

            #Local File Inclusion (LFI): Explore files
            #Command injection (visual): Shell
            #Command injection (blind):  Shell
            modes = ['Select mode...', 'Local File Inclusion (LFI) - Discover files', 'OS Command injection (visual) - Shell']
            self._cboModes = JComboBox(modes)
            self._cboModes.addActionListener(self.cboModesChanged())

            self._titlePanel.add(self._titleText)
            self._titlePanel.add(self._titleSubtitleText)
            self._titlePanel.add(self._cboModes)

            self._mainPanel.add(self._titlePanel, BorderLayout.NORTH)

            self._switchPanel = JPanel()
            self._switchPanel.setLayout(BoxLayout(self._switchPanel, BoxLayout.Y_AXIS))
            self._switchPanel.setBorder(EmptyBorder(5, 30, 10, 10))
            self._outputCompleteResponseSwitch = JCheckBox("Use full response (not only the response body)")
            self._outputCompleteResponseSwitch.setSelected(True)
            self._outputCompleteResponseSwitch.addItemListener(self.OutputCompleteResponseSwitchListener())
            self._switchPanel.add(self._outputCompleteResponseSwitch)
            self._urlEncodeSwitch = JCheckBox("Use url encode")
            self._urlEncodeSwitch.setSelected(True)
            self._urlEncodeSwitch.addItemListener(self.UrlEncodeSwitchListener())
            self._switchPanel.add(self._urlEncodeSwitch)
            self._outputIsolatorSwitch = JCheckBox("Use output isolator")
            self._outputIsolatorSwitch.setSelected(False)
            self._outputIsolatorSwitch.addItemListener(self.OutputIsolatorSwitchListener())
            self._switchPanel.add(self._outputIsolatorSwitch)
            self._removeSpacesSwitch = JCheckBox("Remove leading and trailing spaces")
            self._removeSpacesSwitch.setSelected(False)
            self._removeSpacesSwitch.addItemListener(self.SpacesSwitch())
            self._switchPanel.add(self._removeSpacesSwitch)
            self._removeHtmlTagsSwitch = JCheckBox("Remove html-tags (regex '<.*?>')")
            self._removeHtmlTagsSwitch.setSelected(False)
            self._removeHtmlTagsSwitch.addItemListener(self.HtmlTagsSwitch())
            self._switchPanel.add(self._removeHtmlTagsSwitch)
            self._tabCompletionSwitch = JCheckBox("Use tab-completion")
            self._tabCompletionSwitch.setSelected(False)
            self._tabCompletionSwitch.addItemListener(self.TabCompletionSwitchListener())
            self._switchPanel.add(self._tabCompletionSwitch)
            self._virtualPersistenceSwitch = JCheckBox("Use virtual persistence")
            self._virtualPersistenceSwitch.setSelected(False)
            self._virtualPersistenceSwitch.addItemListener(self.VirtualPersistenceSwitchListener())
            self._switchPanel.add(self._virtualPersistenceSwitch)
            self._wafSwitch = JCheckBox("WAF: Prepend each non-whitespace character (regex '\\w') with '\\'")
            self._wafSwitch.setSelected(False)
            self._wafSwitch.addItemListener(self.WafSwitch())
            self._switchPanel.add(self._wafSwitch)
            self._mainPanel.add(self._switchPanel, BorderLayout.CENTER)
            return self._mainPanel

        class cboModesChanged(ActionListener):
            def actionPerformed(self, e):
                cboModes = e.getSource()
                mode = cboModes.getSelectedItem()
                if mode == 'Local File Inclusion (LFI) - Discover files':
                    #Disable output isolator
                    Utils.shellController._outputIsolator = None
                    Utils.outputIsolator = None
                    Utils._outputIsolator = None
                    Utils.configurationController._outputIsolatorSwitch.setSelected(False)
                    Utils.configurationController._outputIsolatorSwitch.setEnabled(False)
                    #Disable remove leading and trailing spaces
                    Utils.shellController._removeSpaces = False
                    Utils.configurationController._removeSpacesSwitch.setSelected(False)
                    Utils.configurationController._removeSpacesSwitch.setEnabled(False)
                    #Disable remove html tags
                    Utils.shellController._removeHtmlTags = False
                    Utils.configurationController._removeHtmlTagsSwitch.setSelected(False)
                    Utils.configurationController._removeHtmlTagsSwitch.setEnabled(False)
                    #Disable tab-completion
                    Utils.shellController._tabCompletion = False
                    Utils.configurationController._tabCompletionSwitch.setSelected(False)
                    Utils.configurationController._tabCompletionSwitch.setEnabled(False)
                    #Disable virtual peristence
                    Utils.shellController._virtualPersistence = False
                    Utils.configurationController._virtualPersistenceSwitch.setSelected(False)
                    Utils.configurationController._virtualPersistenceSwitch.setEnabled(False)
                    #Disable WAF
                    Utils.shellController._waf = False
                    Utils.configurationController._wafSwitch.setSelected(False)
                    Utils.configurationController._wafSwitch.setEnabled(False)
                if mode == 'OS Command injection (visual) - Shell' or mode == 'Select mode...':
                    Utils.configurationController._outputIsolatorSwitch.setEnabled(True)
                    Utils.configurationController._removeSpacesSwitch.setEnabled(True)
                    Utils.configurationController._removeHtmlTagsSwitch.setEnabled(True)
                    Utils.configurationController._tabCompletionSwitch.setEnabled(True)
                    Utils.configurationController._virtualPersistenceSwitch.setEnabled(True)
                    Utils.configurationController._wafSwitch.setEnabled(True)

        class OutputIsolatorSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.out("selected")
                    isolator = ["3535start3535", "3535end3535"]
                    Utils.shellController._outputIsolator = isolator
                    Utils.outputIsolator = isolator
                    Utils._outputIsolator = isolator
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    #TODO If deselected, Virtual persistence should be disabled: unless the body only returns
                    # the command and nothing else, it's near impossible to warrant virtual persistence.
                    # One possibility I have, is to also allow to define positions in the response tab and filter
                    # out the command response like that (without using the outputisolators)
                    Utils.out("deselected")
                    Utils.shellController._outputIsolator = None
                    Utils.outputIsolator = None
                    Utils._outputIsolator = None

        class SpacesSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._removeSpaces = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._removeSpaces = False

        class HtmlTagsSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._removeHtmlTags = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._removeHtmlTags = False

        class TabCompletionSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._tabCompletion = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._tabCompletion = False

        class VirtualPersistenceSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._virtualPersistence = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.consoleController.setPwd(None)
                    Utils.shellController._virtualPersistence = False

        class UrlEncodeSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._urlEncode = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._urlEncode = False

        class OutputCompleteResponseSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._outputCompleteResponse = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._outputCompleteResponse = False

        class WafSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._waf = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._waf = False
Beispiel #32
0
    class PositionsController(IMessageEditorController):
        def __init__(self, parent):
            self._parent = parent

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            #Left panel
            self._leftPanel = JPanel(BorderLayout())
            self._leftPanel.setBorder(EmptyBorder(10, 10, 10, 10))
            #Left subpanel - Positions editor
            self._positionsEditor = Utils.callbacks.createTextEditor()
            #TODO Remove a normal editor?  self._positionsEditor = Utils.callbacks.createMessageEditor(self, True)
            self._positionsEditor.getComponent().setBorder(BorderFactory.createLineBorder(Color.BLACK))
            #Left subpanel - Title pane
            self._leftTitlePanel = JPanel(GridLayout(0, 1))
            self._leftTitlePanel.setBorder(EmptyBorder(0, 10, 10, 10))
            self._titleText = JLabel("Commands Position")
            self._titleText.setForeground(COLOR_BURP_TITLE_ORANGE)
            self._titleText.setFont(self._titleText.getFont().deriveFont(16.0))
            self._titleSubtitleText = JTextArea("Configure the position where commands will be inserted into the base request. Select the requests that were send Shell in the dropdown, then select the part of the request where commands need to be inserted and click the 'Add $' button.")
            self._titleSubtitleText.setEditable(False)
            self._titleSubtitleText.setLineWrap(True)
            self._titleSubtitleText.setWrapStyleWord(True)
            self._titleSubtitleText.setHighlighter(None)
            self._titleSubtitleText.setBorder(None)
            self._leftTitlePanel.add(self._titleText)
            self._leftTitlePanel.add(self._titleSubtitleText)
            #Left subpanel - Add positions editor and title
            self._leftPanel.add(self._leftTitlePanel, BorderLayout.NORTH)
            self._leftPanel.add(self._positionsEditor.getComponent(), BorderLayout.CENTER)
            #Right panel
            #self._rightPanel = JPanel(GridLayout(20, 1))
            self._rightPanel = JPanel()
            self._rightPanel.setLayout(BoxLayout(self._rightPanel, BoxLayout.Y_AXIS))
            #self._rightPanel.setPreferredSize(Dimension(150, 30))
            self._rightPanel.setBorder(EmptyBorder(10, 10, 10, 10))
            #Right panel - buttons
            self._buttonAdd = JButton("        Add $        ", actionPerformed=self.buttonAddClick)
            self._buttonClear = JButton("       Clear $       ", actionPerformed=self.buttonClearClick) #, actionPerformed=None
            # Right panel - add components
            self._rightPanel.add(self._buttonAdd)
            self._rightPanel.add(self._buttonClear)

            self._mainPanel.add(self._rightPanel, BorderLayout.EAST)
            self._mainPanel.add(self._leftPanel, BorderLayout.CENTER)

            return self._mainPanel

        def buttonAddClick(self, e):
            Utils.out("Button Add click")
            if self._positionsEditor.getSelectedText():
                #TODO: For if it's a messageeditor in stead of texteditor Utils.out(self._positionsEditor.getSelectedData())
                self.addPosition(self._positionsEditor.getSelectionBounds())
                self._parent._consoleController.startSession()
                self._buttonAdd.setEnabled(False)

        def buttonClearClick(self, e):
            Utils.out("Button Clear click")
            self.setEditor(self._parent.currentRequestRaw())
            self._buttonAdd.setEnabled(True)

        def setEditor(self, request_in_bytes):
            self._positionsEditor.setText(request_in_bytes)
            #TODO: for if I make the positions a messageExitor: self._positionsEditor.setMessage(iHttpRequestResponse.getRequest(), True)

        def addPosition(self, boundsArray):
            if len(boundsArray) == 2:
                self._parent.setCurrentRequestBounds(boundsArray[0], boundsArray[1])
                modified_request = Utils.wrapRawData(self._parent.currentRequestRaw(), boundsArray[0], boundsArray[1], "$", "$")
                self.setEditor(modified_request)
Beispiel #33
0
class Interfaz(JFrame):
    def __init__(self):
        super(Interfaz, self).__init__()
        self.filename = ''
        self.initUI()

    def initUI(self):

        self.panel = JPanel()
        self.panel.setLayout(GridLayout(6, 3))
        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        labelVacio1 = JLabel(' ')
        labelVacio2 = JLabel(' ')
        labelVacio3 = JLabel(' ')
        labelVacio4 = JLabel(' ')
        labelVacio5 = JLabel(' ')
        labelVacio6 = JLabel(' ')
        labelVacio7 = JLabel(' ')
        labelVacio8 = JLabel(' ')
        labelVacio9 = JLabel(' ')
        labelVacio10 = JLabel(' ')
        labelVacio11 = JLabel(' ')
        labelVacio12 = JLabel(' ')
        labelVacio13 = JLabel(' ')
        labelVacio14 = JLabel(' ')
        labelVacio15 = JLabel(' ')
        labelVacio16 = JLabel(' ')

        labelURL = JLabel(' Introduzca las URL que desee analizar:')
        chkboxSync = JCheckBox('Sincronizacion de cookies')
        self.textfieldURL = JTextField(15)
        chkboxResp = JCheckBox('Restauracion de cookies')
        labelFichero = JLabel(' O seleccione un fichero que las contenga:')

        self.area = JTextArea()
        pane = JScrollPane()
        pane.getViewport().add(self.area)

        panelFichero = JPanel()
        panelFichero.setLayout(None)
        buttonFichero = JButton("Seleccionar fichero",
                                actionPerformed=self.open)
        buttonFichero.setBounds(10, 0, 200, 25)
        panelFichero.add(buttonFichero)
        buttonEjecutar = JButton("Ejecutar", actionPerformed=self.ejecutar)

        buttonEjecutar.setFont(Font("Tahoma", Font.BOLD, 24))

        self.panel.add(labelURL)
        self.panel.add(labelVacio4)
        self.panel.add(chkboxSync)

        self.panel.add(self.textfieldURL)
        self.panel.add(labelVacio6)
        self.panel.add(chkboxResp)

        self.panel.add(labelFichero)
        self.panel.add(labelVacio9)
        self.panel.add(labelVacio10)

        self.panel.add(pane)
        self.panel.add(panelFichero)
        #self.panel.add(buttonFichero)
        self.panel.add(labelVacio11)

        self.panel.add(labelVacio12)
        self.panel.add(labelVacio13)
        self.panel.add(labelVacio14)

        self.panel.add(labelVacio15)
        self.panel.add(buttonEjecutar)
        self.panel.add(labelVacio16)

        self.add(self.panel)

        self.setTitle(
            "HERRAMIENTA PARA LA DETECCION DE TECNICAS DE SEGUIMIENTO DE USUARIOS EN LA WEB"
        )
        self.setSize(1000, 450)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def open(self, e):
        filechooser = JFileChooser()
        filter = FileNameExtensionFilter("c files", ["c"])
        filechooser.addChoosableFileFilter(filter)
        ret = filechooser.showDialog(self.panel, "Elegir fichero")
        if ret == JFileChooser.APPROVE_OPTION:
            file = filechooser.getSelectedFile()
            text = self.readFile(file)
            self.area.setText(text)

    def readFile(self, file):
        filename = file.getCanonicalPath()
        self.filename = filename
        f = open(filename, "r")
        text = f.read()
        return text

    def ejecutar(self, e):
        JOptionPane.showMessageDialog(self.panel,
                                      "Ejecutando...\n Espere unos minutos.",
                                      "Info", JOptionPane.INFORMATION_MESSAGE)
        print("Ejecutando...")
        url = self.textfieldURL.getText()
        fichero = self.area.getText()
        urls_finales = ''

        if url == '' and fichero == '':
            self.error()
            return
        elif url != '' and fichero != '':
            print("Hay url y fichero")
            urls_finales = url + "\n" + fichero
            #self.writeFile(urls,1)

        elif fichero != '':
            print("Hay fichero")
            urls_finales = fichero
            #self.writeFile(fichero,1)

        elif url != '':
            print("Hay url")
            self.filename = "url"
            urls_finales = url
            #self.writeFile(url,1)

        else:
            print("Ha habido un error")

        self.writeFile(urls_finales, 1)
        f = open("bbdd.txt", "w")
        f.write(self.filename + "1\n")
        f.close()
        subprocess.call("python demo.py", shell=True)
        self.writeFile(urls_finales, 2)
        f = open("bbdd.txt", "a")
        f.write(self.filename + "2")
        f.close()
        subprocess.call("python demo.py", shell=True)
        subprocess.call("python rastreo_analisis.py", shell=True)

        self.initResultados()

    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)

    def readResultados(self):
        count = 0
        f = open("resultados.txt", "r")
        resultados = f.read()
        self.areaResultados.setText(resultados)

        for linea in f:
            self.lineas.append(linea)
            count += 1

        return count

    def writeFile(self, urls, crawl):
        self.filename = self.filename.replace(".txt", '')
        f = open("URLs.txt", "w")
        f.write(self.filename + str(crawl) + ".txt" + '\n')
        f.write(urls)
        f.close()

    def error(self):
        JOptionPane.showMessageDialog(self.panel,
                                      "Debes introducir una URL o un fichero",
                                      "Error", JOptionPane.ERROR_MESSAGE)
Beispiel #34
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, DocumentListener, ChangeListener):

    #
    # implement IBurpExtender
    #
    def	registerExtenderCallbacks(self, callbacks):
        print "PhantomJS RIA Crawler extension"
        print "Nikolay Matyunin @autorak <*****@*****.**>"

        # keep a reference to our callbacks object and helpers object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # extension name
        callbacks.setExtensionName("Phantom RIA Crawler")

        # Create Tab UI components
        self._jPanel = JPanel()
        self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT)
        _titleLabelFont = _titleLabel.font
        _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12);
        _titleLabel.setFont(_titleLabelFont);
        _titleLabel.setForeground(Color(230, 142, 11))

        self._addressTextField = JTextField('')
        self._addressTextField.setColumns(50)
        _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT)
        self._addressTextField.getDocument().addDocumentListener(self)

        self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value
        self._phantomJsPathField.setColumns(50)
        _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT)

        self._startButton = JToggleButton('Start', actionPerformed=self.startToggled)
        self._startButton.setEnabled(False)

        _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT)
        self._requestsMadeInfo = JLabel("", SwingConstants.LEFT)
        _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT)
        self._statesFoundInfo = JLabel("", SwingConstants.LEFT)

        _separator = JSeparator(SwingConstants.HORIZONTAL)

        _configLabel = JLabel("Crawling configuration:")
        self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked)
        self._configFile = ""

        _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT)
        self._listenersCombo = JComboBox()
        self._configTimer = Timer(5000, None)
        self._configTimer.actionPerformed = self._configUpdated
        self._configTimer.stop()
        self._configUpdated(None)

        self._commandClient = CommandClient(self)

        # Layout management
        self._groupLayout = GroupLayout(self._jPanel)
        self._jPanel.setLayout(self._groupLayout)
        self._groupLayout.setAutoCreateGaps(True)
        self._groupLayout.setAutoCreateContainerGaps(True)

        self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_addressTextLabel)
                .addGroup(self._groupLayout.createParallelGroup()
                    .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_requestsMadeLabel)
                        .addComponent(self._requestsMadeInfo))
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_statesFoundLabel)
                        .addComponent(self._statesFoundInfo)))
                .addComponent(self._startButton))
            .addComponent(_separator)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
        )

        self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_addressTextLabel)
                .addComponent(self._addressTextField)
                .addComponent(self._startButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_requestsMadeLabel)
                .addComponent(self._requestsMadeInfo))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_statesFoundLabel)
                .addComponent(self._statesFoundInfo))
            .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo))
        )

        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel);


        # context menu data
        self._contextMenuData = None;
        self._running = False;

        # register callbacks
        callbacks.customizeUiComponent(self._jPanel)
        callbacks.registerContextMenuFactory(self)
        callbacks.addSuiteTab(self)

        return

    #
    # implement ITab and Tab ChangeListener
    #
    def getTabCaption(self):
        return "Phantom RIA Crawler"
    def getUiComponent(self):
        return self._jPanel
    def stateChanged(self, ev):
        self._configUpdated()

    def _configUpdated(self, ev):
        config = self._callbacks.saveConfig()

        # update proxy listeners
        index = 0
        listeners = DefaultComboBoxModel()
        while (("proxy.listener" + str(index)) in config):
            listenerItem = config["proxy.listener" + str(index)]
            listenerItems = listenerItem.split(".")
            if (listenerItems[0] == "1"):
                address = ".".join(listenerItems[2][1:].split("|"))
                if (len(address) == 0):
                    address = "127.0.0.1"
                listeners.addElement(address + " : " + listenerItems[1])

            index = index + 1
        self._listenersCombo.setModel(listeners)
        return;

    #
    # implement button actions
    #
    def startToggled(self, ev):
        if (self._startButton.getModel().isSelected()):
            try:
                os.chdir(sys.path[0] + os.sep + "riacrawler" + os.sep + "scripts")
            except Exception as e:
                print >> sys.stderr, "RIA crawler scripts loading error", "I/O error({0}): {1}".format(e.errno, e.strerror)
                self._startButton.setSelected(False)
                return

            phantomJsPath = self._phantomJsPathField.text
            target = self._addressTextField.text

            config = "crawler.config"
            if (self._configFile):
                config = self._configFile

            listenerAddress = self._listenersCombo.getSelectedItem().replace(" ", "")
            p = Popen("{0} --proxy={3} main.js --target={1} --config={2}".format(phantomJsPath, target, config, listenerAddress), shell=True)
            self._running = True
            self._requestsMadeInfo.setText("")
            self._statesFoundInfo.setText("")
            self._commandClient.startCrawling()
        else:
            if (self._running):
                self._commandClient.stopCrawling()
            self._running = False

    def syncCrawlingState(self, result):
        print "RIA crawling state: ", result
        self._requestsMadeInfo.setText(str(result["requests_made"]))
        self._statesFoundInfo.setText(str(result["states_detected"]))
        if (result["running"] == False):
            self._commandClient.stopCrawling()
            self._running = False
            self._startButton.setSelected(False)

    def loadConfigClicked(self, ev):
        openFile = JFileChooser();
        openFile.showOpenDialog(None);
        self._configFile = openFile.getSelectedFile()

    #
    # implement DocumentListener for _addressTextField
    #
    def removeUpdate(self, ev):
        self.updateStartButton()
    def insertUpdate(self, ev):
        self.updateStartButton()
    def updateStartButton(self):
        self._startButton.setEnabled(len(self._addressTextField.text) > 0)


    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, contextMenuInvocation):
        menuItemList = ArrayList()

        context = contextMenuInvocation.getInvocationContext()
        if (context == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST or context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or
            context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY or context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE):

            self._contextMenuData = contextMenuInvocation.getSelectedMessages()
            menuItemList.add(JMenuItem("Send to Phantom RIA Crawler", actionPerformed = self.menuItemClicked))

        return menuItemList


    def menuItemClicked(self, event):
        if (self._running == True):
            self._callbacks.issueAlert("Can't set data to Phantom RIA Crawler: crawling is running already.")
            return;

        dataIsSet = False;
        for message in self._contextMenuData:
            request = self._helpers.analyzeRequest(message)

            url = request.getUrl().toString()
            print url
            if (url):
                dataisSet = True;
                self._addressTextField.setText(url)
Beispiel #35
0
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        print "Loading..."

        self._callbacks = callbacks
        self._callbacks.setExtensionName('Burp SSL Scanner')
        # self._callbacks.registerScannerCheck(self)
        # self._callbacks.registerExtensionStateListener(self)
        self._helpers = callbacks.getHelpers()

        # initialize the main scanning event and thread
        self.scanningEvent = Event()
        self.scannerThread = None
        self.targetURL = None

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20))
        
        # sub split pane (top)
        self._topPanel = JPanel(BorderLayout(10, 10))
        self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0))

        # Setup Panel :    [Target: ] [______________________] [START BUTTON]
        self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.setupPanel.add(
            JLabel("Target:", SwingConstants.LEFT), BorderLayout.LINE_START)

        self.hostField = JTextField('', 50)
        self.setupPanel.add(self.hostField)

        self.toggleButton = JButton(
            'Start scanning', actionPerformed=self.startScan)
        self.setupPanel.add(self.toggleButton)

        if 'Professional' in callbacks.getBurpVersion()[0] :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap', True)
        else :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap (requires Professional version)', False)
            self.addToSitemapCheckbox.setEnabled(False)
        self.setupPanel.add(self.addToSitemapCheckbox)

        self.scanSiteMapHostCheckbox = JCheckBox('Scan sitemap hosts', True)
        self.setupPanel.add(self.scanSiteMapHostCheckbox)

        self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START)
        
        # Status bar
        self.scanStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.scanStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT))

        self.scanStatusLabel = JLabel("Ready to scan", SwingConstants.LEFT)
        self.scanStatusPanel.add(self.scanStatusLabel)

        self._topPanel.add(self.scanStatusPanel, BorderLayout.LINE_START)

        self._splitpane.setTopComponent(self._topPanel)

        # bottom panel 
        self._bottomPanel = JPanel(BorderLayout(10, 10))
        self._bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0))

        self.initialText = ('<h1 style="color: red;">Burp SSL Scanner<br />'
                            'Please note that TLS1.3 is still not supported by this extension.</h1>')
        self.currentText = self.initialText

        self.textPane = JTextPane()
        self.textScrollPane = JScrollPane(self.textPane)
        self.textPane.setContentType("text/html")
        self.textPane.setText(self.currentText)
        self.textPane.setEditable(False)

        self._bottomPanel.add(self.textScrollPane, BorderLayout.CENTER)

        self.savePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))
        self.saveButton = JButton('Save to file', actionPerformed=self.saveToFile)
        self.saveButton.setEnabled(False)
        self.savePanel.add(self.saveButton)

        self.clearScannedHostButton = JButton('Clear scanned host', actionPerformed=self.clearScannedHost)
        self.savePanel.add(self.clearScannedHostButton)
        self.savePanel.add(JLabel("Clear hosts that were scanned by active scan to enable rescanning", SwingConstants.LEFT))

        self._bottomPanel.add(self.savePanel, BorderLayout.PAGE_END)

        self._splitpane.setBottomComponent(self._bottomPanel)

        callbacks.customizeUiComponent(self._splitpane)

        callbacks.addSuiteTab(self)
        
        print "SSL Scanner tab loaded"


        self.scannerMenu = ScannerMenu(self)
        callbacks.registerContextMenuFactory(self.scannerMenu)
        print "SSL Scanner custom menu loaded"


        self.scannerCheck = ScannerCheck(self, self.scanSiteMapHostCheckbox.isSelected)
        callbacks.registerScannerCheck(self.scannerCheck)
        print "SSL Scanner check registered"

        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
        scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']

        print(scanAccuracy, scanSpeed)

        self.scannedHost = []

        print 'SSL Scanner loaded'
        
    def startScan(self, ev) :

        host = self.hostField.text
        self.scanningEvent.set()
        if(len(host) == 0):
            return
        if host.find("://") == -1:
            host = "https://" + host 
        try:
            self.targetURL = URL(host)
            if(self.targetURL.getPort() == -1):
                self.targetURL = URL("https", self.targetURL.getHost(), 443, "/")
            self.hostField.setEnabled(False)
            self.toggleButton.setEnabled(False)
            self.saveButton.setEnabled(False)
            self.addToSitemapCheckbox.setEnabled(False)
            self.currentText = self.initialText
            self.textPane.setText(self.currentText)
            self.updateText("<h2>Scanning %s:%d</h2>" % (self.targetURL.getHost(), self.targetURL.getPort()))
            print("Scanning %s:%d" % (self.targetURL.getHost(), self.targetURL.getPort()))
            self.scannerThread = Thread(target=self.scan, args=(self.targetURL, ))
            self.scannerThread.start()
        except BaseException as e:
            self.saveButton.setEnabled(False)
            print(e)
            return

    def scan(self, url, usingBurpScanner=False):

        def setScanStatusLabel(text) :
            if not usingBurpScanner :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.scanStatusLabel.setText, 
                                    (text,)))
                                
        def updateResultText(text) :
            if not usingBurpScanner :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.updateText, (text, )))

        if usingBurpScanner :
            res = result.Result(url, self._callbacks, self._helpers, False)
        else :
            res = result.Result(url, self._callbacks, self._helpers, self.addToSitemapCheckbox.isSelected())

        host, port = url.getHost(), url.getPort()

        ### Get project configuration
        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        if 'scanner' in projectConfig:
            # scanAccuracy: minimise_false_negatives, normal, minimise_false_positives
            scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
            # scanSpeed: fast, normal, thorough
            scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']
        else:
            scanAccuracy = 'normal'
            scanSpeed = 'normal'

        updateResultText('<h2>Scanning speed: %s</h2> %s' % (scanSpeed, test_details.SCANNING_SPEED_INFO[scanSpeed]))
        updateResultText('<h2>Scanning accuracy: %s</h2> %s' % (scanAccuracy, test_details.SCANNING_ACCURACY_INFO[scanAccuracy]))

        try :
            setScanStatusLabel("Checking for supported SSL/TLS versions")
            con = connection_test.ConnectionTest(res, host, port, scanSpeed, scanAccuracy)
            con.start()
            conResultText = '<hr /><br /><h3>' + res.printResult('connectable') + '</h3>' + \
                '<ul><li>' + res.printResult('offer_ssl2') + '</li>' + \
                '<li>' + res.printResult('offer_ssl3') + '</li>' + \
                '<li>' + res.printResult('offer_tls10') + '</li>' + \
                '<li>' + res.printResult('offer_tls11') + '</li>' + \
                '<li>' + res.printResult('offer_tls12') + '</li></ul>'
            updateResultText(conResultText)

            
            if not res.getResult('connectable') :
                updateResultText("<h2>Scan terminated (Connection failed)</h2>")
                raise BaseException('Connection failed')

            setScanStatusLabel("Checking for supported cipher suites (This can take a long time)")
            supportedCipher = supportedCipher_test.SupportedCipherTest(res, host, port, scanSpeed, scanAccuracy)
            supportedCipher.start()

            
            setScanStatusLabel("Checking for Cipherlist")
            cipher = cipher_test.CipherTest(res, host, port, scanSpeed, scanAccuracy)
            cipher.start()
            cipherResultText = '<h3>Available ciphers:</h3>' + \
                '<ul><li>' + res.printResult('cipher_NULL') + '</li>' + \
                '<li>' + res.printResult('cipher_ANON') + '</li>' + \
                '<li>' + res.printResult('cipher_EXP') + '</li>' + \
                '<li>' + res.printResult('cipher_LOW') + '</li>' + \
                '<li>' + res.printResult('cipher_WEAK') + '</li>' + \
                '<li>' + res.printResult('cipher_3DES') + '</li>' + \
                '<li>' + res.printResult('cipher_HIGH') + '</li>' + \
                '<li>' + res.printResult('cipher_STRONG') + '</li></ul>' 
            updateResultText(cipherResultText)
            

            setScanStatusLabel("Checking for Heartbleed")
            heartbleed = heartbleed_test.HeartbleedTest(res, host, port, scanSpeed, scanAccuracy)
            heartbleed.start()
            heartbleedResultText = res.printResult('heartbleed')
            updateResultText(heartbleedResultText)
            

            setScanStatusLabel("Checking for CCS Injection")
            ccs = ccs_test.CCSTest(res, host, port, scanSpeed, scanAccuracy)
            ccs.start()
            ccsResultText = res.printResult('ccs_injection')
            updateResultText(ccsResultText)

            
            setScanStatusLabel("Checking for TLS_FALLBACK_SCSV")
            fallback = fallback_test.FallbackTest(res, host, port, scanSpeed, scanAccuracy)
            fallback.start()
            fallbackResultText = res.printResult('fallback_support')
            updateResultText(fallbackResultText)


            setScanStatusLabel("Checking for POODLE (SSLv3)")
            poodle = poodle_test.PoodleTest(res, host, port, scanSpeed, scanAccuracy)
            poodle.start()
            poodleResultText = res.printResult('poodle_ssl3')
            updateResultText(poodleResultText)
            

            setScanStatusLabel("Checking for SWEET32")
            sweet32 = sweet32_test.Sweet32Test(res, host, port, scanSpeed, scanAccuracy)
            sweet32.start()
            sweet32ResultText = res.printResult('sweet32')
            updateResultText(sweet32ResultText)
            

            setScanStatusLabel("Checking for DROWN")
            drown = drown_test.DrownTest(res, host, port, scanSpeed, scanAccuracy)
            drown.start()
            drownResultText = res.printResult('drown')
            updateResultText(drownResultText)
            

            setScanStatusLabel("Checking for FREAK")
            freak = freak_test.FreakTest(res, host, port, scanSpeed, scanAccuracy)
            freak.start()
            freakResultText = res.printResult('freak')
            updateResultText(freakResultText)
            

            setScanStatusLabel("Checking for LUCKY13")
            lucky13 = lucky13_test.Lucky13Test(res, host, port, scanSpeed, scanAccuracy)
            lucky13.start()
            lucky13ResultText = res.printResult('lucky13')
            updateResultText(lucky13ResultText)
            

            setScanStatusLabel("Checking for CRIME")
            crime = crime_test.CrimeTest(res, host, port, scanSpeed, scanAccuracy)
            crime.start()
            crimeResultText = res.printResult('crime_tls')
            updateResultText(crimeResultText)
            

            setScanStatusLabel("Checking for BREACH")
            breach = breach_test.BreachTest(res, host, port, scanSpeed, scanAccuracy)
            breach.start(self._callbacks, self._helpers)
            breachResultText = res.printResult('breach')
            updateResultText(breachResultText)


            setScanStatusLabel("Checking for BEAST")
            beast = beast_test.BeastTest(res, host, port, scanSpeed, scanAccuracy)
            beast.start()
            beastResultText = res.printResult('beast')
            updateResultText(beastResultText)


            setScanStatusLabel("Checking for LOGJAM")
            logjam = logjam_test.LogjamTest(res, host, port, scanSpeed, scanAccuracy)
            logjam.start()
            logjamResultText = res.printResult('logjam_export') + '<br />' + res.printResult('logjam_common') 
            updateResultText(logjamResultText)
            

            updateResultText('<h2>Finished scanning</h2><br /><hr /><br /><h2>Summary</h2>')

            updateResultText('<h2>Supported ciphers (by Protocol)</h2>')
            updateResultText(res.printCipherList())
            updateResultText('<h2>Supported ciphers (by Vulnerability)</h2>')
            updateResultText(res.printCipherListByVulns())

            updateResultText('<h2>Issues found</h2>')
            updateResultText(res.printAllIssue())

        except BaseException as e :
            print(e)
            setScanStatusLabel("An error occurred. Please refer to the output/errors tab for more information.")
            time.sleep(2)

        if usingBurpScanner :
            return res.getAllIssue()
        else :
            self.scanningEvent.clear()
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.toggleButton.setEnabled, (True, ))
            )
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.hostField.setEnabled, (True, ))
            )
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.saveButton.setEnabled, (True, ))
            )
            if 'Professional' in self._callbacks.getBurpVersion()[0] :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.addToSitemapCheckbox.setEnabled, (True, ))
                )
            setScanStatusLabel("Ready to scan")
        print("Finished scanning")

    def updateText(self, stringToAppend):
        self.currentText += ('<br />' + stringToAppend)
        self.textPane.setText(self.currentText)

    def saveToFile(self, event):
        fileChooser = JFileChooser()
        if not (self.targetURL is None):
            fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result_%s.html" \
                % (self.targetURL.getHost())))
        else:
            fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result.html"))
        if (fileChooser.showSaveDialog(self.getUiComponent()) == JFileChooser.APPROVE_OPTION):
            fw = FileWriter(fileChooser.getSelectedFile())
            fw.write(self.textPane.getText())
            fw.flush()
            fw.close()
            print "Saved results to disk"

    def clearScannedHost(self, event) :
        self.scannedHost = []

    def addHostToScannedList(self, host, port) :
        self.scannedHost.append([host, port])

    def getTabCaption(self):
        return "SSL Scanner"

    def getUiComponent(self):
        return self._splitpane
Beispiel #36
0
class NewZoneDialog(JDialog, ActionListener, WindowListener):
    """Dialog for favourite zone editing
    """
    def __init__(self, parent, title, modal, app):
        from java.awt import CardLayout
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

        info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone"))
        info.setAlignmentX(Component.LEFT_ALIGNMENT)

        #Name
        nameLbl = JLabel(self.app.strings.getString("fav_zone_name"))
        self.nameTextField = JTextField(20)
        self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize())
        self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip"))
        namePanel = JPanel()
        namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS))
        namePanel.add(nameLbl)
        namePanel.add(Box.createHorizontalGlue())
        namePanel.add(self.nameTextField)

        #Country
        countryLbl = JLabel(self.app.strings.getString("fav_zone_country"))
        self.countryTextField = JTextField(20)
        self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize())
        self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip"))
        countryPanel = JPanel()
        countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS))
        countryPanel.add(countryLbl)
        countryPanel.add(Box.createHorizontalGlue())
        countryPanel.add(self.countryTextField)

        #Type
        modeLbl = JLabel(self.app.strings.getString("fav_zone_type"))
        RECTPANEL = "rectangle"
        POLYGONPANEL = "polygon"
        BOUNDARYPANEL = "boundary"
        self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL]
        modesComboModel = DefaultComboBoxModel()
        for i in (self.app.strings.getString("rectangle"),
                  self.app.strings.getString("delimited_by_a_closed_way"),
                  self.app.strings.getString("delimited_by_an_administrative_boundary")):
            modesComboModel.addElement(i)
        self.modesComboBox = JComboBox(modesComboModel,
                                       actionListener=self,
                                       editable=False)

        #- Rectangle
        self.rectPanel = JPanel()
        self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS))

        capturePane = JPanel()
        capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS))
        capturePane.setAlignmentX(Component.LEFT_ALIGNMENT)

        josmP = JPanel()
        self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area"))
        self.captureRBtn.addActionListener(self)
        self.captureRBtn.setSelected(True)
        self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"),
                                       actionPerformed=self.on_bboxFromJosmBtn_clicked)
        self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip"))
        josmP.add(self.bboxFromJosmBtn)
        capturePane.add(self.captureRBtn)
        capturePane.add(Box.createHorizontalGlue())
        capturePane.add(self.bboxFromJosmBtn)

        manualPane = JPanel()
        manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS))
        manualPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox"))
        self.manualRBtn.addActionListener(self)
        self.bboxTextField = JTextField(20)
        self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize())
        self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip"))
        self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder()
        self.bboxTextField.getDocument().addDocumentListener(TextListener(self))
        manualPane.add(self.manualRBtn)
        manualPane.add(Box.createHorizontalGlue())
        manualPane.add(self.bboxTextField)

        group = ButtonGroup()
        group.add(self.captureRBtn)
        group.add(self.manualRBtn)

        previewPane = JPanel()
        previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS))
        previewPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"),
                                     editable=0,
                                     border=None)
        bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize())
        self.bboxPreviewTextField = JTextField(20,
                                               editable=0,
                                               border=None)
        self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize())
        previewPane.add(bboxPreviewInfo)
        previewPane.add(Box.createHorizontalGlue())
        previewPane.add(self.bboxPreviewTextField)

        self.rectPanel.add(capturePane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.rectPanel.add(manualPane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 20)))
        self.rectPanel.add(previewPane)

        #- Polygon (closed way) drawn by hand
        self.polygonPanel = JPanel(BorderLayout())
        self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS))

        polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info"))
        polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC))
        polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        editPolyPane = JPanel()
        editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"),
                              actionPerformed=self.create_new_zone_editing_layer)
        editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip"))
        editPolyPane.add(editPolyBtn)

        self.polygonPanel.add(polyInfo)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.polygonPanel.add(editPolyPane)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))

        #- Administrative Boundary
        self.boundaryPanel = JPanel()
        self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS))

        boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info"))
        boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC))
        boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5))
        boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        boundaryTagsPanel.add(JLabel("name ="))
        self.nameTagTextField = JTextField(20)
        boundaryTagsPanel.add(self.nameTagTextField)
        boundaryTagsPanel.add(JLabel("admin_level ="))
        self.adminLevelTagTextField = JTextField(20)
        self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip"))
        boundaryTagsPanel.add(self.adminLevelTagTextField)
        boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag")))
        self.optionalTagTextField = JTextField(20)
        self.optionalTagTextField.setToolTipText("key=value")
        boundaryTagsPanel.add(self.optionalTagTextField)

        downloadBoundariesPane = JPanel()
        downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"),
                                        actionPerformed=self.on_downloadBoundariesBtn_clicked)
        downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip"))
        downloadBoundariesPane.add(downloadBoundariesBtn)

        self.boundaryPanel.add(boundaryInfo)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.boundaryPanel.add(boundaryTagsPanel)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.boundaryPanel.add(downloadBoundariesPane)

        self.editingPanels = {"rectangle": self.rectPanel,
                              "polygon": self.polygonPanel,
                              "boundary": self.boundaryPanel}

        #Main buttons
        self.okBtn = JButton(self.app.strings.getString("OK"),
                             ImageProvider.get("ok"),
                             actionPerformed=self.on_okBtn_clicked)
        self.cancelBtn = JButton(self.app.strings.getString("cancel"),
                                 ImageProvider.get("cancel"),
                                 actionPerformed=self.close_dialog)
        self.previewBtn = JButton(self.app.strings.getString("Preview_zone"),
                                  actionPerformed=self.on_previewBtn_clicked)
        self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip"))
        okBtnSize = self.okBtn.getPreferredSize()
        viewBtnSize = self.previewBtn.getPreferredSize()
        viewBtnSize.height = okBtnSize.height
        self.previewBtn.setPreferredSize(viewBtnSize)

        #layout
        self.add(info)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        namePanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(namePanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(countryPanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(modeLbl)
        self.add(Box.createRigidArea(Dimension(0, 5)))

        self.add(self.modesComboBox)
        self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        self.configPanel = JPanel(CardLayout())
        self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self.configPanel.add(self.rectPanel, RECTPANEL)
        self.configPanel.add(self.polygonPanel, POLYGONPANEL)
        self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL)
        self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(self.configPanel)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        buttonsPanel.add(self.previewBtn)
        buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(buttonsPanel)

        self.addWindowListener(self)
        self.pack()

    def update_gui_from_preferences(self):
        self.nameTextField.setText(self.app.newZone.name)
        #Reset rectangle mode
        bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox])
        self.bboxTextField.setText(bboxStr)
        self.bboxPreviewTextField.setText(bboxStr)
        self.bboxFromJosmBtn.setEnabled(True)
        self.bboxTextField.setEnabled(False)

        #Reset polygon mode
        self.polygonAsString = ""

        #Reset boundary mode
        self.boundaryAsString = ""

        self.modesComboBox.setSelectedIndex(0)

    def actionPerformed(self, e):
        #Show the panel for configuring the favourite area of the
        #selected type
        if e.getSource() == self.modesComboBox:
            cl = self.configPanel.getLayout()
            selectedMode = self.modesStrings[self.modesComboBox.selectedIndex]
            cl.show(self.configPanel, selectedMode)
        #Activate bbox input for rectangular favourite zone mode
        elif e.getSource() == self.captureRBtn:
            self.bboxFromJosmBtn.setEnabled(True)
            self.bboxTextField.setEnabled(False)
        else:
            self.bboxFromJosmBtn.setEnabled(False)
            self.bboxTextField.setEnabled(True)

    def on_bboxFromJosmBtn_clicked(self, widget):
        """Read bbox currently shown in JOSM
        """
        bbox = self.app.get_frame_bounds()
        self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox]))

### Manage layer for creating a new favourite zone from polygon or boundary
    def create_new_zone_editing_layer(self, e=None):
        """Open a new dataset where the user can draw a closed way to
           delimit the favourite area
        """
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.setActiveLayer(layer)
        else:
            Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None))
        Main.main.parent.toFront()

    def get_new_zone_editing_layer(self):
        """Check if the layer for editing the favourite area yet exists
        """
        for layer in self.app.mv.getAllLayers():
            if layer.getName() == self.FAVAREALAYERNAME:
                return layer
        return None

    def remove_new_zone_editing_layer(self):
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.removeLayer(layer)

    def on_zone_edited(self):
        """Read ways that delimit the favourite area and convert them to
           jts geometry
        """
        if self.modesComboBox.getSelectedIndex() == 0:
            mode = "rectangle"
        elif self.modesComboBox.getSelectedIndex() == 1:
            mode = "polygon"
        elif self.modesComboBox.getSelectedIndex() == 2:
            mode = "boundary"

        if mode in ("polygon", "boundary"):
            layer = self.get_new_zone_editing_layer()
            if layer is not None:
                self.app.mv.setActiveLayer(layer)
            else:
                if mode == "polygon":
                    msg = self.app.strings.getString("polygon_fav_layer_missing_msg")
                else:
                    msg = self.app.strings.getString("boundary_fav_layer_missing_msg")
                JOptionPane.showMessageDialog(self,
                                              msg,
                                              self.app.strings.getString("Warning"),
                                              JOptionPane.WARNING_MESSAGE)
                return

            dataset = self.app.mv.editLayer.data
            areaWKT = self.read_area_from_osm_ways(mode, dataset)
            if areaWKT is None:
                print "I could not read the new favourite area."
            else:
                if mode == "polygon":
                    self.polygonAsString = areaWKT
                else:
                    self.boundaryAsString = areaWKT
        return mode

    def read_area_from_osm_ways(self, mode, dataset):
        """Read way in favourite area editing layer and convert them to
           WKT
        """
        converter = JTSConverter(False)
        lines = [converter.convert(way) for way in dataset.ways]
        polygonizer = Polygonizer()
        polygonizer.add(lines)
        polygons = polygonizer.getPolygons()
        multipolygon = GeometryFactory().createMultiPolygon(list(polygons))
        multipolygonWKT = WKTWriter().write(multipolygon)
        if multipolygonWKT == "MULTIPOLYGON EMPTY":
            if mode == "polygon":
                msg = self.app.strings.getString("empty_ways_polygon_msg")
            else:
                msg = self.app.strings.getString("empty_ways_boundaries_msg")
            JOptionPane.showMessageDialog(self,
                msg,
                self.app.strings.getString("Warning"),
                JOptionPane.WARNING_MESSAGE)
            return
        return multipolygonWKT

    def on_downloadBoundariesBtn_clicked(self, e):
        """Download puter ways of administrative boundaries from
           Overpass API
        """
        adminLevel = self.adminLevelTagTextField.getText()
        name = self.nameTagTextField.getText()
        optional = self.optionalTagTextField.getText()
        if (adminLevel, name, optional) == ("", "", ""):
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("enter_a_tag_msg"),
                                          self.app.strings.getString("Warning"),
                                          JOptionPane.WARNING_MESSAGE)
            return
        optTag = ""
        if optional.find("=") != -1:
            if len(optional.split("=")) == 2:
                key, value = optional.split("=")
                optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"),
                                          URLEncoder.encode(value.replace(" ", "%20"), "UTF-8"))
        self.create_new_zone_editing_layer()
        overpassurl = 'http://127.0.0.1:8111/import?url='
        overpassurl += 'http://overpass-api.de/api/interpreter?data='
        overpassquery = 'relation["admin_level"="%s"]' % adminLevel
        overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8")
        overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag
        overpassurl += overpassquery.replace(" ", "%20")
        print overpassurl
        self.app.send_to_josm(overpassurl)

### Buttons ############################################################
    def create_new_zone(self, mode):
        """Read data entered on gui and create a new zone
        """
        name = self.nameTextField.getText()
        country = self.countryTextField.getText().upper()

        #error: name
        if name.replace(" ", "") == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("missing_name_warning"),
                                          self.app.strings.getString("missing_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False
        if name in [z.name for z in self.app.tempZones]:
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("duplicate_name_warning"),
                                          self.app.strings.getString("duplicate_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #zone type
        zType = mode
        #error: geometry type not defined
        if zType == "polygon" and self.polygonAsString == ""\
            or zType == "boundary" and self.boundaryAsString == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("zone_not_correctly_build_warning"),
                                          self.app.strings.getString("zone_not_correctly_build_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #geometry string
        if zType == "rectangle":
            geomString = self.bboxPreviewTextField.getText()
        elif zType == "polygon":
            geomString = self.polygonAsString
        else:
            geomString = self.boundaryAsString

        self.app.newZone = Zone(self.app, name, zType, geomString, country)
        #self.app.newZone.print_info()
        return True

    def on_okBtn_clicked(self, event):
        """Add new zone to temp zones
        """
        mode = self.on_zone_edited()
        if self.create_new_zone(mode):
            self.app.tempZones.append(self.app.newZone)
            self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country,
                                                                    self.app.newZone.icon,
                                                                    self.app.newZone.name])
            maxIndex = len(self.app.tempZones) - 1
            self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex,
                                                                         maxIndex)
            self.close_dialog()
            self.app.preferencesFrame.check_removeBtn_status()
            self.app.preferencesFrame.zonesTable.scrollRectToVisible(
                self.app.preferencesFrame.zonesTable.getCellRect(
                    self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True))

    def on_previewBtn_clicked(self, e):
        """Show the favourite area on a map
        """
        mode = self.on_zone_edited()
        if not self.create_new_zone(mode):
            return
        zone = self.app.newZone

        if zone.zType == "rectangle":
            wktString = zone.bbox_to_wkt_string()
        else:
            wktString = zone.wktGeom
        script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/'
        script += '\nfunction init() {'
        script += '\n    var map = new OpenLayers.Map({'
        script += '\n        div: "map",'
        script += '\n        projection: new OpenLayers.Projection("EPSG:900913"),'
        script += '\n        displayProjection: new OpenLayers.Projection("EPSG:4326"),'
        script += '\n        layers: ['
        script += '\n            new OpenLayers.Layer.OSM()'
        script += '\n            ]'
        script += '\n    });'
        script += '\n    var wkt = new OpenLayers.Format.WKT();'
        script += '\n    var polygonFeature = wkt.read("%s");' % wktString
        script += '\n    var vectors = new OpenLayers.Layer.Vector("Favourite area");'
        script += '\n    map.addLayer(vectors);'
        script += '\n    polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());'
        script += '\n    vectors.addFeatures([polygonFeature]);'
        script += '\n    map.zoomToExtent(vectors.getDataExtent());'
        script += '\n};'
        scriptFile = open(File.separator.join([self.app.SCRIPTDIR,
                                              "html",
                                              "script.js"]), "w")
        scriptFile.write(script)
        scriptFile.close()
        OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR,
                                                   "html",
                                                   "favourite_area.html"]))

    def windowClosing(self, windowEvent):
        self.close_dialog()

    def close_dialog(self, e=None):
        #delete favourite zone editing layer if present
        self.remove_new_zone_editing_layer()
        self.dispose()
        self.app.preferencesFrame.setEnabled(True)
        self.app.preferencesFrame.toFront()
Beispiel #37
0
    def __init__(self, pP):
        '''
        Constructor
        '''
        self.pP = pP
        self.annotationType = self.pP.getAnnotationType()
        
        self.setTitle("Random Picture Picker")

        #annotation Panel
        annoPanel = JPanel()
        annoPanel.setBorder(BorderFactory.createTitledBorder("Annotations"))
        annoPLayout = GroupLayout(annoPanel)
        annoPanel.setLayout(annoPLayout)
        annoPLayout.setAutoCreateContainerGaps(True)
        annoPLayout.setAutoCreateGaps(True)        

        # dynamic creation of annotation panel
        # yesNoIgnore, int, number, list
        if len(self.pP.getAnnotationType()) == 1:
            self.annoField = JTextField("", 16)
            annoPLayout.setHorizontalGroup(annoPLayout.createParallelGroup().addComponent(self.annoField))
            annoPLayout.setVerticalGroup(annoPLayout.createSequentialGroup().addComponent(self.annoField))
        elif len(self.pP.getAnnotationType()) > 1:
            choices = pP.getAnnotationType()
            print "choices", choices
            choiceBtns = []
            self.annoField = ButtonGroup()
            for c in choices:
                Btn = JRadioButton(c, actionCommand=c)
                self.annoField.add(Btn)
                choiceBtns.append(Btn)
          
            h = annoPLayout.createParallelGroup()
            for b in choiceBtns:
                h.addComponent(b)
            annoPLayout.setHorizontalGroup(h)
            
            v = annoPLayout.createSequentialGroup()
            for b in choiceBtns:
                v.addComponent(b)
            annoPLayout.setVerticalGroup(v)


        # Control Panel
        ctrlPanel = JPanel()
        ctrlPLayout = GroupLayout(ctrlPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        ctrlPanel.setLayout(ctrlPLayout)
        
        nextImgButton = JButton("Next >", actionPerformed=self.nextPicture)
        prevImgButton = JButton("< Prev", actionPerformed=self.pP.prevPicture)
        quitButton = JButton("Quit", actionPerformed=self.exit)

        ctrlPLayout.setHorizontalGroup(ctrlPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                       .addGroup(ctrlPLayout.createSequentialGroup()
                                                 .addComponent(prevImgButton)
                                                 .addComponent(nextImgButton))
                                       .addComponent(quitButton))
        ctrlPLayout.setVerticalGroup(ctrlPLayout.createSequentialGroup()
                                     .addGroup(ctrlPLayout.createParallelGroup()
                                               .addComponent(prevImgButton)
                                               .addComponent(nextImgButton))
                                     .addComponent(quitButton))
        ctrlPLayout.linkSize(SwingConstants.HORIZONTAL, quitButton)

        
        statusPanel = JPanel()   # contains status information: progress bar
        self.progressBar = JProgressBar()
        self.progressBar.setStringPainted(True)
        self.progressBar.setValue(0)
        statusPanel.add(self.progressBar)
        
        #MainLayout
        mainLayout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(mainLayout)
        
        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.setVerticalGroup(mainLayout.createSequentialGroup()
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.linkSize(SwingConstants.HORIZONTAL, annoPanel, ctrlPanel, statusPanel)
         
      
        self.pack()
        self.setVisible(True)
        
        self.pP.nextPicture()
class JythonGui(object):
    def __init__(self, instructionsURI=""):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger("sasi_gridder_gui")
        self.logger.addHandler(logging.StreamHandler())

        def log_fn(msg):
            self.log_msg(msg)

        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
        self.frame.size = (650, 600)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1

        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
            actionPerformed=self.browseInstructions,
        )
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
        instructionsButton.setBorderPainted(False)
        instructionsButton.setOpaque(False)
        instructionsButton.setBackground(Color.WHITE)
        instructionsButton.setToolTipText(self.instructionsURI)
        self.top_panel.add(instructionsButton)

        # Select input elements.
        self.top_panel.add(getStageLabel("Select an input data folder:"))
        self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))

        # Select output elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # Run elements.
        self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        self.outputChooser = JFileChooser()
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
        defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
        self.outputChooser.setSelectedFile(File(defaultOutputFile))

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)
        return

    def log_msg(self, msg):
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg("Selected '%s' as output." % self.selected_output_file.path)

    def runSASIGridder(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            try:
                input_dir = self.selected_input_file.path
                output_path = self.selected_output_file.path

                grid_path = os.path.join(input_dir, "grid", "grid.shp")

                stat_areas_path = os.path.join(input_dir, "stat_areas", "stat_areas.shp")

                raw_efforts_path = os.path.join(input_dir, "raw_efforts.csv")

                gear_mappings_path = os.path.join(input_dir, "gear_mappings.csv")

                gear_mappings = {}
                with open(gear_mappings_path, "rb") as f:
                    r = csv.DictReader(f)
                    for mapping in r:
                        gear_mappings[mapping["trip_type"]] = mapping["gear_code"]

                task = SASIGridderTask(
                    grid_path=grid_path,
                    raw_efforts_path=raw_efforts_path,
                    stat_areas_path=stat_areas_path,
                    output_path=output_path,
                    logger=self.logger,
                    gear_mappings=gear_mappings,
                    effort_limit=None,
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
class JythonGui(ItemListener):
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger('sasi_runner_gui')
        self.logger.addHandler(logging.StreamHandler())
        def log_fn(msg):
            self.log_msg(msg)
        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame(
            "SASI Runner",
            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE,
        )
        self.frame.size = (650, 600,)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1
        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">'
             '<U>open instructions</U></FONT><HTML>'),
            actionPerformed=self.browseInstructions)
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT);
        instructionsButton.setBorderPainted(False);
        instructionsButton.setOpaque(False);
        instructionsButton.setBackground(Color.WHITE);
        instructionsButton.setToolTipText(self.instructionsURI);
        self.top_panel.add(instructionsButton)

        # 'Select input' elements.
        self.top_panel.add(getStageLabel(
            "Select a SASI .zip file or data folder:"))
        self.top_panel.add(
            JButton("Select input...", actionPerformed=self.openInputChooser))

        # 'Select output' elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(
            JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # 'Set result fields' elements.
        result_fields = [
            {'id': 'gear_id', 'label': 'Gear', 'selected': True, 
             'enabled': False}, 
            {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, 
            {'id': 'energy_id', 'label': 'Energy', 'selected': False},
            {'id': 'feature_id', 'label': 'Feature', 'selected': False}, 
            {'id': 'feature_category_id', 'label': 'Feature Category', 
             'selected': False}
        ]
        self.selected_result_fields = {}
        resolutionLabelPanel = JPanel(GridLayout(0,1))
        resolutionLabelPanel.add(getStageLabel("Set result resolution:"))
        resolutionLabelPanel.add(
            JLabel(("<html><i>This sets the specificity with which<br>"
                    "results will be grouped. Note that enabling<br>"
                    "more fields can *greatly* increase resulting<br>"
                    "output sizes and run times.</i>")))
        #self.top_panel.add(getStageLabel("Set result resolution:"))
        self.top_panel.add(resolutionLabelPanel)
        checkPanel = JPanel(GridLayout(0, 1))
        self.top_panel.add(checkPanel) 
        self.resultFieldCheckBoxes = {}
        for result_field in result_fields:
            self.selected_result_fields.setdefault(
                result_field['id'], result_field['selected'])
            checkBox = JCheckBox(
                result_field['label'], result_field['selected'])
            checkBox.setEnabled(result_field.get('enabled', True))
            checkBox.addItemListener(self)
            checkPanel.add(checkBox)
            self.resultFieldCheckBoxes[checkBox] = result_field

        # 'Run' elements.
        self.top_panel.add(getStageLabel("Run SASI: (this might take a while)"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASI)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(
            self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10,10,10,10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES

        self.outputChooser = JFileChooser()
        defaultOutputFile = os.path.join(System.getProperty("user.home"),
                                         "sasi_project.zip")

        self.outputChooser.setSelectedFile(File(defaultOutputFile));
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)

    def itemStateChanged(self, event):
        """ Listen for checkbox changes. """
        checkBox = event.getItemSelectable()
        is_selected = (event.getStateChange() == ItemEvent.SELECTED)
        result_field = self.resultFieldCheckBoxes[checkBox]
        self.selected_result_fields[result_field['id']] = is_selected

    def log_msg(self, msg):
        """ Print message to log and scroll to bottom. """
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            selectedPath = self.outputChooser.selectedFile.path
            if not selectedPath.endswith('.zip'):
                zipPath = selectedPath + '.zip'
                self.outputChooser.setSelectedFile(File(zipPath))
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg(
                "Selected '%s' as output." % self.selected_output_file.path)

    def runSASI(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():
            self.tmp_dir = tempfile.mkdtemp(prefix="sasi_runner.")
            self.db_file = os.path.join(self.tmp_dir, "sasi_runner.db")

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            def get_connection():
                engine = create_engine('h2+zxjdbc:////%s' % self.db_file)
                con = engine.connect()
                return con

            try:
                # Set result fields.
                result_fields = []
                for field_id, is_selected in self.selected_result_fields.items():
                    if is_selected: result_fields.append(field_id)

                task = RunSasiTask(
                    input_path=self.selected_input_file.path,
                    output_file=self.selected_output_file.path,
                    logger=self.logger,
                    get_connection=get_connection,
                    config={
                        'result_fields': result_fields,
                        'run_model': {
                            'run': {
                                'batch_size': 'auto',
                            }
                        },
                        'output': {
                            'batch_size': 'auto',
                        },
                    }
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

            try:
                shutil.rmtree(self.tmp_dir)
            except:
                pass

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
Beispiel #40
0
    def __init__(self,
                 kconfig_file="Kconfig",
                 config_file=".config",
                 systemLogger=None):
        """[summary]

        Parameters
        ----------
            kconfig_file : string (default: "Kconfig")
                The Kconfig configuration file
            config_file : string (default: ".config")
                The save file which will be used for loading and saving the settings
            systemLogger (default: None)
                A system logger object. If None then print statements are used for logging.
        """
        global log
        if systemLogger:
            log = systemLogger

        # Load Kconfig configuration files
        self.kconfig = Kconfig(kconfig_file)
        setKConfig(self.kconfig)

        if os.path.isfile(config_file):
            log.info(self.kconfig.load_config(config_file))
        elif os.path.isfile(".config"):
            log.info(self.kconfig.load_config(".config"))

        self.tree = KConfigTree(self.kconfig)
        self.tree.addTreeSelectionListener(self.treeSelectionChanged)
        jTreeSP = JScrollPane(self.tree)

        self.jta = JTextArea()
        self.jta.setEditable(False)
        jTextSP = JScrollPane(self.jta)

        toolPanel = JPanel()
        toolPanel.setLayout(BoxLayout(toolPanel, BoxLayout.X_AXIS))
        toolPanel.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0))

        toolPanel.add(JLabel("Search: "))

        jSearchPanel = JPanel()
        jSearchPanel.setLayout(BoxLayout(jSearchPanel, BoxLayout.X_AXIS))
        self.jSearchField = JTextField()
        jSearchPanel.setBackground(self.jSearchField.getBackground())
        jSearchPanel.setBorder(self.jSearchField.getBorder())
        self.jSearchField.setBorder(None)
        self.jSearchField.getDocument().addDocumentListener(
            SearchListener(self.tree))
        jSearchPanel.add(self.jSearchField)

        clearSearchButton = JButton(u'\u00d7',
                                    actionPerformed=self.clearSearch)
        d = clearSearchButton.getPreferredSize()
        clearSearchButton.setPreferredSize(Dimension(d.height, d.height))
        clearSearchButton.setBackground(self.jSearchField.getBackground())
        clearSearchButton.setBorder(None)
        clearSearchButton.setOpaque(False)
        clearSearchButton.setContentAreaFilled(False)
        clearSearchButton.setFocusPainted(False)
        jSearchPanel.add(clearSearchButton)

        toolPanel.add(jSearchPanel)

        self.showAllCheckBox = JCheckBox("Show all",
                                         actionPerformed=self.OnShowAllCheck)
        toolPanel.add(self.showAllCheckBox)

        splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, jTreeSP, jTextSP)
        splitPane.setOneTouchExpandable(True)
        splitPane.setDividerLocation(300)

        treePanel = JPanel(BorderLayout())
        treePanel.add(toolPanel, BorderLayout.NORTH)
        treePanel.add(splitPane, BorderLayout.CENTER)

        loadSavePanel = JPanel()
        loadSavePanel.setLayout(BoxLayout(loadSavePanel, BoxLayout.X_AXIS))
        loadSavePanel.add(
            JButton("Load", actionPerformed=self.loadConfigDialog))
        loadSavePanel.add(
            JButton("Save as", actionPerformed=self.writeConfigDialog))

        self.rootPanel = JPanel()
        self.rootPanel.setLayout(BorderLayout())
        self.rootPanel.add(loadSavePanel, BorderLayout.PAGE_START)
        self.rootPanel.add(treePanel, BorderLayout.CENTER)
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(
            BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- "                                                 + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- "                                                     + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- "                                           + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- "                                                          + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>"                                    )
        keyLable.setBorder(
            BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
    def showStackOverlayWindow(self):
        all = JPanel()
        all.setLayout(MigLayout())

        self.imageIDs = WindowManager.getIDList()
        self.imageNames = []

        if self.imageIDs is None:
            IJ.error("No open images", "Stack Overlay requires at least one image to be already open.")
            return

        for i in self.imageIDs:
            self.imageNames.append(WindowManager.getImage(i).getTitle())

        self.baseImageBox = JComboBox(self.imageNames)
        baseImageBoxLabel = JLabel("Base image")
        self.baseImageBox.setSelectedIndex(0)
        all.add(baseImageBoxLabel)
        all.add(self.baseImageBox, "wrap")

        self.overlayImageBox = JComboBox(self.imageNames)
        overlayImageBoxLabel = JLabel("Overlay image")
        if len(self.imageNames) > 1:
            self.overlayImageBox.setSelectedIndex(1)

        all.add(overlayImageBoxLabel)
        all.add(self.overlayImageBox, "wrap")

        all.add(JSeparator(SwingConstants.HORIZONTAL), "span, wrap")

        overlayStyleFrame = JPanel()
        overlayStyleFrame.setLayout(MigLayout())
        overlayStyleFrame.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Overlay Style"), BorderFactory.createEmptyBorder(5,5,5,5)))

        colorLabel = JLabel("Overlay color")
        self.overlayColorPreviewLabel = JLabel("           ")
        self.overlayColorPreviewLabel.setBorder(BorderFactory.createEmptyBorder(0,0,1,0))
        self.overlayColorPreviewLabel.setOpaque(True)
        self.overlayColorPreviewLabel.setBackground(Color.red)
        self.overlayColor = Color.red
        colorPicker = JColorChooser()
        colorPicker.setPreviewPanel(self.overlayColorPreviewLabel)
        colorButton = JButton("Select color...", actionPerformed=self.showColorChooser)

        opacityLabel = JLabel("Overlay opacity (%)")
        opacitySpinnerModel = SpinnerNumberModel(100, 0, 100, 1)
        self.opacitySpinner = JSpinner(opacitySpinnerModel)

        overlayStyleFrame.add(colorLabel)
        overlayStyleFrame.add(self.overlayColorPreviewLabel)
        overlayStyleFrame.add(colorButton, "wrap")

        overlayStyleFrame.add(opacityLabel)
        overlayStyleFrame.add(self.opacitySpinner, "wrap")
        

        all.add(overlayStyleFrame, "span, wrap")
        
        self.virtualStackCheckbox = JCheckBox("Use Virtual Stack", True)
        all.add(self.virtualStackCheckbox, "span, wrap")

        # TODO: add non-thermonuclear cancel button functionality
        overlayCancelButton = JButton("Cancel", actionPerformed=self.onQuit)
        overlayStartButton = JButton("Overlay images", actionPerformed=self.overlayImages)
        
        all.add(overlayCancelButton, "gapleft push")
        all.add(overlayStartButton, "gapleft push")

        self.frame = JFrame("Stack Overlay")
        self.frame.getContentPane().add(JScrollPane(all))
        self.frame.pack()
        self.frame.setLocationRelativeTo(None)
        self.frame.setVisible(True)
Beispiel #43
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorTabFactory):
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("HaE(Highlighter and Extractor)")
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        callbacks.registerHttpListener(self)
        callbacks.registerMessageEditorTabFactory(self)
        print 'HaE(Highlighter and Extractor)\nAuthor: Vulkey_Chen\nBlog: gh0st.cn\nTeam: MSTSEC'
        self._callbacks.customizeUiComponent(self.getUiComponent())
        self._callbacks.addSuiteTab(self)
        self.endColors = []

    def getTabCaption(self):
        return 'HaE'

    def createNewInstance(self, controller, editable):
        return MarkINFOTab(self, controller, editable)

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if messageIsRequest:
            return
        content = messageInfo.getResponse()
        # content 为响应正文信息
        info = getConfig()
        results = findContent(info, content)
        colorList = []
        if results != {}:
            for i in results:
                if info[i]['highlight'] == 1:
                    if info[i]['color'] == 'red':
                        messageInfo.setHighlight(info[i]['color'])
                        break
                    else:
                        colorList.append(info[i]['color'])

            if not messageInfo.getHighlight():
                colorsList = [colors.index(i) for i in colorList]
                colorsList.sort()
                # print(colorsList)
                self.helper(colorsList)
                endColor = [colors.index(x) for x in self.endColors]
                # print(endColor)
                messageInfo.setHighlight(colors[min(endColor)])

    # 颜色升级
    def helper(self, mylist):
        l = len(mylist)
        i = 0
        stack = []
        while i < l:
            if not stack:
                stack.append(mylist[i])
                i += 1
            else:
                if mylist[i] != stack[-1]:
                    stack.append(mylist[i])
                    i += 1
                else:
                    stack[-1] -= 1
                    i += 1

        if len(stack) == len(set(stack)):
            self.endColors = [colors[i] for i in stack]
        else:
            self.helper(stack)

    def addConfig(self, event):
        nameText = self.nameTextField.getText()
        regexText = self.regexTextField.getText()
        colorText = self.colorTextField.getText()
        isHighlight = int(self.highlightCheckBox.isSelected())
        isExtract = int(self.extractCheckBox.isSelected())
        if colorText in colors:
            with open(configFile, 'r+') as content:
                dicts = json.load(content)
                # 解决r+写入问题
                content.seek(0, 0)
                content.truncate()
                if nameText in dicts:
                    self.tipString.setText("Name is existed!")
                elif not (isHighlight or isExtract):
                    self.tipString.setText("Highlight or Extract?")
                else:
                    dicts[nameText] = {
                        "regex": regexText,
                        "highlight": isHighlight,
                        "extract": isExtract,
                        "color": colorText
                    }
                    content.write(jsbeautifier.beautify(json.dumps(dicts)))
                    #print(dicts)
                    self.tipString.setText("Save Successfully!")
        else:
            self.tipString.setText("Not in colors list.")

    def reloadConfig(self, event):
        with open(configFile, 'r') as content:
            self.configTextArea.setText(content.read())

    def getUiComponent(self):
        self.HaEPanel = JPanel()
        self.HaEPanel.setBorder(None)
        self.HaEPanel.setLayout(BorderLayout(0, 0))
        self.panel = JPanel()
        self.HaEPanel.add(self.panel, BorderLayout.NORTH)
        self.panel.setLayout(BorderLayout(0, 0))
        self.tabbedPane = JTabbedPane(JTabbedPane.TOP)
        self.panel.add(self.tabbedPane, BorderLayout.CENTER)
        self.setPanel = JPanel()
        self.tabbedPane.addTab("Set", None, self.setPanel, None)
        self.setPanel.setLayout(BorderLayout(0, 0))
        self.setPanel_1 = JPanel()
        self.setPanel.add(self.setPanel_1, BorderLayout.NORTH)
        self.nameString = JLabel("Name")
        self.setPanel_1.add(self.nameString)
        self.nameTextField = JTextField()
        self.setPanel_1.add(self.nameTextField)
        self.nameTextField.setColumns(10)
        self.regexString = JLabel("Regex")
        self.setPanel_1.add(self.regexString)
        self.regexTextField = JTextField()
        self.setPanel_1.add(self.regexTextField)
        self.regexTextField.setColumns(10)
        self.extractCheckBox = JCheckBox("Extract")
        self.setPanel_1.add(self.extractCheckBox)
        self.highlightCheckBox = JCheckBox("Highlight")
        self.setPanel_1.add(self.highlightCheckBox)
        self.setPanel_2 = JPanel()
        self.setPanel.add(self.setPanel_2)
        self.colorString = JLabel("Color")
        self.setPanel_2.add(self.colorString)
        self.colorTextField = JTextField()
        self.setPanel_2.add(self.colorTextField)
        self.colorTextField.setColumns(5)
        self.addBottun = JButton("Add", actionPerformed=self.addConfig)
        self.setPanel_2.add(self.addBottun)
        self.tipString = JLabel("")
        self.setPanel_2.add(self.tipString)
        self.configPanel = JPanel()
        self.tabbedPane.addTab("Config", None, self.configPanel, None)
        self.configPanel.setLayout(BorderLayout(0, 0))
        self.configString = JLabel("This is config file content.")
        self.configString.setHorizontalAlignment(SwingConstants.CENTER)
        self.configPanel.add(self.configString, BorderLayout.NORTH)
        self.configTextArea = JTextArea()
        self.configTextArea.setEnabled(False)
        self.configTextArea.setTabSize(4)
        self.configTextArea.setLineWrap(True)
        self.configTextArea.setRows(20)
        self.configPanel.add(self.configTextArea, BorderLayout.SOUTH)
        self.scrollPane = JScrollPane(self.configTextArea)
        self.configPanel.add(self.scrollPane, BorderLayout.SOUTH)
        self.reloadButton = JButton("Reload",
                                    actionPerformed=self.reloadConfig)
        self.configPanel.add(self.reloadButton, BorderLayout.CENTER)
        return self.HaEPanel
class GUI():
    def __init__(self):
        self.frame = JFrame('Phone status twitter')
        self.frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
        self.asteriskLoginPanel = gui.AsteriskLoginPanel(buttonAction=self.loginToAsterisk)
        self.asteriskLoginPanel.render()
        self.frame.add(self.asteriskLoginPanel)
        self.asteriskLoginPanel.getRootPane().setDefaultButton(self.asteriskLoginPanel.login)
        self.frame.pack()
        self.frame.visible = True

    def renderTwitterLoginPanel(self):
        '''Render on the frame the login panel with the fields needed to
        authenticate with the Twitter API.'''
        self.twitterLoginPanel = JPanel(GridLayout(0,2))
        self.frame.add(self.twitterLoginPanel)
        
        self.twitterLoginPanel.setBorder(BorderFactory.createTitledBorder('Twitter account information'))

        self.twitterLoginField = extragui.EnhancedTextField('asterisk-jython', 15)
        self.twitterLoginPanel.add(JLabel('Username:'******'password', 15)
        self.twitterLoginPanel.add(JLabel('Password:'******'Log in', actionPerformed=self.loginToTwitter)
        self.twitterLoginPanel.add(self.twitterLoginButton)
        self.twitterLoginPanel.getRootPane().setDefaultButton(self.twitterLoginButton)

        self.twitterLoginStatusLabel = JLabel('Awaiting information...')
        self.twitterLoginPanel.add(self.twitterLoginStatusLabel)

    def renderMainPanel(self):
        '''Render on the frame the main panel with a status label'''
        self.mainPanel = JPanel(GridLayout(0,2))
        self.frame.add(self.mainPanel)

        self.mainPanel.setBorder(BorderFactory.createTitledBorder('Application status'))

        self.mainPanel.add(JLabel('Status:'))
        self.statusLabel = JTextField('Running...', 15)
        self.statusLabel.editable = False
        self.mainPanel.add(self.statusLabel)

    def loginToAsterisk(self, event):
        '''Execute the login procedure to the Asterisk Manager interface'''
        self.manager = PhoneStatusListener(self.asteriskLoginPanel.hostname.text, \
                                            self.asteriskLoginPanel.username.text, \
                                            self.asteriskLoginPanel.password.text, \
                                            self.asteriskLoginPanel.extension.text)
        try:
            self.manager.addStatusUpdater(self.statusUpdater)
            self.manager.start()
            self.asteriskLoginPanel.visible = False
            self.renderTwitterLoginPanel()
            self.twitterLoginField.requestFocusInWindow()
            self.frame.pack()
        except:
            self.asteriskLoginPanel.status.text = "Unable to authenticate"

    def loginToTwitter(self, event):
        '''Execute the login procedure to the Twitter platform'''
        try:
            self.twitter = twitter.Api(username=self.twitterLoginField.text, \
                                        password=self.twitterPasswordField.text)
            self.twitter.GetUser(self.twitterLoginField.text)
            self.twitterLoginPanel.visible = False
            self.renderMainPanel()
            self.frame.pack()
        except:
            self.twitterLoginStatusLabel.text = "Unable to authenticate"

    def statusUpdater(self, update):
        self.statusLabel.text = update
        self.twitter.PostUpdate(update)
Beispiel #45
0
def makeTranslationUI(affines, imp, show=True, print_button_text="Print transforms"):
  """
  A GUI to control the translation components of a list of AffineTransform3D instances.
  When updated, the ImagePlus is refreshed.

  affines: a list (will be read multiple times) of one affine transform per image.
  imp: the ImagePlus that hosts the virtual stack with the transformed images.
  show: defaults to True, whether to make the GUI visible.
  print_button_text: whatever you want the print button to read like, defaults to "Print transforms".
   
  Returns the JFrame, the main JPanel and the lower JButton panel.
  """
  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()
  gc.anchor = GBC.WEST
  gc.fill = GBC.NONE

  # Column labels
  gc.gridy = 0
  for i, title in enumerate(["Camera", "translation X", "translation Y", "translation Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  gc.anchor = GBC.WEST
  listeners = []
  
  # One row per affine to control: skip the first
  for i, affine in enumerate(affines[1:]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel("CM0%i: " % (i + 1))
    gb.setConstraints(label, gc)
    panel.add(label)
    # One JTextField per dimension
    for dimension, translation in enumerate(affine.getTranslation()):
      tf = JTextField(str(translation), 10)
      listener = MatrixTextFieldListener(affine, dimension, tf, imp)
      listeners.append(listener)
      imp.addImageListener(listener) # to disable the JTextField when closed
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)
      gc.gridx += 1
      gb.setConstraints(tf, gc)
      panel.add(tf)

  # Documentation for the user
  help_lines = ["Type a number and push enter,",
                "or use the scroll wheel."]
  gc.gridx = 0
  gc.gridwidth = 4
  for line in help_lines:
    gc.gridy += 1
    help = JLabel(line)
    gb.setConstraints(help, gc)
    panel.add(help)

  # Buttons
  printButton = JButton(print_button_text)
  
  def printTransforms(event):
    for i, aff in enumerate(affines): # print all, including the first
      matrix = zeros(12, 'd')
      aff.toArray(matrix)
      msg = "# Coarse affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)
      
  
  printButton.addActionListener(printTransforms)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  button_panel = JPanel()
  button_panel.add(printButton)
  gb.setConstraints(button_panel, gc)
  panel.add(button_panel)

  frame = JFrame("Translation control")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl(destroyables=listeners))
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(show)

  return frame, panel, button_panel
Beispiel #46
0
    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()
Beispiel #47
0
def makeCropUI(imp, images, tgtDir, panel=None, cropContinuationFn=None):
  """ imp: the ImagePlus to work on.
      images: the list of ImgLib2 images, one per frame, not original but already isotropic.
              (These are views that use a nearest neighbor interpolation using the calibration to scale to isotropy.)
      tgtDir: the target directory where e.g. CSV files will be stored, for ROI, features, pointmatches.
      panel: optional, a JPanel controlled by a GridBagLayout.
      cropContinuationFn: optional, a function to execute after cropping,
                          which is given as arguments the original images,
                          minC, maxC (both define a ROI), and the cropped images. """
  independent = None == panel
  if not panel:
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
    gb = GridBagLayout()
    gc = GBC()
  else:
    gb = panel.getLayout()
    # Constraints of the last component
    gc = gb.getConstraints(panel.getComponent(panel.getComponentCount() - 1))
    
    # Horizontal line to separate prior UI components from crop UI
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 4
    gc.anchor = GBC.WEST
    gc.fill = GBC.HORIZONTAL
    sep = JSeparator()
    sep.setMinimumSize(Dimension(200, 10))
    gb.setConstraints(sep, gc)
    panel.add(sep)

  # ROI UI header
  title = JLabel("ROI controls:")
  gc.gridy +=1
  gc.anchor = GBC.WEST
  gc.gridwidth = 4
  gb.setConstraints(title, gc)
  panel.add(title)

  # Column labels for the min and max coordinates
  gc.gridy += 1
  gc.gridwidth = 1
  for i, title in enumerate(["", "X", "Y", "Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  textfields = []
  rms = []

  # Load stored ROI if any
  roi_path = path = os.path.join(tgtDir, "crop-roi.csv")
  if os.path.exists(roi_path):
    with open(roi_path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
      reader.next() # header
      minC = map(int, reader.next()[1:])
      maxC = map(int, reader.next()[1:])
      # Place the ROI over the ImagePlus
      imp.setRoi(Roi(minC[0], minC[1], maxC[0] + 1 - minC[0], maxC[1] + 1 - minC[1]))
  else:
    # Use whole image dimensions
    minC = [0, 0, 0]
    maxC = [v -1 for v in Intervals.dimensionsAsLongArray(images[0])]

  # Text fields for the min and max coordinates
  for rowLabel, coords in izip(["min coords: ", "max coords: "],
                               [minC, maxC]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel(rowLabel)
    gb.setConstraints(label, gc)
    panel.add(label)
    for i in xrange(3):
      gc.gridx += 1
      tf = JTextField(str(coords[i]), 10)
      gb.setConstraints(tf, gc)
      panel.add(tf)
      textfields.append(tf)
      listener = RoiMaker(imp, textfields, len(textfields) -1)
      rms.append(listener)
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)

  # Listen to changes in the ROI of imp
  rfl = RoiFieldListener(imp, textfields)
  Roi.addRoiListener(rfl)
  # ... and enable cleanup
  ImagePlus.addImageListener(FieldDisabler(rfl, rms))

  # Functions for cropping images
  cropped = None
  cropped_imp = None

  def storeRoi(minC, maxC):
    if os.path.exists(roi_path):
      # Load ROI
      with open(path, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
        reader.next() # header
        same = True
        for a, b in izip(minC + maxC, map(int, reader.next()[1:] + reader.next()[1:])):
          if a != b:
            same = False
            # Invalidate any CSV files for features and pointmatches: different cropping
            for filename in os.listdir(tgtDir):
              if filename.endswith("features.csv") or filename.endswith("pointmatches.csv"):
                os.remove(os.path.join(tgtDir, filename))
            break
        if same:
          return
    # Store the ROI as crop-roi.csv
    with open(roi_path, 'w') as csvfile:
      w = csv.writer(csvfile, delimiter=',', quotechar="\"", quoting=csv.QUOTE_NONNUMERIC)
      w.writerow(["coords", "x", "y", "z"])
      w.writerow(["min"] + map(int, minC))
      w.writerow(["max"] + map(int, maxC))
  
  def crop(event):
    global cropped, cropped_imp
    coords = [int(float(tf.getText())) for tf in textfields]
    minC = [max(0, c) for c in coords[0:3]]
    maxC = [min(d -1, c) for d, c in izip(Intervals.dimensionsAsLongArray(images[0]), coords[3:6])]
    storeRoi(minC, maxC)
    print "ROI min and max coordinates"
    print minC
    print maxC
    cropped = [Views.zeroMin(Views.interval(img, minC, maxC)) for img in images]
    cropped_imp = showAsStack(cropped, title="cropped")
    cropped_imp.setDisplayRange(imp.getDisplayRangeMin(), imp.getDisplayRangeMax())
    if cropContinuationFn:
      cropContinuationFn(images, minC, maxC, cropped, cropped_imp)

  # Buttons to create a ROI and to crop to ROI,
  # which when activated enables the fine registration buttons
  crop_button = JButton("Crop to ROI")
  crop_button.addActionListener(crop)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  gc.anchor = GBC.WEST
  buttons_panel = JPanel()
  buttons_panel.add(crop_button)
  gb.setConstraints(buttons_panel, gc)
  panel.add(buttons_panel)

  if independent:
    frame = JFrame("Crop by ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
    frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
    frame.setVisible(True)
  else:
    # Re-pack the JFrame
    parent = panel.getParent()
    while not isinstance(parent, JFrame) and parent is not None:
      parent = parent.getParent()

    if parent:
      frame = parent
      frame.pack()
      found = False
      for wl in frame.getWindowListeners():
        if isinstance(wl, CloseControl):
          wl.addDestroyables(rms + [rfl])
          found = True
          break
      if not found:
        frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
      frame.setVisible(True)

  return panel
Beispiel #48
0
def makeRegistrationUI(original_images, original_calibration, coarse_affines, params, images, minC, maxC, cropped, cropped_imp):
  """
  Register cropped images either all to all or all to the first one,
  and print out a config file with the coarse affines,
  the ROI for cropping, and the refined affines post-crop.

  original_images: the original, raw images, with original dimensions.
  original_calibration: the calibration of the images as they are on disk.
  coarse_affines: list of AffineTransform3D, one per image, that specify the translation between images
                  as manually set using the makeTranslationUI.
  params: dictionary with parameters for registering the given cropped images.
          This includes a calibration that is likely [1.0, 1.0, 1.0] as the cropped images
          are expected to have been scaled to isotropy.
  images: the list of near-original images but scaled (by calibration) to isotropy.
          (These are really views of the original images, using nearest neighbor interpolation
           to scale them to isotropy.)
  minC, maxC: the minimum and maximum coordinates of a ROI with which the cropped images were made.
  cropped: the list of images that have been scaled to isotropy, translated and cropped by the ROI.
           (These are really interval views of the images, the latter using nearest neighbor interpolation.)
  cropped_imp: the ImagePlus holding the virtual stack of cropped image views.

  The computed registration will merge the scaling to isotropy + first transform (a translation)
   + roi cropping translation + the params["modelclass"] registration transform, to read directly
   from the original images using a nearest interpolation, for best performance (piling two nearest
   interpolations over one another would result in very slow access to pixel data).
  """

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  calibration = params["calibration"]
  params["cal X"] = calibration[0]
  params["cal Y"] = calibration[1]
  params["cal Z"] = calibration[2]

  # Add a label and a text field for every parameter, with titles for every block
  strings = [["Calibration",
              "cal X", "cal Y", "cal Z"],
             ["Difference of Gaussian",
              "minPeakValue", "sigmaSmaller", "sigmaLarger"],
             ["Feature extraction",
              "radius", "min_angle", "max_per_peak",
              "angle_epsilon", "len_epsilon_sq",
              "pointmatches_nearby", "pointmatches_search_radius"],
             ["RANSAC parameters for the model",
              "maxEpsilon", "minInlierRatio", "minNumInliers",
              "n_iterations", "maxTrust"],
             ["All to all registration",
              "maxAllowedError", "maxPlateauwidth", "maxIterations", "damp"]]
  # Insert all as fields, with values populated from the params dictionary
  # and updating dynamically the params dictionary
  params = dict(params) # copy, will be updated
  insertFloatFields(panel, gb, gc, params, strings)

  # Identity transforms prior to registration
  affines = [affine3D([1, 0, 0, 0,
                       0, 1, 0, 0,
                       0, 0, 1, 0]) for img in cropped]
  
  def run():
    exe = newFixedThreadPool(min(len(cropped), numCPUs()))
    try:
      # Dummy for in-RAM reading of isotropic images
      img_filenames = [str(i) for i in xrange(len(cropped))]
      loader = InRAMLoader(dict(zip(img_filenames, cropped)))
      getCalibration = params.get("getCalibration", None)
      if not getCalibration:
        getCalibration = lambda img: [1.0] * cropped[0].numDimensions()
      csv_dir = params["csv_dir"]
      modelclass = params["modelclass"]
      # Matrices describing the registration on the basis of the cropped images
      matrices = computeOptimizedTransforms(img_filenames, loader, getCalibration,
                                            csv_dir, exe, modelclass, params)
      # Store outside, so they can be e.g. printed, and used beyond here
      for matrix, affine in zip(matrices, affines):
        affine.set(*matrix)

      # Combine the transforms: scaling (by calibration)
      #                         + the coarse registration (i.e. manual translations)
      #                         + the translation introduced by the ROI cropping
      #                         + the affine matrices computed above over the cropped images.
      coarse_matrices = []
      for coarse_affine in coarse_affines:
        matrix = zeros(12, 'd')
        coarse_affine.toArray(matrix)
        coarse_matrices.append(matrix)

      # NOTE: both coarse_matrices and matrices are from the camera X to camera 0. No need to invert them.
      # NOTE: uses identity calibration because the coarse_matrices already include the calibration scaling to isotropy
      transforms = mergeTransforms([1.0, 1.0, 1.0], coarse_matrices, [minC, maxC], matrices, invert2=False)

      print "calibration:", [1.0, 1.0, 1.0]
      print "cmTransforms:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in coarse_matrices)
      print "ROI", [minC, maxC]
      print "fineTransformsPostROICrop:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in matrices)
      print "invert2:", False
      
      # Show registered images
      registered = [transformedView(img, transform, interval=cropped[0])
                    for img, transform in izip(original_images, transforms)]
      registered_imp = showAsStack(registered, title="Registered with %s" % params["modelclass"].getSimpleName())
      registered_imp.setDisplayRange(cropped_imp.getDisplayRangeMin(), cropped_imp.getDisplayRangeMax())

      """
      # TEST: same as above, but without merging the transforms. WORKS, same result
      # Copy into ArrayImg, otherwise they are rather slow to browse
      def copy(img1, affine):
        # Copy in two steps. Otherwise the nearest neighbor interpolation on top of another
        # nearest neighbor interpolation takes a huge amount of time
        dimensions = Intervals.dimensionsAsLongArray(img1)
        aimg1 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img1, aimg1.factory()), aimg1)
        img2 = transformedView(aimg1, affine)
        aimg2 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img2, aimg2.factory()), aimg2)
        return aimg2
      futures = [exe.submit(Task(copy, img, affine)) for img, affine in izip(cropped, affines)]
      aimgs = [f.get() for f in futures]
      showAsStack(aimgs, title="DEBUG Registered with %s" % params["modelclass"].getSimpleName())
      """
    except:
      print sys.exc_info()
    finally:
      exe.shutdown()
      SwingUtilities.invokeLater(lambda: run_button.setEnabled(True))

  def launchRun(event):
    # Runs on the event dispatch thread
    run_button.setEnabled(False) # will be re-enabled at the end of run()
    # Fork:
    Thread(run).start()


  def printAffines(event):
    for i, affine in enumerate(affines):
      matrix = zeros(12, 'd')
      affine.toArray(matrix)
      msg = "# Refined post-crop affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)

  def prepareDeconvolutionScriptUI(event):
    """
    # DEBUG generateDeconvolutionScriptUI: generate params as a loadable serialized file
    with open("/tmp/parameters.pickle", 'w') as f:
      import pickle
      def asArrays(affines):
        arrays = []
        for affine in affines:
          matrix = zeros(12, 'd')
          affine.toArray(matrix)
          arrays.append(matrix)
        return arrays
        
      pickle.dump([params["srcDir"], params["tgtDir"], calibration,
                   asArrays(coarse_affines), [minC, maxC], asArrays(affines)], f)
    """
    generateDeconvolutionScriptUI(params["srcDir"], params["tgtDir"], calibration,
                                  coarse_affines, [minC, maxC], affines)
  
  # Buttons
  panel_buttons = JPanel()
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(panel_buttons, gc)
  panel.add(panel_buttons)
  
  run_button = JButton("Run")
  run_button.addActionListener(launchRun)
  gb.setConstraints(run_button, gc)
  panel_buttons.add(run_button)
  
  print_button = JButton("Print affines")
  print_button.addActionListener(printAffines)
  panel_buttons.add(print_button)

  prepare_button = JButton("Prepare deconvolution script")
  prepare_button.addActionListener(prepareDeconvolutionScriptUI)
  panel_buttons.add(prepare_button)

  frame = JFrame("Registration")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl())
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
Beispiel #49
0
def generateDeconvolutionScriptUI(srcDir,
                                  tgtDir,
                                  calibration,
                                  preCropAffines,
                                  ROI,
                                  postCropAffines):
  """
  Open an UI to automatically generate a script to:
  1. Register the views of each time point TM folder, and deconvolve them.
  2. Register deconvolved time points to each other, for a range of consecutive time points.

  Will ask for the file path to the kernel file,
  and also for the range of time points to process,
  and for the deconvolution iterations for CM00-CM01, and CM02-CM03.
  """

  template = """
# AUTOMATICALLY GENERATED - %s

import sys, os
sys.path.append("%s")
from lib.isoview import deconvolveTimePoints
from mpicbg.models import RigidModel3D, TranslationModel3D
from net.imglib2.img.display.imagej import ImageJFunctions as IL

# The folder with the sequence of TM\d+ folders, one per time point in the 4D series.
# Each folder should contain 4 KLB files, one per camera view of the IsoView microscope.
srcDir = "%s"

# A folder to save deconvolved images in, and CSV files describing features, point matches and transformations
targetDir = "%s"

# Path to the volume describing the point spread function (PSF)
kernelPath = "%s"

calibration = [%s] # An array with 3 floats (identity--all 1.0--because the coarse affines, that is,
                   # the camera transformations, already include the scaling to isotropy computed using the original calibration.

# The transformations of each timepoint onto the camera at index zero.
def cameraTransformations(dims0, dims1, dims2, dims3, calibration):
  return {
    0: [%s],
    1: [%s],
    2: [%s],
    3: [%s]
  }

# Deconvolution parameters
paramsDeconvolution = {
  "blockSizes": None, # None means the image size + kernel size. Otherwise specify like e.g. [[128, 128, 128]] for img in images]
  "CM_0_1_n_iterations": %i,
  "CM_2_3_n_iterations": %i,
}

# Joint dictionary of parameters
params = {}
params.update(paramsDeconvolution)

# A region of interest for each camera view, for cropping after registration but prior to deconvolution
roi = ([%s], # array of 3 integers, top-left coordinates
       [%s]) # array of 3 integers, bottom-right coordinates

# All 4 cameras relative to CM00
fineTransformsPostROICrop = \
   [[1, 0, 0, 0,
     0, 1, 0, 0,
     0, 0, 1, 0],
    [%s],
    [%s],
    [%s]]

deconvolveTimePoints(srcDir, targetDir, kernelPath, calibration,
                    cameraTransformations, fineTransformsPostROICrop,
                    params, roi, fine_fwd=True, subrange=range(%i, %i))
  """

  od = OpenDialog("Choose kernel file", srcDir)
  kernel_path = od.getPath()
  if not kernel_path:
    JOptionPane.showMessageDialog(None, "Can't proceed without a filepath to the kernel", "Alert", JOptionPane.ERROR_MESSAGE)
    return

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  msg = ["Edit parameters, then push the button",
         "to generate a script that, when run,",
         "will execute the deconvolution for each time point",
         "saving two 3D stacks per time point as ZIP files",
         "in the target directory under subfolder 'deconvolved'.",
         "Find the script in a new Script Editor window.",
         " "]
  gc.gridy = -1 # init
  for line in msg:
    label = JLabel(line)
    gc.anchor = GBC.WEST
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 2
    gc.gridheight = 1
    gb.setConstraints(label, gc)
    panel.add(label)

  strings = [["Deconvolution iterations",
              "CM_0_1_n_iterations", "CM_2_3_n_iterations"],
             ["Range",
              "First time point", "Last time point"]]
  params = {"CM_0_1_n_iterations": 5,
            "CM_2_3_n_iterations": 7,
            "First time point": 0,
            "Last time point": -1} # -1 means last
  insertFloatFields(panel, gb, gc, params, strings)

  def asString(affine):
    matrix = zeros(12, 'd')
    affine.toArray(matrix)
    return ",".join(imap(str, matrix))

  def generateScript(event):
    script = template % (str(datetime.now()),
                         filter(lambda path: path.endswith("IsoView-GCaMP"), sys.path)[-1],
                         srcDir,
                         tgtDir,
                         kernel_path,
                         ", ".join(imap(str, calibration)),
                         asString(preCropAffines[0]),
                         asString(preCropAffines[1]),
                         asString(preCropAffines[2]),
                         asString(preCropAffines[3]),
                         params["CM_0_1_n_iterations"],
                         params["CM_2_3_n_iterations"],
                         ", ".join(imap(str, ROI[0])),
                         ", ".join(imap(str, ROI[1])),
                         asString(postCropAffines[1]),
                         asString(postCropAffines[2]),
                         asString(postCropAffines[3]),
                         params["First time point"],
                         params["Last time point"])
    tab = None
    for frame in JFrame.getFrames():
      if str(frame).startswith("org.scijava.ui.swing.script.TextEditor["):
        try:
          tab = frame.newTab(script, "python")
          break
        except:
          print sys.exc_info()
    if not tab:
      try:
        now = datetime.now()
        with open(os.path.join(System.getProperty("java.io.tmpdir"),
                               "script-%i-%i-%i_%i:%i.py" % (now.year, now.month, now.day,
                                                             now.hour, now.minute)), 'w') as f:
          f.write(script)
      except:
        print sys.exc_info()
        print script
  

  gen = JButton("Generate script")
  gen.addActionListener(generateScript)
  gc.anchor = GBC.CENTER
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(gen, gc)
  panel.add(gen)

  frame = JFrame("Generate deconvolution script")
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
    def initUI(self):
        
        inputPanel = JPanel()
        inputPanel.setBorder(BorderFactory.createTitledBorder("Where are your control and treament images?"))
        inputLayout = GroupLayout(inputPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        inputPanel.setLayout(inputLayout)
        
        annotatePanel = JPanel()
        annotatePanel.setBorder(BorderFactory.createTitledBorder("How do you want to annotate your data?"))
        anLayout = GroupLayout(annotatePanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        annotatePanel.setLayout(anLayout)
        
        exportPanel = JPanel()
        exportPanel.setBorder(BorderFactory.createTitledBorder("Where do you want to export your data"))
        exportLayout = GroupLayout(exportPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        exportPanel.setLayout(exportLayout)
        
        btnPanel = JPanel()
        btnLayout = GroupLayout(btnPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        btnPanel.setLayout(btnLayout)
        
        layout = GroupLayout(self.getContentPane(), autoCreateContainerGaps=True, autoCreateGaps=True)
        self.getContentPane().setLayout(layout)

        self.setModalityType(ModalityType.APPLICATION_MODAL)
        self.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)# JFrame.EXIT_ON_CLOSE)
        # definition of elements
        # labels
        cPathLabel = JLabel("Control Path:")
        tPathLabel = JLabel("Treatment Path:")
        exPathLabel = JLabel("Save Results in:")
        
        #textfields
        self.cPathField = JTextField("/Users/schiklen/DotData/131118_dummy/131118_2926/cutout/", 16)
        self.tPathField = JTextField("/Users/schiklen/DotData/131118_dummy/131118_2926/cutout/", 16)
        self.exPathField = JTextField("/Users/schiklen/DotData/131118_dummy/131118_2926/cutout/", 16)
        
        #Radiobuttons
        yesNoRButton = JRadioButton("Yes / No / Ignore", selected=True, actionCommand="yesNoIgnore", actionPerformed=self.setAnnotationTypeDialog)
        intRButton = JRadioButton("Integer", actionCommand="int", actionPerformed=self.setAnnotationTypeDialog)
        nRButton = JRadioButton("Number", actionCommand="float", actionPerformed=self.setAnnotationTypeDialog)
        listRButton = JRadioButton("From List...", actionCommand="list", actionPerformed=self.openListDialog)

        self.rBGroup = ButtonGroup()
        self.rBGroup.add(yesNoRButton)
        self.rBGroup.add(intRButton)
        self.rBGroup.add(nRButton)
        self.rBGroup.add(listRButton)
        
        #self.customListButton = JButton("Custom List...", actionPerformed=self.makeCustomList, enabled=0)
        
        #buttons
        cPathButton = JButton("Browse...", actionPerformed=self.browseC) # lambda on fieldvalue
        tPathButton = JButton("Browse...", actionPerformed=self.browseT) # lambda on fieldvalue
        exPathButton = JButton("Browse...", actionPerformed=self.browseE)
        OKButton = JButton("OK", actionPerformed=self.okayEvent)
        CancelButton = JButton("Cancel", actionPerformed=self.cancel)
        
        '''General ContentPane Layout'''
        layout.setHorizontalGroup(layout.createParallelGroup()
                                  .addComponent(inputPanel)
                                  .addComponent(annotatePanel)
                                  .addComponent(exportPanel)
                                  .addComponent(btnPanel)
                                  )
        layout.linkSize(SwingConstants.HORIZONTAL, inputPanel, annotatePanel, exportPanel, btnPanel)
        layout.setVerticalGroup(layout.createSequentialGroup()
                                .addComponent(inputPanel)
                                .addComponent(annotatePanel)
                                .addComponent(exportPanel)
                                .addComponent(btnPanel)
                                )
        
        ''' Input panel Layout '''
        inputLayout.setHorizontalGroup(inputLayout.createSequentialGroup()
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                 .addComponent(cPathLabel)
                                                 .addComponent(tPathLabel))
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                 .addComponent(self.cPathField)
                                                 .addComponent(self.tPathField))
                                       .addGroup(inputLayout.createParallelGroup()
                                                 .addComponent(cPathButton)
                                                 .addComponent(tPathButton))
                                       )
        
        inputLayout.setVerticalGroup(inputLayout.createSequentialGroup()
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                 .addComponent(cPathLabel)
                                                 .addComponent(self.cPathField)
                                                 .addComponent(cPathButton))
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                 .addComponent(tPathLabel)
                                                 .addComponent(self.tPathField)
                                                 .addComponent(tPathButton))
                                     )
        
        '''Annotate panel layout'''
        anLayout.setHorizontalGroup(anLayout.createParallelGroup()
                                    .addComponent(yesNoRButton)
                                    .addComponent(intRButton)
                                    .addComponent(nRButton)
                                    .addComponent(listRButton)
                                    #.addComponent(self.customListButton)
                                    )
        anLayout.setVerticalGroup(anLayout.createSequentialGroup()
                                    .addComponent(yesNoRButton)
                                    .addComponent(intRButton)
                                    .addComponent(nRButton)
                                    .addComponent(listRButton)
                                    #.addComponent(self.customListButton)
                                    )
        
        
        '''Export panel layout'''
        exportLayout.setHorizontalGroup(exportLayout.createSequentialGroup()
                                        .addComponent(exPathLabel)
                                        .addComponent(self.exPathField)
                                        .addComponent(exPathButton))
        exportLayout.setVerticalGroup(exportLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                        .addComponent(exPathLabel)
                                        .addComponent(self.exPathField)
                                        .addComponent(exPathButton))
        
        
        '''Buttons Panel Layout'''
        btnLayout.setHorizontalGroup(btnLayout.createSequentialGroup()
                                     .addComponent(CancelButton)
                                     .addComponent(OKButton)
                                     )
        btnLayout.setVerticalGroup(btnLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                   .addComponent(CancelButton)
                                   .addComponent(OKButton)
                                   )

        self.setTitle("Random Picture Picker")

        self.pack()
        self.setLocationRelativeTo(None)
        self.setVisible(True)
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- " + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- " + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- " + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- " + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>")
        keyLable.setBorder(BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()