Exemplo n.º 1
0
class positionDialog(JFrame):
    def __init__(self):
        self.frame = JFrame("CellCropper: Experiment details", size=(400,200))
        self.frame.setLocation(20,120)
        self.Panel = JPanel(GridLayout(4,2))
        self.frame.add(self.Panel)
        self.Panel.add(JLabel("Date:"))
        self.dateField = JTextField( str(date.today()), 8 )
        self.Panel.add(self.dateField)
        self.strainField = JTextField( "2926",4 )
        self.Panel.add(self.strainField)
        self.tempField = JTextField( "34",2 )
        self.Panel.add(self.tempField)
        self.ODField = JTextField( "0.5",3 )
        self.Panel.add(self.ODField)
        self.condField = JTextField( "0.5",3 )
        self.Panel.add(self.condField)

        self.OKButton = JButton("OK",actionPerformed=closeAndMakePos)
        self.Panel.add(self.OKButton)
        self.frame.pack()
        WindowManager.addWindow(self.frame)
        self.show()

    def show(self):
        self.frame.visible = True
    
    def close(self):
        return self.dateField.text, self.strainField.text, self.tempField.text, self.ODField.text, self.condField.text
        WindowManager.removeWindow(self.frame)
        self.frame.dispose()
Exemplo n.º 2
0
class _AccountAdder:
    def __init__(self, contactslist):
        self.contactslist = contactslist
        self.mainframe = JFrame("Add New Contact")
        self.account = JComboBox(self.contactslist.clientsByName.keys())
        self.contactname = JTextField()
        self.buildpane()

    def buildpane(self):
        buttons = JPanel()
        buttons.add(JButton("OK", actionPerformed=self.add))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        acct = JPanel(GridLayout(1, 2), doublebuffered)
        acct.add(JLabel("Account"))
        acct.add(self.account)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(self.contactname)
        mainpane.add(acct)
        mainpane.add(buttons)
        self.mainframe.pack()
        self.mainframe.show()

    #action listeners
    def add(self, ae):
        acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
        acct.addContact(self.contactname.getText())
        self.mainframe.dispose()

    def cancel(self, ae):
        self.mainframe.dispose()
Exemplo n.º 3
0
class _AccountAdder:
    def __init__(self, contactslist):
        self.contactslist = contactslist
        self.mainframe = JFrame("Add New Contact")
        self.account = JComboBox(self.contactslist.clientsByName.keys())
        self.contactname = JTextField()
        self.buildpane()

    def buildpane(self):
        buttons = JPanel()
        buttons.add(JButton("OK", actionPerformed=self.add))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        acct = JPanel(GridLayout(1, 2), doublebuffered)
        acct.add(JLabel("Account"))
        acct.add(self.account)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(self.contactname)
        mainpane.add(acct)
        mainpane.add(buttons)
        self.mainframe.pack()
        self.mainframe.show()

    #action listeners
    def add(self, ae):
        acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
        acct.addContact(self.contactname.getText())
        self.mainframe.dispose()

    def cancel(self, ae):
        self.mainframe.dispose()
Exemplo n.º 4
0
class View(JComponent):
    def __init__(self, obj, location, size=(800, 600), keys=None):
        JComponent.__init__(self)
        self.location = list(location)
        self.buffer = FrameBuffer(
            size[0], size[1], FrameBuffer.SAMPLINGMODE_NORMAL)
        self.obj = obj
        self.frame = JFrame(keyPressed=self.keyPressed,
                            keyReleased=self.keyReleased)
        self.frame.add(self)
        self.size = size
        self.frame.pack()
        self.frame.size = size
        self.frame.visible = True
        self.clearColor = Color(0x666666)
        self.keys = keys

    def paint(self, g):
        x, y, z = self.location
        self.obj.world.camera.setPosition(x, -y, z)
        self.obj.world.camera.lookAt(SimpleVector(0, 0, 0))

        self.buffer.clear(self.clearColor)
        self.obj.world.renderScene(self.buffer)
        self.obj.world.draw(self.buffer)
        self.buffer.update()
        self.buffer.display(g)
        self.repaint()

    def keyReleased(self, event):
        if self.keys is not None and hasattr(self.keys, 'key_released'):
            self.keys.key_released(KeyEvent.getKeyText(event.keyCode))

    def keyPressed(self, event):
        if self.keys is not None and hasattr(self.keys, 'key_pressed'):
            self.keys.key_pressed(KeyEvent.getKeyText(event.keyCode))
        if event.keyCode == KeyEvent.VK_ESCAPE:
            self.frame.dispose()
        elif event.keyCode == KeyEvent.VK_PAGE_UP:
            self.obj.sch.rate *= 1.1
            self.frame.title = 'rate: %1.3f' % self.obj.sch.rate
        elif event.keyCode == KeyEvent.VK_PAGE_DOWN:
            self.obj.sch.rate /= 1.1
            self.frame.title = 'rate: %1.3f' % self.obj.sch.rate
        elif event.keyCode == KeyEvent.VK_Z:
            self.location[2] += 1
        elif event.keyCode == KeyEvent.VK_X:
            self.location[2] -= 1
        elif event.keyCode == KeyEvent.VK_W:
            self.location[1] += 1
        elif event.keyCode == KeyEvent.VK_S:
            self.location[1] -= 1
        elif event.keyCode == KeyEvent.VK_A:
            self.location[0] += 1
        elif event.keyCode == KeyEvent.VK_D:
            self.location[0] -= 1
Exemplo n.º 5
0
    def run_update(self):
        #from javax.swing import JFrame, JButton

        frame = JFrame("Hello")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.setLocation(100, 100)
        frame.setSize(300, 200)

        def updatePressed(event):
            jmri.jmrit.signalling.SignallingPanel.updatePressed(ActionEvent)(e)

        btn = JButton("Add", actionPerformed=updatePressed)
        frame.add(btn)

        frame.setVisible(True)
        btn.doClick
        frame.dispose()
Exemplo n.º 6
0
def cachedBPROM(genome, fileName, frame):
  """
  genome: Genome as a string.
  fileName: File to save the BPROM results in.
  swing: A JFrame or None.  If this is None then messages will be printed, if it isn't then
         they will also be put in a dialog box.

  return: Results of the BPROM prediction stored in a list of Promoter objects.

  If the file Specified by fileName already exists then this function simply parses the file
  already there.  Also, if a request is made to BPROM and nothing is returned, no file is
  created, the user is warned, and an empty list is returned.
  """
  offset = 25 if ".forward.bprom" in fileName else 50
  direction = "forward" if offset == 50 else "reverse"
    
  def getPromoters():
    input = open(fileName, "r")
    results = parseBPROM(input.read())
    input.close()
    return results

  if not os.path.isfile(fileName):
    results = urllib.urlopen("http://linux1.softberry.com/cgi-bin/programs/gfindb/bprom.pl",
                             urllib.urlencode({"DATA" : genome}))
    resultString = results.read()
    results.close()
    resultString = resultString[resultString.find("<pre>"):resultString.find("</pre>")]
    resultString = re.sub("<+.+>+", "", resultString).strip()
    if resultString:
      output = open(fileName, "w")
      output.write(resultString)
      output.close()
      return getPromoters()
    else:
      if frame:
        messageFrame = JFrame("BPROM Error",
                              defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE)
        messageFrame.setLocation(frame.location().x + offset, frame.location().y + offset)
        messageFrame.contentPane.layout = GridBagLayout()
        constraints = GridBagConstraints()
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        messageFrame.contentPane.add(JLabel("<html>The pipeline will continue to run but BPROM<br/>did not process the request for promoters on the<br/>" + direction + " strand.  Try again tomorrow.</html>"), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 1, 1
        constraints.anchor = GridBagConstraints.LINE_END
        messageFrame.contentPane.add(JButton("Ok", actionPerformed = lambda e: messageFrame.dispose()), constraints)
        messageFrame.pack()
        messageFrame.visible = True
      print "BPROM Error:", "The pipeline will continue to run but BPROM did not process the request for promoters on the " + direction + " strand.  Try again tomorrow"
      return []
  else:
    return getPromoters()
Exemplo n.º 7
0
class NewAccountGUI:
    def __init__(self, amgui):
        self.amgui = amgui
        self.am = amgui.acctmanager
        self.buildgwinfo()
        self.autologin = JCheckBox("Automatically Log In")
        self.acctname = JTextField()
        self.gwoptions = JPanel(doublebuffered)
        self.gwoptions.border = TitledBorder("Gateway Options")
        self.buildgwoptions("Twisted")
        self.mainframe = JFrame("New Account Window")
        self.buildpane()

    def buildgwinfo(self):
        self.gateways = {
            "Twisted": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField("twistedmatrix.com"),
                "port": JTextField("8787"),
                "service": JTextField("twisted.words"),
                "persp": JTextField()
            },
            "AIM": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField("toc.oscar.aol.com"),
                "port": JTextField("9898")
            },
            "IRC": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField(),
                "port": JTextField("6667"),
                "channels": JTextField()
            }
        }
        self.displayorder = {
            "Twisted": [["Identity Name", "ident"], ["Password", "passwd"],
                        ["Host", "host"], ["Port", "port"],
                        ["Service Name", "service"],
                        ["Perspective Name", "persp"]],
            "AIM": [["Screen Name", "ident"], ["Password", "passwd"],
                    ["Host", "host"], ["Port", "port"]],
            "IRC": [["Nickname", "ident"], ["Password", "passwd"],
                    ["Host", "host"], ["Port", "port"],
                    ["Channels", "channels"]]
        }

    def buildgwoptions(self, gw):
        self.gwoptions.removeAll()
        self.gwoptions.layout = GridLayout(len(self.gateways[gw]), 2)
        for mapping in self.displayorder[gw]:
            self.gwoptions.add(JLabel(mapping[0]))
            self.gwoptions.add(self.gateways[gw][mapping[1]])

    def buildpane(self):
        gw = JPanel(GridLayout(1, 2), doublebuffered)
        gw.add(JLabel("Gateway"))
        self.gwlist = JComboBox(
            self.gateways.keys())  #, actionPerformed=self.changegw)
        self.gwlist.setSelectedItem("Twisted")
        gw.add(self.gwlist)

        stdoptions = JPanel(GridLayout(2, 2), doublebuffered)
        stdoptions.border = TitledBorder("Standard Options")
        stdoptions.add(JLabel())
        stdoptions.add(self.autologin)
        stdoptions.add(JLabel("Account Name"))
        stdoptions.add(self.acctname)

        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(JButton("OK", actionPerformed=self.addaccount))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        mainpane = self.mainframe.getContentPane()
        mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
        mainpane.add(gw)
        mainpane.add(self.gwoptions)
        mainpane.add(stdoptions)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.setLocation(100, 100)
        self.mainframe.pack()
        self.mainframe.show()

    #actionlisteners
    def changegw(self, ae):
        self.buildgwoptions(self.gwlist.getSelectedItem())
        self.mainframe.pack()
        self.mainframe.show()

    def addaccount(self, ae):
        gwselection = self.gwlist.getSelectedItem()
        gw = self.gateways[gwselection]
        name = gw["ident"].text
        passwd = gw["passwd"].text
        host = gw["host"].text
        port = int(gw["port"].text)
        autologin = self.autologin.isSelected()
        acctname = self.acctname.text

        if gwselection == "Twisted":
            sname = gw["service"].text
            perspective = gw["persp"].text
            self.am.addAccount(
                PBAccount(acctname, autologin, name, passwd, host, port,
                          [[stype, sname, perspective]]))
        elif gwselection == "AIM":
            self.am.addAccount(
                TOCAccount(acctname, autologin, name, passwd, host, port))
        elif gwselection == "IRC":
            channels = gw["channels"].text
            self.am.addAccount(
                IRCAccount(acctname, autologin, name, passwd, host, port,
                           channels))

        self.amgui.update()
        print "Added new account"
        self.mainframe.dispose()

    def cancel(self, ae):
        print "Cancelling new account creation"
        self.mainframe.dispose()
Exemplo n.º 8
0
class PropertyEditor(WindowAdapter):
    """
    Edits Tabular Properties of a given WindowAdapter
    """
    instances = {}
    last_location = None
    locations = {}
    last_size = None
    sizes = {}

    NEW_WINDOW_OFFSET = 32
    offset = NEW_WINDOW_OFFSET

    @staticmethod
    def get_instance(text="Property Editor",
                     columns=None,
                     data=None,
                     empty=None,
                     add_actions=True,
                     actions=None):
        """
        Singleton Method based on the text property. It tries to generate only one property configuration page per text.

        :param text: getinstance key
        :param columns: proparty columns it should be an array alike
        :param data: it contains the current property rows
        :param empty: empty row property when adding a new one
        :param add_actions: include or not new actions
        :param actions: default set of actions to be appended to Add and Delete Rows
        :return: a new instance of PropertyEditor or a reused one.
        """
        if not actions: actions = []
        if not columns: columns = []
        if data == None: data = []
        if not empty: empty = []
        try:
            PropertyEditor.instances[text]
        except KeyError:
            PropertyEditor.instances[text] = \
                PropertyEditor().__private_init__(text, columns, data, empty, add_actions, actions)
            try:
                PropertyEditor.instances[text].this.setLocation(
                    PropertyEditor.locations[text])
            except KeyError:
                if PropertyEditor.last_location:
                    PropertyEditor.instances[text].this.setLocation(
                        PropertyEditor.last_location.x + PropertyEditor.offset,
                        PropertyEditor.last_location.y + PropertyEditor.offset)
                    PropertyEditor.offset = PropertyEditor.NEW_WINDOW_OFFSET
            try:
                PropertyEditor.instances[text].this.setSize(
                    PropertyEditor.sizes[text])
            except KeyError:
                if PropertyEditor.last_size:
                    PropertyEditor.instances[text].this.setSize(
                        PropertyEditor.last_size)
            PropertyEditor.last_location = PropertyEditor.instances[
                text].this.getLocation()
            PropertyEditor.last_size = PropertyEditor.instances[
                text].this.getSize()
        ## Hack ON: Bring on Front
        PropertyEditor.instances[text].this.setAlwaysOnTop(True)
        PropertyEditor.instances[text].this.setAlwaysOnTop(False)
        ## Hack OFF
        return PropertyEditor.instances[text]

    def __private_init__(self,
                         text="Property Editor",
                         columns=None,
                         data=None,
                         empty=None,
                         add_actions=True,
                         actions=None):
        if not actions: actions = []
        if not columns: columns = []
        if data == None: data = []
        if not empty: empty = []

        self._text = text
        self.this = JFrame(text)
        self._table = JTable()
        self._dtm = DefaultTableModel(0, 0)
        self._dtm.setColumnIdentifiers(columns)
        self._table.setModel(self._dtm)
        self._data = data
        for d in data:
            self._dtm.addRow(d)
        self._pane = JScrollPane(self._table)
        self.this.add(self._pane)
        self._empty = empty

        self.this.addWindowListener(self)

        self._dtm.addTableModelListener(lambda _: self._update_model())
        self.this.setLocation(PropertyEditor.NEW_WINDOW_OFFSET,
                              PropertyEditor.NEW_WINDOW_OFFSET)

        if add_actions:
            self._popup = JPopupMenu()
            self._pane.setComponentPopupMenu(self._popup)
            inherits_popup_menu(self._pane)

            self._actions = actions
            self._actions.append(
                ExecutorAction('Remove Selected Rows',
                               action=lambda e: self._remove_row()))
            self._actions.append(
                ExecutorAction('Add New Row',
                               action=lambda e: self._add_row()))

            for action in self._actions:
                self._popup.add(action.menuitem)

        self.this.setForeground(Color.black)
        self.this.setBackground(Color.lightGray)
        self.this.pack()
        self.this.setVisible(True)
        self.this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)

        return self

    def _add_row(self):
        """
        Add a new row the selection

        :return: None
        """
        self._dtm.addRow(self._empty)

    def _remove_row(self):
        """
        Remove all the selected rows from the selection
        :return:
        """
        rows = self._table.getSelectedRows()
        for i in range(0, len(rows)):
            self._dtm.removeRow(rows[i] - i)

    def windowClosing(self, evt):
        """
        Overrides WindowAdapter method

        :param evt: unused
        :return: None
        """
        PropertyEditor.locations[self._text] = self.this.getLocation()
        PropertyEditor.sizes[self._text] = self.this.getSize()
        PropertyEditor.last_location = self.this.getLocation()
        PropertyEditor.last_size = self.this.getSize()
        PropertyEditor.offset = 0
        self.this.setVisible(False)
        self.this.dispose()
        del PropertyEditor.instances[self._text]

    def _update_model(self):
        """
        Update the data content with the updated rows

        :return: None
        """
        del self._data[:]
        nRow = self._dtm.getRowCount()
        nCol = self._dtm.getColumnCount()
        for i in range(0, nRow):
            self._data.append([None] * nCol)
            for j in range(0, nCol):
                d = str(self._dtm.getValueAt(i, j)).lower()
                if d == 'none' or d == '':
                    self._data[i][j] = None
                elif d == 'true' or d == 't':
                    self._data[i][j] = True
                elif d == 'false' or d == 'f':
                    self._data[i][j] = False
                else:
                    try:
                        self._data[i][j] = int(self._dtm.getValueAt(i, j))
                    except ValueError:
                        self._data[i][j] = self._dtm.getValueAt(i, j)
Exemplo n.º 9
0
class Window (object):
	def __init__(self, windowManager, commandConsoleFactory, subject, windowTitle):
		self._windowManager = windowManager





		self.onCloseRequestListener = None



		# EDIT MENU

		transferActionListener = _TransferActionListener()

		editMenu = JMenu( 'Edit' )

		if Platform.getPlatform() is Platform.MAC:
			command_key_mask = ActionEvent.META_MASK
		else:
			command_key_mask = ActionEvent.CTRL_MASK;

		self.__editUndoItem = JMenuItem( 'Undo' )
		undoAction = _action( 'undo', self.__onUndo )
		self.__editUndoItem.setActionCommand( undoAction.getValue( Action.NAME ) )
		self.__editUndoItem.addActionListener( undoAction )
		self.__editUndoItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Z, command_key_mask ) )
		self.__editUndoItem.setMnemonic( KeyEvent.VK_U )
		editMenu.add( self.__editUndoItem )

		self.__editRedoItem = JMenuItem( 'Redo' )
		redoAction = _action( 'redo', self.__onRedo )
		self.__editRedoItem.setActionCommand( redoAction.getValue( Action.NAME ) )
		self.__editRedoItem.addActionListener( redoAction )
		self.__editRedoItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Y, command_key_mask ) )
		self.__editRedoItem.setMnemonic( KeyEvent.VK_R )
		editMenu.add( self.__editRedoItem )

		editMenu.addSeparator()

		editCutItem = JMenuItem( 'Cut' )
		editCutItem.setActionCommand( TransferHandler.getCutAction().getValue( Action.NAME ) )
		editCutItem.addActionListener( transferActionListener )
		editCutItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_X, command_key_mask ) )
		editCutItem.setMnemonic( KeyEvent.VK_T )
		editMenu.add( editCutItem )

		editCopyItem = JMenuItem( 'Copy' )
		editCopyItem.setActionCommand( TransferHandler.getCopyAction().getValue( Action.NAME ) )
		editCopyItem.addActionListener( transferActionListener )
		editCopyItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_C, command_key_mask ) )
		editCopyItem.setMnemonic( KeyEvent.VK_C )
		editMenu.add( editCopyItem )

		editPasteItem = JMenuItem( 'Paste' )
		editPasteItem.setActionCommand( TransferHandler.getPasteAction().getValue( Action.NAME ) )
		editPasteItem.addActionListener( transferActionListener )
		editPasteItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_V, command_key_mask ) )
		editPasteItem.setMnemonic( KeyEvent.VK_P )
		editMenu.add( editPasteItem )

		editMenu.addSeparator()

		self.__showUndoHistoryItem = JMenuItem( 'Show undo history' )
		self.__showUndoHistoryItem.addActionListener( _action( 'Show undo history', self.__onShowUndoHistory ) )
		editMenu.add( self.__showUndoHistoryItem )




		# HELP MENU

		helpMenu = JMenu( 'Help' )

		helpToggleTooltipHighlightsItem = JMenuItem( 'Toggle tooltip highlights' )
		toggleTooltipHighlightsAction = _action( 'Toggle tooltip highlights', self.__onToggleTooltipHighlights )
		helpToggleTooltipHighlightsItem.setActionCommand( toggleTooltipHighlightsAction.getValue( Action.NAME ) )
		helpToggleTooltipHighlightsItem.addActionListener( toggleTooltipHighlightsAction )
		helpToggleTooltipHighlightsItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_F2, 0 ) )
		helpMenu.add( helpToggleTooltipHighlightsItem )

		helpMenu.add( _action( 'Show all tip boxes', self.__onShowAllTipBoxes ) )


		# MENU BAR

		menuBar = JMenuBar()
		menuBar.add( editMenu )
		menuBar.add( helpMenu )




		# BROWSER

		# Initialise here, as the browser listener may invoke methods upon the browser's creation
		class _BrowserListener (TabbedBrowser.TabbedBrowserListener):
			def createNewBrowserWindow(_self, subject):
				self._onOpenNewWindow( subject )

			def onTabbledBrowserChangePage(_self, browser):
				pass


		def inspectFragment(fragment, sourceElement, triggeringEvent):
			return self._windowManager.world.inspectFragment( fragment, sourceElement, triggeringEvent )



		def onChangeHistoryChanged(history):
			self.__refreshChangeHistoryControls( history )

		self._browser = TabbedBrowser( self._windowManager.world.rootSubject, subject, inspectFragment, _BrowserListener(), commandConsoleFactory )
		self._browser.getComponent().setPreferredSize( Dimension( 800, 600 ) )
		changeHistory = self._browser.getChangeHistory()
		self._browser.getChangeHistory().addChangeHistoryListener(onChangeHistoryChanged)





		# MAIN PANEL

		windowPanel = JPanel()
		windowPanel.setLayout( BoxLayout( windowPanel, BoxLayout.Y_AXIS ) )
		windowPanel.add( self._browser.getComponent() )




		# WINDOW

		class _WindowLister (WindowListener):
			def windowActivated(listenerSelf, event):
				pass

			def windowClosed(listenerSelf, event):
				pass

			def windowClosing(listenerSelf, event):
				if self.onCloseRequestListener is not None:
					self.onCloseRequestListener( self )

			def windowDeactivated(listenerSelf, event):
				pass

			def windowDeiconified(listenerSelf, event):
				pass

			def windowIconified(listenerSelf, event):
				pass

			def windowOpened(listenerSelf, event):
				pass


		self.__frame = JFrame( windowTitle )

		self.__frame.setJMenuBar( menuBar )

		self.__frame.add( windowPanel )
		self.__frame.addWindowListener( _WindowLister() )
		self.__frame.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE )

		self.__frame.pack()


		# Cause command history controls to refresh
		self.__refreshChangeHistoryControls( None )





	@property
	def frame(self):
		return self.__frame


	@property
	def tabbedBrowser(self):
		return self._browser

	@property
	def currentBrowser(self):
		return self._browser.getCurrentBrowser()



	def show(self):
		self.__frame.setVisible( True )

	def close(self):
		self.__frame.dispose()




	def __refreshChangeHistoryControls(self, changeHistory):
		if changeHistory is not None:
			self.__editUndoItem.setEnabled( changeHistory.canUndo() )
			self.__editRedoItem.setEnabled( changeHistory.canRedo() )
			self.__showUndoHistoryItem.setEnabled( True )
		else:
			self.__editUndoItem.setEnabled( False )
			self.__editRedoItem.setEnabled( False )
			self.__showUndoHistoryItem.setEnabled( False )
			
		
		
			

	
	def _onOpenNewWindow(self, subject):
		self._windowManager._createNewWindow( subject )
	
	
	
	def __onUndo(self):
		changeHistory = self._browser.getChangeHistory()
		if changeHistory.canUndo():
			changeHistory.concreteChangeHistory().undo()

	def __onRedo(self):
		changeHistory = self._browser.getChangeHistory()
		if changeHistory.canRedo():
			changeHistory.concreteChangeHistory().redo()


		

	def __onShowUndoHistory(self):
		changeHistory = self._browser.getChangeHistory().concreteChangeHistory()
		if changeHistory is not None:
			subject = DefaultPerspective.instance.objectSubject( changeHistory )
			self._browser.openSubjectInNewWindow( subject )




	def __onToggleTooltipHighlights(self):
		AttachTooltip.toggleHighlights()


	def __onShowAllTipBoxes(self):
		TipBox.resetTipHiddenStates()
class BurpExtender(IBurpExtender, IContextMenuFactory):
    # Implement IBurpExtender
    def registerExtenderCallbacks(self, callbacks):

        self.printHeader()

        # Set extension name
        callbacks.setExtensionName("Directory Listing Parser for Burp Suite")

        # Callbacks object
        self._callbacks = callbacks

        # Helpers object
        self._helpers = callbacks.getHelpers()

        # Register a factory for custom context menu items
        callbacks.registerContextMenuFactory(self)

        return

    # Create a menu item if the appropriate section of the UI is selected
    def createMenuItems(self, invocation):
        menu = []

        # Which part of the interface the user selects
        ctx = invocation.getInvocationContext()

        # Message Viewer Req/Res, Site Map Table, and Proxy History will show menu item if selected by the user
        if ctx == 2 or ctx == 3 or  ctx == 4 or ctx == 5 or ctx == 6:
            menu.append(JMenuItem("Import Directory Listing", None, actionPerformed=lambda x, inv=invocation: self.openGUI(inv)))

        return menu if menu else None

    # Create and place GUI components on JFrame
    def openGUI(self, invocation):
        try:
            # Get values from request or response the extension is invoked from and prepopulate GUI values
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0]
            originalHttpService = message.getHttpService()
            self.originalMsgProtocol = originalHttpService.getProtocol()
            self.originalMsgHost = originalHttpService.getHost()
            self.originalMsgPort = originalHttpService.getPort()
        except:
            self.originalMsgProtocol = ''
            self.originalMsgHost = ''
            self.originalMsgPort = ''

        try:
            self.cookies = self._callbacks.getCookieJarContents()
            self.cookie = ''
        except:
            pass

        self.SSL = 'http://'
        self.listType = ''
        self.parsedList = []

        # Set up main window (JFrame)
        self.window = JFrame("Directory Listing Parser for Burp Suite", preferredSize=(600, 475), windowClosing=self.closeUI)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10)
        self.window.contentPane.setBorder(emptyBorder)
        self.window.contentPane.layout = BorderLayout()

        # Main window title placed at the top of the main window with an invisible bottom border
        titlePanel = JPanel()
        titleBorder = BorderFactory.createEmptyBorder(0, 0, 10, 0)
        title = JLabel("Directory Listing Parser for Burp Suite", JLabel.CENTER)
        title.setBorder(titleBorder)
        title.setFont(Font("Default", Font.PLAIN, 18))
        titlePanel.add(title)
        self.window.contentPane.add("North", titlePanel)

        # Left panel for user input, consisting of hostname, directory prefix, ssl, port, type of listing, and file
        self.leftPanel = JPanel()
        self.leftPanel.layout = GridLayout(14, 1, 3, 3)
        hostnameLabel = JLabel("Hostname:")

        if self.originalMsgHost:
            self.hostnameTextField = JTextField(self.originalMsgHost.rstrip())
        else:
            self.hostnameTextField = JTextField('Hostname')

        dirPrefixLabel = JLabel("Full Directory Prefix (Windows):")
        self.dirPrefixField = JTextField('C:\\var\www\\')
        
        sslLabel = JLabel("SSL:")
        self.radioBtnSslEnabled = JRadioButton('Enabled (https)', actionPerformed=self.radioSsl)
        self.radioBtnSslDisabled = JRadioButton('Disabled (http)', actionPerformed=self.radioSsl)
        sslButtonGroup = ButtonGroup()
        sslButtonGroup.add(self.radioBtnSslEnabled)
        sslButtonGroup.add(self.radioBtnSslDisabled)
        
        if self.originalMsgProtocol == "https":
            self.radioBtnSslEnabled.setSelected(True)
        else:
            self.radioBtnSslDisabled.setSelected(True)
        
        portLabel = JLabel("Port:")

        if self.originalMsgPort:
            self.portTextField = JTextField(str(self.originalMsgPort).rstrip())
        else:
            self.portTextField = JTextField('80')

        osLabel = JLabel("Type of File Listing:")
        self.types = ('Windows \'dir /s\'', 'Linux \'ls -lR\'', 'Linux \'ls -R\'')
        self.comboListingType = JComboBox(self.types)
        uploadLabel = JLabel("Directory Listing File:")
        self.uploadTextField = JTextField('')
        uploadButton = JButton('Choose File', actionPerformed=self.chooseFile)

        self.leftPanel.add(hostnameLabel)
        self.leftPanel.add(self.hostnameTextField)
        self.leftPanel.add(dirPrefixLabel)
        self.leftPanel.add(self.dirPrefixField)
        self.leftPanel.add(sslLabel)
        self.leftPanel.add(self.radioBtnSslEnabled)
        self.leftPanel.add(self.radioBtnSslDisabled)
        self.leftPanel.add(portLabel)
        self.leftPanel.add(self.portTextField)
        self.leftPanel.add(osLabel)
        self.leftPanel.add(self.comboListingType)
        self.leftPanel.add(uploadLabel)
        self.leftPanel.add(self.uploadTextField)
        self.leftPanel.add(uploadButton)

        # Right panel consisting of a text area for the URL list
        self.UrlPanelLabel = JLabel("URL List:")
        self.textArea = JTextArea()
        self.textArea.setEditable(True)
        self.textArea.setFont(Font("Default", Font.PLAIN, 14))
        if self.cookies:
            self.textArea.append('Cookies Found:\n')
            for cookie in self.cookies:
                if cookie.getDomain() in self.originalMsgHost:
                    self.cookie += cookie.getName() + '=' + cookie.getValue() + '; '
                    self.textArea.append(cookie.getName() + '=' + cookie.getValue() + '\n')
        scrollArea = JScrollPane(self.textArea)
        scrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        scrollArea.setPreferredSize(Dimension(400, 200))
        self.rightPanel = JPanel()
        self.rightPanel.setLayout(BorderLayout(3, 3))
        self.rightPanel.add(self.UrlPanelLabel, BorderLayout.NORTH)
        self.rightPanel.add(scrollArea, BorderLayout.CENTER)
        
        # Panel for the generate URL list and import URL list buttons
        generatePanel = JPanel()
        generatePanel.layout = BorderLayout(3, 3)
        generateButton = JButton('Generate URL List', actionPerformed=self.generateUrlList)
        importButton = JButton('Import URL List to Burp Site Map', actionPerformed=self.confirmImport)
        generatePanel.add("North", generateButton)
        generatePanel.add("South", importButton)
        self.rightPanel.add("South", generatePanel)

        # Add the two main panels to the left and right sides
        self.window.contentPane.add("East", self.rightPanel)
        self.window.contentPane.add("West", self.leftPanel)

        # Create a panel to be used for the file chooser window
        self.uploadPanel = JPanel()
        
        self.window.pack()
        self.window.show()

    # JFileChooser and showDialog for the user to specify their directory listing input file
    def chooseFile(self, event):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("c files", ["c"])
        chooseFile.addChoosableFileFilter(filter)
        chooseFile.showDialog(self.uploadPanel, "Choose File")
        chosenFile = chooseFile.getSelectedFile()
        self.uploadTextField.text = str(chosenFile)

    # Set whether https is enabled.  Default is disabled (http)
    def radioSsl(self, event):
        if self.radioBtnSslEnabled.isSelected():
            self.SSL = 'https://'
        else:
            self.SSL = 'http://'

    # Create a parser object and pass the user's specified options.  Retrieve the results and print them to a text area
    def generateUrlList(self, event):
        fileListingType = self.comboListingType.selectedIndex
        self.listType = self.types[fileListingType]
        urlsMade = 0
        if os.path.isfile(self.uploadTextField.text):
            parser = ListingParser()
            parser.parse(self.hostnameTextField.getText(), self.dirPrefixField.getText().rstrip(), self.SSL, self.portTextField.getText(), self.listType, self.uploadTextField.getText())
            self.parsedList = parser.returnList()
            self.textArea.setText('')
            for item in self.parsedList:
                self.textArea.append(item + '\n')

            urlsMade = str(len(self.parsedList))
            if self.parsedList and urlsMade:
                self.textArea.append('\n' + 'Total Directories Found: ' + str(parser.directoryCount))
                self.textArea.append('\n' + 'Total URLs Created: ' + urlsMade)
            else:
                self.textArea.append('Error occurred during parsing.\n')
                self.textArea.append('Please make sure the directory listing is a valid format and all input is correct.\n')
                self.textArea.append('E-mail [email protected] with errors or for further help.')
        else:
            JOptionPane.showMessageDialog(None, 'ERROR: File is not valid file or not found!')

    def closeUI(self, event):
        self.window.setVisible(False)
        self.window.dispose()

    # This is initiated by the user selecting the 'import to burp' button.  Checks each generated URL for a valid response and adds it to the site map
    def importList(self):
        if self.parsedList:
            urlsAdded = 0
            # Loop through each URL and check the response.  If the response code is less than 404, add to site map
            for item in self.parsedList:
                # Pass exception if urlopen returns an http error if the URL is not reachable
                try:
                    code = urlopen(item).code
                    if code < 404:
                        javaURL = URL(item)
                        newRequest = self._helpers.buildHttpRequest(javaURL)
                        stringNewRequest = self._helpers.bytesToString(newRequest).rstrip()
                        if self.cookie:
                            stringNewRequest += '\nCookie: ' + self.cookie.rstrip('; ') + '\r\n\r\n'
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), stringNewRequest)
                        else:
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), newRequest)
                        self._callbacks.addToSiteMap(requestResponse)
                        urlsAdded += 1
                except Exception, e:
                    print e
                    pass
            JOptionPane.showMessageDialog(None, str(urlsAdded) + " URL(s) added to Burp site map.")
        else:
Exemplo n.º 11
0
class Config(ITab):
    """Defines the Configuration tab"""

    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)

        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass

    def build_ui(self):
        """Builds the configuration screen"""
        labels = JPanel(GridLayout(21, 1))
        checkbox = JCheckBox("Attempt to parse files for URL patterns?",
                             False, actionPerformed=self.set_parse)
        stats_box = JCheckBox("Show stats?", True,
                              actionPerformed=self.set_show_stats)
        # The two year old in me is laughing heartily
        plug_butt = JButton("Specify plugins location",
                            actionPerformed=self.set_plugin_loc)
        load_plug_butt = JButton("Select plugins",
                                 actionPerformed=self.p_build_ui)
        parse_butt = JButton("Parse directory", actionPerformed=self.parse)
        clear_butt = JButton("Clear text", actionPerformed=self.clear)
        spider_butt = JButton("Send to Spider", actionPerformed=self.scan)
        save_butt = JButton("Save config", actionPerformed=self.save)
        rest_butt = JButton("Restore config", actionPerformed=self.restore)
        source_butt = JButton("Input Source File/Directory",
                              actionPerformed=self.get_source_input)

        # Build grid
        labels.add(source_butt)
        labels.add(self.curr_conf)
        labels.add(JLabel("String Delimiter:"))
        labels.add(self.delim)
        labels.add(JLabel("Extension Whitelist:"))
        labels.add(self.ext_white_list)
        labels.add(JLabel("URL:"))
        labels.add(self.url)
        # Leaving these here for now.
        # labels.add(JLabel("Cookies:"))
        # labels.add(self.cookies)
        # labels.add(JLabel("HTTP Headers:"))
        # labels.add(self.headers)
        labels.add(checkbox)
        labels.add(stats_box)
        labels.add(plug_butt)
        labels.add(parse_butt)
        labels.add(JButton("Show all endpoints",
                           actionPerformed=self.print_endpoints))
        labels.add(clear_butt)
        labels.add(spider_butt)
        labels.add(JLabel(""))
        labels.add(save_butt)
        labels.add(rest_butt)
        labels.add(load_plug_butt)
        # Tool tips!
        self.delim.setToolTipText("Use to manipulate the final URL. "
                                  "See About tab for example.")
        self.ext_white_list.setToolTipText("Define a comma delimited list of"
                                           " file extensions to parse. Use *"
                                           " to parse all files.")
        self.url.setToolTipText("Enter the target URL")
        checkbox.setToolTipText("Parse files line by line using plugins"
                                " to enumerate language/framework specific"
                                " endpoints")
        parse_butt.setToolTipText("Attempt to enumerate application endpoints")
        clear_butt.setToolTipText("Clear status window and the parse results")
        spider_butt.setToolTipText("Process discovered endpoints")
        save_butt.setToolTipText("Saves the current config settings")
        rest_butt.setToolTipText("<html>Restores previous config settings:"
                                 "<br/>-Input Directory<br/>-String Delim"
                                 "<br/>-Ext WL<br/>-URL<br/>-Plugins")
        source_butt.setToolTipText("Select the application's "
                                   "source directory or file to parse")

        return labels

    def set_url(self, menu_url):
        """Changes the configuration URL to the one from the menu event"""
        self.url.setText(menu_url)

    # Event functions
    def set_parse(self, event):
        """
        Handles the click event from the UI checkbox
        to attempt code level parsing
        """
        self.parse_files = not self.parse_files
        if self.parse_files:
            if not self.loaded_plugins:
                self._plugins_missing_warning()

    def restore(self, event):
        """Attempts to restore the previously saved configuration."""
        jdump = None
        try:
            jdump = loads(self._callbacks.loadExtensionSetting("config"))
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll(
                "[!!] Error during restore!\n\tException: %s" % str(exc))
        if jdump is not None:
            self.url.setText(jdump.get('URL'))
            # self.cookies.setText(jdump.get('Cookies'))
            # self.headers.setText(jdump.get("Headers"))
            ewl = ""
            for ext in jdump.get('Extension Whitelist'):
                ewl += ext + ", "
            self.ext_white_list.setText(ewl[:-2])
            self.delim.setText(jdump.get('String Delimiter'))
            self.source_input = jdump.get("Input Directory")
            self.config['Plugin Folder'] = jdump.get("Plugin Folder")
            if (self.config['Plugin Folder'] is not None and
                    (len(self.plugins.values()) < 1)):
                self._load_plugins(self.config['Plugin Folder'])
            self._update()
            self.update_scroll("[^] Restore complete!")
        else:
            self.update_scroll("[!!] Restore failed!")

    def save(self, event=None):
        """
        Saves the configuration details to a Burp Suite's persistent store.
        """
        self._update()
        try:
            if not self._callbacks.isInScope(URL(self.url.getText())):
                self.update_scroll("[!!] URL provided is NOT in Burp Scope!")
        except MalformedURLException:  # If url field is blank we'll
            pass                       # still save the settings.

        try:
            self._callbacks.saveExtensionSetting("config", dumps(self.config))
            self.update_scroll("[^] Settings saved!")
        except Exception:
            self.update_scroll("[!!] Error saving settings to Burp Suite!")

    def parse(self, event):
        """
        Handles the click event from the UI.
        Attempts to parse the given directory
            (and/or source files) for url endpoints
        Saves the items found within the url_reqs list
        """
        self._update()

        file_set = set()
        fcount = 0
        other_dirs = set()
        self.ext_stats = {}
        if self.loaded_plugins:
            self.update_scroll("[^] Attempting to parse files" +
                               " for URL patterns. This might take a minute.")
        if path.isdir(self.source_input):
            for dirname, _, filenames in walk(self.source_input):
                for filename in filenames:
                    fcount += 1
                    ext = path.splitext(filename)[1]
                    count = self.ext_stats.get(ext, 0) + 1
                    filename = "%s/%s" % (dirname, filename)
                    self.ext_stats.update({ext: count})
                    if self.parse_files:
                        # i can haz threading?
                        file_set.update(self._code_as_endpoints(filename, ext))
                    elif self._ext_test(ext):
                        r_files, oths = self._files_as_endpoints(filename, ext)
                        file_set.update(r_files)
                        other_dirs.update(oths)
        elif path.isfile(self.source_input):
            ext = path.splitext(self.source_input)[1]
            file_set.update(self._code_as_endpoints(self.source_input, ext))
        else:
            self.update_scroll("[!!] Input Directory is not valid!")
        if len(other_dirs) > 0:
            self.update_scroll("[*] Found files matching file extension in:\n")
            for other_dir in other_dirs:
                self.update_scroll(" " * 4 + "%s\n" % other_dir)
        for item in file_set:
            if item.startswith("http://") or item.startswith("https://"):
                proto = item.split("//")[0] + '//'
                item = item.replace(proto, "")
            self.url_reqs.append(proto + item.replace('//', '/'))
        self._print_parsed_status(fcount)
        return (other_dirs, self.url_reqs)

    def scan(self, event):
        """
        handles the click event from the UI.
        Adds the given URL to the burp scope and sends the requests
        to the burp spider
        """
        temp_url = self.url.getText()
        if not self._callbacks.isInScope(URL(temp_url)):
            if not self.double_click:
                self.update_scroll("[!!] URL is not in scope! Press Send to "
                                   "Spider again to add to scope and scan!")
                self.double_click = True
                return
            else:
                self._callbacks.sendToSpider(URL(temp_url))
        self.update_scroll(
            "[^] Sending %d requests to Spider" % len(self.url_reqs))
        for req in self.url_reqs:
            self._callbacks.sendToSpider(URL(req))

    def clear(self, event):
        """Clears the viewport and the current parse exts"""
        self.view_port_text.setText("===SpyDir===")
        self.ext_stats = {}

    def print_endpoints(self, event):
        """Prints the discovered endpoints to the status window."""
        req_str = ""
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Printing all discovered endpoints:")
            for req in self.url_reqs:
                req_str += "    %s\n" % req
        else:
            req_str = "[!!] No endpoints discovered"
        self.update_scroll(req_str)

    def set_show_stats(self, event):
        """Modifies the show stats setting"""
        self.print_stats = not self.print_stats

    def get_source_input(self, event):
        """Sets the source dir/file for parsing"""
        source_chooser = JFileChooser()
        source_chooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES)
        source_chooser.showDialog(self.tab, "Choose Source Location")
        chosen_source = source_chooser.getSelectedFile()
        try:
            self.source_input = chosen_source.getAbsolutePath()
        except AttributeError:
            pass
        if self.source_input is not None:
            self.update_scroll("[*] Source location: %s" % self.source_input)
            self.curr_conf.setText(self.source_input)

    # Plugin functions
    def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys():
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set

    def set_plugin_loc(self, event):
        """Attempts to load plugins from a specified location"""
        if self.config['Plugin Folder'] is not None:
            choose_plugin_location = JFileChooser(self.config['Plugin Folder'])
        else:
            choose_plugin_location = JFileChooser()
        choose_plugin_location.setFileSelectionMode(
            JFileChooser.DIRECTORIES_ONLY)
        choose_plugin_location.showDialog(self.tab, "Choose Folder")
        chosen_folder = choose_plugin_location.getSelectedFile()
        self.config['Plugin Folder'] = chosen_folder.getAbsolutePath()
        self._load_plugins(self.config['Plugin Folder'])

    def _load_plugins(self, folder):
        """
        Parses a local directory to get the plugins
            related to code level scanning
        """
        report = ""
        if len(self.plugins.keys()) > 0:
            report = "[^] Plugins reloaded!"
        for _, _, filenames in walk(folder):
            for p_name in filenames:
                n_e = path.splitext(p_name)  # n_e = name_extension
                if n_e[1] == ".py":
                    f_loc = "%s/%s" % (folder, p_name)
                    loaded_plug = self._validate_plugin(n_e[0], f_loc)
                    if loaded_plug:
                        self.loaded_p_list.add(loaded_plug)
                        if not report.startswith("[^]"):
                            report += "%s loaded\n" % loaded_plug.get_name()

        self._dictify(self.loaded_p_list)
        if len(self.plugins.keys()) > 0:
            self.loaded_plugins = True
        else:
            report = "[!!] Plugins load failure"
            self.loaded_plugins = False
        self.update_scroll(report)
        return report

    def _validate_plugin(self, p_name, f_loc):
        """
        Attempts to verify the manditory plugin functions to prevent broken
        plugins from loading.
        Generates an error message if plugin does not contain an appropriate
        function.
        """
        # Load the plugin
        try:
            plug = load_source(p_name, f_loc)
        except Exception as exc:  # this needs to be generic.
            self.update_scroll(
                "[!!] Error loading: %s\n\tType:%s Error: %s"
                % (f_loc, type(exc), str(exc)))
        # Verify the plugin's functions
        funcs = dir(plug)
        err = []
        if "get_name" not in funcs:
            err.append("get_name()")
        if "get_ext" not in funcs:
            err.append("get_ext()")
        if "run" not in funcs:
            err.append("run()")

        # Report errors & return
        if len(err) < 1:
            return Plugin(plug, True)
        else:
            for issue in err:
                self.update_scroll("[!!] %s is missing: %s func" %
                                   (p_name, issue))
            return None

    def _dictify(self, plist):
        """Converts the list of loaded plugins (plist) into a dictionary"""
        for p in plist:
            exts = p.get_ext().upper()
            for ext in exts.split(","):
                prev_load = self.plugins.get(ext, [])
                prev_load.append(p)
                self.plugins[ext] = prev_load

    # Status window functions
    def _print_parsed_status(self, fcount):
        """Prints the parsed directory status information"""
        if self.parse_files and not self.loaded_plugins:
            self._plugins_missing_warning()
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Example URL: %s" % self.url_reqs[0])

        if self.print_stats:
            report = (("[*] Found: %r files to be requested.\n\n" +
                       "[*] Stats: \n    " +
                       "Found: %r files.\n") % (len(self.url_reqs), fcount))
            if len(self.ext_stats) > 0:
                report += ("[*] Extensions found: %s"
                           % str(dumps(self.ext_stats,
                                       sort_keys=True, indent=4)))
        else:
            report = ("[*] Found: %r files to be requested.\n" %
                      len(self.url_reqs))
        self.update_scroll(report)
        return report

    def _plugins_missing_warning(self):
        """Prints a warning message"""
        self.update_scroll("[!!] No plugins loaded!")

    def update_scroll(self, text):
        """Updates the view_port_text with the new information"""
        temp = self.view_port_text.getText().strip()
        if text not in temp or text[0:4] == "[!!]":
            self.view_port_text.setText("%s\n%s" % (temp, text))
        elif not temp.endswith("[^] Status unchanged"):
            self.view_port_text.setText("%s\n[^] Status unchanged" % temp)

    # Internal functions
    def _code_as_endpoints(self, filename, ext):
        file_set = set()
        file_url = self.config.get("URL")
        if self.loaded_plugins:
            if self._ext_test(ext):
                file_set.update(
                    self._parse_file(filename, file_url))
            else:
                file_set.update(
                    self._parse_file(filename, file_url))
        return file_set

    def _files_as_endpoints(self, filename, ext):
        """Generates endpoints via files with the appropriate extension(s)"""
        file_url = self.config.get("URL")
        broken_splt = ""
        other_dirs = set()  # directories outside of the String Delim.
        file_set = set()
        str_del = self.config.get("String Delimiter")
        if not str_del:
            self.update_scroll("[!!] No available String Delimiter!")
            return
        spl_str = filename.split(str_del)

        try:
            # Fix for index out of bounds exception while parsing
            # subfolders _not_ included by the split
            if len(spl_str) > 1:
                file_url += ((spl_str[1])
                             .replace('\\', '/'))
            else:
                broken_splt = filename.split(self.source_input)[1]
                other_dirs.add(broken_splt)
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll("[!!] Error parsing: " +
                               "%s\n\tException: %s"
                               % (filename, str(exc)))
        if self._ext_test(ext):
            if file_url != self.config.get("URL"):
                file_set.add(file_url)
        else:
            other_dirs.discard(broken_splt)
        return file_set, other_dirs

    def _ext_test(self, ext):
        """Litmus test for extension whitelist"""
        val = False
        if len(self.config.get("Extension Whitelist")) > 0:
            val = (len(ext) > 0 and
                   (ext.strip().upper()
                    in self.config.get("Extension Whitelist")))
        elif "*" in self.config.get("Extension Whitelist"):
            val = True
        return val

    def _update(self):
        """Updates internal data"""
        self.config["Input Directory"] = self.source_input
        self.config["String Delimiter"] = self.delim.getText()

        white_list_text = self.ext_white_list.getText()
        self.config["Extension Whitelist"] = white_list_text.upper().split(',')
        file_url = self.url.getText()
        if not file_url.endswith('/') and file_url != "":
            file_url += '/'

        self.config["URL"] = file_url
        # self.config["Cookies"] = self.cookies.getText()
        # self.config["Headers"] = self.headers.getText()
        del self.url_reqs[:]
        self.curr_conf.setText(self.source_input)

    # Window sizing functions
    def resize(self, event):
        """Resizes the window to better fit Burp"""
        if self.parent_window is not None:
            par_size = self.parent_window.getSize()
            par_size.setSize(par_size.getWidth() * .99,
                             par_size.getHeight() * .9)
            self.tab.setPreferredSize(par_size)
            self.parent_window.validate()
            self.parent_window.switch_focus()

    def p_close(self, event):
        """
        Handles the window close event.
        """
        self.window.setVisible(False)
        self.window.dispose()

    def p_build_ui(self, event):
        """
        Adds a list of checkboxes, one for each loaded plugin
        to the Selct plugins window
        """
        if not self.loaded_p_list:
            self.update_scroll("[!!] No plugins loaded!")
            return

        scroll_pane = JScrollPane()
        scroll_pane.setPreferredSize(Dimension(200, 250))
        check_frame = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.FIRST_LINE_START

        for plug in self.loaded_p_list:
            check_frame.add(JCheckBox(plug.get_name(), plug.enabled,
                                      actionPerformed=self.update_box),
                            constraints)
            constraints.gridy += 1

        vport = JViewport()
        vport.setView(check_frame)
        scroll_pane.setViewport(vport)
        self.window.contentPane.add(scroll_pane)
        self.window.pack()
        self.window.setVisible(True)

    def update_box(self, event):
        """
        Handles the check/uncheck event for the plugin's box.
        """
        for plug in self.loaded_p_list:
            if plug.get_name() == event.getActionCommand():
                plug.enabled = not plug.enabled
                if plug.enabled:
                    self.update_scroll("[^] Enabled: %s" %
                                       event.getActionCommand())
                else:
                    self.update_scroll("[^] Disabled: %s" %
                                       event.getActionCommand())

    # ITab required functions
    @staticmethod
    def getTabCaption():
        """Returns the name of the Burp Suite Tab"""
        return "SpyDir"

    def getUiComponent(self):
        """Returns the UI component for the Burp Suite tab"""
        return self.tab
class MenueFrame(object):
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()

   def show(self):
      self.frame.visible = True

   def getFrame(self):
      return self.frame

   def setSaveActive(self):
      self.saveButton.setEnabled(True)
      self.show()

   def setSaveInactive(self):
      self.saveButton.setEnabled(False)
      self.show()

   def setMainDir(self, path):
      self.mainDir = path
      self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))

   def getMainDir(self):
      return self.mainDir

   def setProgBarMax(self, maximum):
      self.ProgBar.setMaximum(maximum)

   def setProgBarVal(self, value):
      self.ProgBar.setValue(value)

   def close():
      WindowManager.removeWindow(self.frame)
      self.frame.dispose()     
Exemplo n.º 13
0
# Ensure we have an APIKEY
elif APIKEY == "":
    show_error_message("VirusTotal API key must be set.")
# Initial checks good, lets run the script
else:
    global cancelled
    cancelled = False

    # Do some UI setup here to keep the main() method a little easier to read
    jframe = JFrame("VirusTotal Integration",
                    defaultCloseOperation=JFrame.DISPOSE_ON_CLOSE,
                    size=(300, 100),
                    locationRelativeTo=None)
    jframe.setUndecorated(True)
    statusLabel = JLabel("", JLabel.CENTER)
    jframe.setResizable(False)
    jframe.setLayout(GridLayout(3, 1))
    statusLabel.setSize(300, 50)
    jframe.getContentPane().add(statusLabel)
    jbutton = JButton('Cancel')
    jbutton.addActionListener(cancel)

    # Run the main code function
    result = main()

    # Clean up jframe and show the result message
    jframe.setVisible(False)
    jframe.dispose()
    if result:
        JOptionPane.showMessageDialog(None, result)
Exemplo n.º 14
0
]
nbButtons = len(buttons)

win = JFrame("Music Player")
win.getContentPane().setLayout(FlowLayout())
for i in range(nbButtons):
    win.getContentPane().add(buttons[i])
win.getContentPane().add(status)
win.setTitle("Music Player")
win.setSize(700, 100)
win.setLocation(200, 100)
win.setVisible(True)
status.setText("Please open a WAV music file")
doDisplayTime = True

# Display loop
while (win.isVisible()):
    if player != None:
        if doDisplayTime:
            status.setText("Current time: " + getClipTime())
        else:
            status.setText("Current volume: " + str(volume))
            SoundPlayer.delay(300)
            doDisplayTime = True
    SoundPlayer.delay(100)

# Cleanup
if player != None:
    player.stop()
win.dispose()  # free resources
Exemplo n.º 15
0
class Config(ITab):
    """Defines the Configuration tab"""

    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)
        self.path_vars = JTextField(30)


        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass

    def build_ui(self):
        """Builds the configuration screen"""
        labels = JPanel(GridLayout(21, 1))
        checkbox = JCheckBox("Attempt to parse files for URL patterns?",
                             False, actionPerformed=self.set_parse)
        stats_box = JCheckBox("Show stats?", True,
                              actionPerformed=self.set_show_stats)
        # The two year old in me is laughing heartily
        plug_butt = JButton("Specify plugins location",
                            actionPerformed=self.set_plugin_loc)
        load_plug_butt = JButton("Select plugins",
                                 actionPerformed=self.p_build_ui)
        parse_butt = JButton("Parse directory", actionPerformed=self.parse)
        clear_butt = JButton("Clear text", actionPerformed=self.clear)
        spider_butt = JButton("Send to Spider", actionPerformed=self.scan)
        save_butt = JButton("Save config", actionPerformed=self.save)
        rest_butt = JButton("Restore config", actionPerformed=self.restore)
        source_butt = JButton("Input Source File/Directory",
                              actionPerformed=self.get_source_input)

        # Build grid
        labels.add(source_butt)
        labels.add(self.curr_conf)
        labels.add(JLabel("String Delimiter:"))
        labels.add(self.delim)
        labels.add(JLabel("Extension Whitelist:"))
        labels.add(self.ext_white_list)
        labels.add(JLabel("URL:"))
        labels.add(self.url)
        labels.add(JLabel("Path Variables"))
        labels.add(self.path_vars)
        # Leaving these here for now.
        # labels.add(JLabel("Cookies:"))
        # labels.add(self.cookies)
        # labels.add(JLabel("HTTP Headers:"))
        # labels.add(self.headers)
        labels.add(checkbox)
        labels.add(stats_box)
        labels.add(plug_butt)
        labels.add(parse_butt)
        labels.add(JButton("Show all endpoints",
                           actionPerformed=self.print_endpoints))
        labels.add(clear_butt)
        labels.add(spider_butt)
        labels.add(JLabel(""))
        labels.add(save_butt)
        labels.add(rest_butt)
        labels.add(load_plug_butt)
        # Tool tips!
        self.delim.setToolTipText("Use to manipulate the final URL. "
                                  "See About tab for example.")
        self.ext_white_list.setToolTipText("Define a comma delimited list of"
                                           " file extensions to parse. Use *"
                                           " to parse all files.")
        self.url.setToolTipText("Enter the target URL")
        checkbox.setToolTipText("Parse files line by line using plugins"
                                " to enumerate language/framework specific"
                                " endpoints")
        parse_butt.setToolTipText("Attempt to enumerate application endpoints")
        clear_butt.setToolTipText("Clear status window and the parse results")
        spider_butt.setToolTipText("Process discovered endpoints")
        save_butt.setToolTipText("Saves the current config settings")
        rest_butt.setToolTipText("<html>Restores previous config settings:"
                                 "<br/>-Input Directory<br/>-String Delim"
                                 "<br/>-Ext WL<br/>-URL<br/>-Plugins")
        source_butt.setToolTipText("Select the application's "
                                   "source directory or file to parse")
        self.path_vars.setToolTipText("Supply a JSON object with values"
                                      "for dynamically enumerated query"
                                      "string variables")

        return labels

    def set_url(self, menu_url):
        """Changes the configuration URL to the one from the menu event"""
        self.url.setText(menu_url)

    # Event functions
    def set_parse(self, event):
        """
        Handles the click event from the UI checkbox
        to attempt code level parsing
        """
        self.parse_files = not self.parse_files
        if self.parse_files:
            if not self.loaded_plugins:
                self._plugins_missing_warning()

    def restore(self, event):
        """Attempts to restore the previously saved configuration."""
        jdump = None
        try:
            jdump = loads(self._callbacks.loadExtensionSetting("config"))
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll(
                "[!!] Error during restore!\n\tException: %s" % str(exc))
        if jdump is not None:
            self.url.setText(jdump.get('URL'))
            # self.cookies.setText(jdump.get('Cookies'))
            # self.headers.setText(jdump.get("Headers"))
            ewl = ""
            for ext in jdump.get('Extension Whitelist'):
                ewl += ext + ", "
            self.ext_white_list.setText(ewl[:-2])
            self.delim.setText(jdump.get('String Delimiter'))
            self.source_input = jdump.get("Input Directory")
            self.config['Plugin Folder'] = jdump.get("Plugin Folder")
            if (self.config['Plugin Folder'] is not None and
                    (len(self.plugins.values()) < 1)):
                self._load_plugins(self.config['Plugin Folder'])
            self._update()
            self.update_scroll("[^] Restore complete!")
        else:
            self.update_scroll("[!!] Restore failed!")

    def save(self, event=None):
        """
        Saves the configuration details to a Burp Suite's persistent store.
        """
        self._update()
        try:
            if not self._callbacks.isInScope(URL(self.url.getText())):
                self.update_scroll("[!!] URL provided is NOT in Burp Scope!")
        except MalformedURLException:  # If url field is blank we'll
            pass                       # still save the settings.
        try:
            self._callbacks.saveExtensionSetting("config", dumps(self.config))
            self.update_scroll("[^] Settings saved!")
        except Exception:
            self.update_scroll("[!!] Error saving settings to Burp Suite!")

    def parse(self, event):
        """
        Handles the click event from the UI.
        Attempts to parse the given directory
            (and/or source files) for url endpoints
        Saves the items found within the url_reqs list
        """
        self._update()

        file_set = set()
        fcount = 0
        other_dirs = set()
        self.ext_stats = {}
        if self.loaded_plugins:
            self.update_scroll("[^] Attempting to parse files" +
                               " for URL patterns. This might take a minute.")
        if path.isdir(self.source_input):
            for dirname, _, filenames in walk(self.source_input):
                for filename in filenames:
                    fcount += 1
                    ext = path.splitext(filename)[1]
                    count = self.ext_stats.get(ext, 0) + 1
                    filename = "%s/%s" % (dirname, filename)
                    self.ext_stats.update({ext: count})
                    if self.parse_files and self._ext_test(ext):
                        # i can haz threading?
                        file_set.update(self._code_as_endpoints(filename, ext))
                    elif self._ext_test(ext):
                        r_files, oths = self._files_as_endpoints(filename, ext)
                        file_set.update(r_files)
                        other_dirs.update(oths)
        elif path.isfile(self.source_input):
            ext = path.splitext(self.source_input)[1]
            file_set.update(self._code_as_endpoints(self.source_input, ext))
        else:
            self.update_scroll("[!!] Input Directory is not valid!")
        if len(other_dirs) > 0:
            self.update_scroll("[*] Found files matching file extension in:\n")
            for other_dir in other_dirs:
                self.update_scroll(" " * 4 + "%s\n" % other_dir)
        self._handle_path_vars(file_set)
        self._print_parsed_status(fcount)
        return (other_dirs, self.url_reqs)

    def _handle_path_vars(self, file_set):
        proto = 'http://'
        for item in file_set:
            if item.startswith("http://") or item.startswith("https://"):
                proto = item.split("//")[0] + '//'
                item = item.replace(proto, "")
                item = self._path_vars(item)
            self.url_reqs.append(proto + item.replace('//', '/'))

    def _path_vars(self, item):
        p_vars = None
        if self.path_vars.getText():
            try:
                p_vars = loads(str(self.path_vars.getText()))
            except:
                self.update_scroll("[!] Error reading supplied Path Variables!")
        if p_vars is not None:
            rep_str = ""
            try:
                for k in p_vars.keys():
                    rep_str += "[^] Replacing %s with %s!\n" % (k, str(p_vars.get(k)))
                self.update_scroll(rep_str)
                for k in p_vars.keys():
                    if str(k) in item:
                        item = item.replace(k, str(p_vars.get(k)))
            except AttributeError:
                self.update_scroll("[!] Error reading supplied Path Variables! This needs to be a JSON dictionary!")
        return item
            
            
    def scan(self, event):
        """
        handles the click event from the UI.
        Adds the given URL to the burp scope and sends the requests
        to the burp spider
        """
        temp_url = self.url.getText()
        if not self._callbacks.isInScope(URL(temp_url)):
            if not self.double_click:
                self.update_scroll("[!!] URL is not in scope! Press Send to "
                                   "Spider again to add to scope and scan!")
                self.double_click = True
                return
            else:
                self._callbacks.sendToSpider(URL(temp_url))
        self.update_scroll(
            "[^] Sending %d requests to Spider" % len(self.url_reqs))
        for req in self.url_reqs:
            self._callbacks.sendToSpider(URL(req))

    def clear(self, event):
        """Clears the viewport and the current parse exts"""
        self.view_port_text.setText("===SpyDir===")
        self.ext_stats = {}

    def print_endpoints(self, event):
        """Prints the discovered endpoints to the status window."""
        req_str = ""
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Printing all discovered endpoints:")
            for req in sorted(self.url_reqs):
                req_str += "    %s\n" % req
        else:
            req_str = "[!!] No endpoints discovered"
        self.update_scroll(req_str)

    def set_show_stats(self, event):
        """Modifies the show stats setting"""
        self.print_stats = not self.print_stats

    def get_source_input(self, event):
        """Sets the source dir/file for parsing"""
        source_chooser = JFileChooser()
        source_chooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES)
        source_chooser.showDialog(self.tab, "Choose Source Location")
        chosen_source = source_chooser.getSelectedFile()
        try:
            self.source_input = chosen_source.getAbsolutePath()
        except AttributeError:
            pass
        if self.source_input is not None:
            self.update_scroll("[*] Source location: %s" % self.source_input)
            self.curr_conf.setText(self.source_input)

    # Plugin functions
    def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys() and self._ext_test(ext):
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set

    def set_plugin_loc(self, event):
        """Attempts to load plugins from a specified location"""
        if self.config['Plugin Folder'] is not None:
            choose_plugin_location = JFileChooser(self.config['Plugin Folder'])
        else:
            choose_plugin_location = JFileChooser()
        choose_plugin_location.setFileSelectionMode(
            JFileChooser.DIRECTORIES_ONLY)
        choose_plugin_location.showDialog(self.tab, "Choose Folder")
        chosen_folder = choose_plugin_location.getSelectedFile()
        self.config['Plugin Folder'] = chosen_folder.getAbsolutePath()
        self._load_plugins(self.config['Plugin Folder'])

    def _load_plugins(self, folder):
        """
        Parses a local directory to get the plugins
            related to code level scanning
        """
        report = ""
        if len(self.plugins.keys()) > 0:
            report = "[^] Plugins reloaded!"
        for _, _, filenames in walk(folder):
            for p_name in filenames:
                n_e = path.splitext(p_name)  # n_e = name_extension
                if n_e[1] == ".py":
                    f_loc = "%s/%s" % (folder, p_name)
                    loaded_plug = self._validate_plugin(n_e[0], f_loc)
                    if loaded_plug:
                        for p in self.loaded_p_list:
                            if p.get_name() == loaded_plug.get_name():
                                self.loaded_p_list.discard(p)
                        self.loaded_p_list.add(loaded_plug)
                        if not report.startswith("[^]"):
                            report += "%s loaded\n" % loaded_plug.get_name()

        self._dictify(self.loaded_p_list)
        if len(self.plugins.keys()) > 0:
            self.loaded_plugins = True
        else:
            report = "[!!] Plugins load failure"
            self.loaded_plugins = False
        self.update_scroll(report)
        return report

    def _validate_plugin(self, p_name, f_loc):
        """
        Attempts to verify the manditory plugin functions to prevent broken
        plugins from loading.
        Generates an error message if plugin does not contain an appropriate
        function.
        """
        # Load the plugin
        try:
            plug = load_source(p_name, f_loc)
        except Exception as exc:  # this needs to be generic.
            self.update_scroll(
                "[!!] Error loading: %s\n\tType:%s Error: %s"
                % (f_loc, type(exc), str(exc)))
        # Verify the plugin's functions
        funcs = dir(plug)
        err = []
        if "get_name" not in funcs:
            err.append("get_name()")
        if "get_ext" not in funcs:
            err.append("get_ext()")
        if "run" not in funcs:
            err.append("run()")

        # Report errors & return
        if len(err) < 1:
            return Plugin(plug, True)
        for issue in err:
            self.update_scroll("[!!] %s is missing: %s func" %
                               (p_name, issue))
        return None

    def _dictify(self, plist):
        """Converts the list of loaded plugins (plist) into a dictionary"""
        for p in plist:
            exts = p.get_ext().upper()
            for ext in exts.split(","):
                prev_load = self.plugins.get(ext, [])
                prev_load.append(p)
                self.plugins[ext] = prev_load

    # Status window functions
    def _print_parsed_status(self, fcount):
        """Prints the parsed directory status information"""
        if self.parse_files and not self.loaded_plugins:
            self._plugins_missing_warning()
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Example URL: %s" % self.url_reqs[0])

        if self.print_stats:
            report = (("[*] Found: %r files to be requested.\n\n" +
                       "[*] Stats: \n    " +
                       "Found: %r files.\n") % (len(self.url_reqs), fcount))
            if len(self.ext_stats) > 0:
                report += ("[*] Extensions found: %s"
                           % str(dumps(self.ext_stats,
                                       sort_keys=True, indent=4)))
        else:
            report = ("[*] Found: %r files to be requested.\n" %
                      len(self.url_reqs))
        self.update_scroll(report)
        return report

    def _plugins_missing_warning(self):
        """Prints a warning message"""
        self.update_scroll("[!!] No plugins loaded!")

    def update_scroll(self, text):
        """Updates the view_port_text with the new information"""
        temp = self.view_port_text.getText().strip()
        if text not in temp or text[0:4] == "[!!]":
            self.view_port_text.setText("%s\n%s" % (temp, text))
        elif not temp.endswith("[^] Status unchanged"):
            self.view_port_text.setText("%s\n[^] Status unchanged" % temp)

    # Internal functions
    def _code_as_endpoints(self, filename, ext):
        file_set = set()
        file_url = self.config.get("URL")
        if self.loaded_plugins or ext == '.txt':
            if self._ext_test(ext):
                file_set.update(
                    self._parse_file(filename, file_url))
            else:
                file_set.update(
                    self._parse_file(filename, file_url))
        return file_set

    def _files_as_endpoints(self, filename, ext):
        """Generates endpoints via files with the appropriate extension(s)"""
        file_url = self.config.get("URL")
        broken_splt = ""
        other_dirs = set()  # directories outside of the String Delim.
        file_set = set()
        str_del = self.config.get("String Delimiter")
        if not str_del:
            self.update_scroll("[!!] No available String Delimiter!")
            return
        spl_str = filename.split(str_del)

        try:
            # Fix for index out of bounds exception while parsing
            # subfolders _not_ included by the split
            if len(spl_str) > 1:
                file_url += ((spl_str[1])
                             .replace('\\', '/'))
            else:
                broken_splt = filename.split(self.source_input)[1]
                other_dirs.add(broken_splt)
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll("[!!] Error parsing: " +
                               "%s\n\tException: %s"
                               % (filename, str(exc)))
        if self._ext_test(ext):
            if file_url != self.config.get("URL"):
                file_set.add(file_url)
        else:
            other_dirs.discard(broken_splt)
        return file_set, other_dirs

    def _ext_test(self, ext):
        """Litmus test for extension whitelist"""
        val = False
        if "*" in self.config.get("Extension Whitelist"):
            val = True
        else:
            val = (len(ext) > 0 and
                   (ext.strip().upper()
                    in self.config.get("Extension Whitelist")))
        return val

    def _update(self):
        """Updates internal data"""
        self.config["Input Directory"] = self.source_input
        self.config["String Delimiter"] = self.delim.getText()

        white_list_text = self.ext_white_list.getText()
        self.config["Extension Whitelist"] = white_list_text.upper().split(',')
        file_url = self.url.getText()
        if not (file_url.startswith('https://') or file_url.startswith('http://')):
            self.update_scroll("[!] Assuming protocol! Default value: 'http://'")
            file_url = 'http://' + file_url
            self.url.setText(file_url)

        if not file_url.endswith('/') and file_url != "":
            file_url += '/'

        self.config["URL"] = file_url
        # self.config["Cookies"] = self.cookies.getText()
        # self.config["Headers"] = self.headers.getText()
        del self.url_reqs[:]
        self.curr_conf.setText(self.source_input)

    # Window sizing functions
    def resize(self, event):
        """Resizes the window to better fit Burp"""
        if self.parent_window is not None:
            par_size = self.parent_window.getSize()
            par_size.setSize(par_size.getWidth() * .99,
                             par_size.getHeight() * .9)
            self.tab.setPreferredSize(par_size)
            self.parent_window.validate()
            self.parent_window.switch_focus()

    def p_close(self, event):
        """
        Handles the window close event.
        """
        self.window.setVisible(False)
        self.window.dispose()

    def p_build_ui(self, event):
        """
        Adds a list of checkboxes, one for each loaded plugin
        to the Selct plugins window
        """
        if not self.loaded_p_list:
            self.update_scroll("[!!] No plugins loaded!")
            return

        scroll_pane = JScrollPane()
        scroll_pane.setPreferredSize(Dimension(200, 250))
        check_frame = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.FIRST_LINE_START

        for plug in self.loaded_p_list:
            check_frame.add(JCheckBox(plug.get_name(), plug.enabled,
                                      actionPerformed=self.update_box),
                            constraints)
            constraints.gridy += 1

        vport = JViewport()
        vport.setView(check_frame)
        scroll_pane.setViewport(vport)
        self.window.contentPane.add(scroll_pane)
        self.window.pack()
        self.window.setVisible(True)

    def update_box(self, event):
        """
        Handles the check/uncheck event for the plugin's box.
        """
        for plug in self.loaded_p_list:
            if plug.get_name() == event.getActionCommand():
                plug.enabled = not plug.enabled
                if plug.enabled:
                    self.update_scroll("[^] Enabled: %s" %
                                       event.getActionCommand())
                else:
                    self.update_scroll("[^] Disabled: %s" %
                                       event.getActionCommand())

    # ITab required functions
    @staticmethod
    def getTabCaption():
        """Returns the name of the Burp Suite Tab"""
        return "SpyDir"

    def getUiComponent(self):
        """Returns the UI component for the Burp Suite tab"""
        return self.tab
Exemplo n.º 16
0
# http://www.jython.org/jythonbook/en/1.0/GUIApplications.html
from java.awt import Component
from javax.swing import JTextArea, JFrame

import time

frame = JFrame('Message',
            defaultCloseOperation = JFrame.DO_NOTHING_ON_CLOSE,
            size = (300, 300)
        )

t = JTextArea(text = 'Hello\nworld',
              editable = False,
              wrapStyleWord = True,
              lineWrap = True,
              alignmentX = Component.LEFT_ALIGNMENT,
              size = (300, 1)
             )
frame.add(t)
frame.visible = True
sleep(2)
frame.visible = False
sleep(0.5)
t.text = "{}\n{}".format("Hello",time.asctime())
frame.visible = True
sleep(2)
frame.visible = False
frame.dispose()
frame = None
Exemplo n.º 17
0
class Menue(object):
    def __init__(self, p):
        self.cellCounter = 1
        self.olay = Overlay()
        self.position = p
        print p.getRoiPath()
        if p.getRoiPath() != None:         # check if there is an existing overlay file and load it!
            p.loadRois()

        self.frame = JFrame("CellCropper", size=(200,200))
        self.frame.setLocation(20,120)
        self.Panel = JPanel(GridLayout(0,1))
        self.frame.add(self.Panel)
        #self.nameField = JTextField("p" + "_c",15)
        self.nameField = JTextField("p" + str(self.position.getID()) + "_c",15)
        self.Panel.add(self.nameField)
        self.cutoutButton = JButton("Cut out cell",actionPerformed=cut)
        self.Panel.add(self.cutoutButton)
        self.delOlButton = JButton("Delete Overlay",actionPerformed=delOverlay)
        self.Panel.add(self.delOlButton)
        self.saveOlButton = JButton("Save Overlay",actionPerformed=saveOverlay)
        self.Panel.add(self.saveOlButton) 
        self.quitButton = JButton("Quit script",actionPerformed=quit)
        self.Panel.add(self.quitButton)
        self.frame.pack()
        WindowManager.addWindow(self.frame)
        self.show()
        #IJ.setTool("freehand")

    '''def getPosition(self, path, filename):
       moved to containers.position.determineID(path, filename)'''

    def eventtest(self, event):
        print "eventtest"

    def setTextField(self, pos):
        name = "p" + str(pos) + "_c"
        self.nameField.setText(name)

    def openOl(self, path, fileName):
        print "aaaaah"

    def show(self):
        self.frame.visible = True

    def close(self):
        if self.olay != None:
            yncd = YesNoCancelDialog(self.frame, "Save overlay?", "Save overlay?") #frame, title, message
            if yncd.yesPressed():
                self.saveOverlay()
        WindowManager.removeWindow(self.frame)
        self.frame.dispose()
        
    def resetCounter(self):
        self.cellCounter = 0
        
    def increaseCounter(self):
        self.cellCounter += 1
        
    def setCounter(self):
        self.cellCounter += 1
        
    #'get' functions
    def getImp(self):
        return self.imp
    
    def getCounter(self):
        return self.cellCounter
        
    def getFrame(self):
        return self.frame
        
    def getFilePath(self):
        return self.filePath

    def getTextField(self):
        return self.nameField.text
    
    def getPosition(self):
        return self.position
    
    # overlay functions
    def addOlay(self, roi):
        self.olay.add(roi)

    def getOverlay(self):
        return self.olay

    def clearOverlay(self):
        self.olay.clear()
        self.cellCounter = 1

    def saveOverlay(self):
        self.position.saveRois()   
Exemplo n.º 18
0
class NewAccountGUI:
    def __init__(self, amgui):
        self.amgui = amgui
        self.am = amgui.acctmanager
        self.buildgwinfo()
        self.autologin = JCheckBox("Automatically Log In")
        self.acctname = JTextField()
        self.gwoptions = JPanel(doublebuffered)
        self.gwoptions.border = TitledBorder("Gateway Options")
        self.buildgwoptions("Twisted")
        self.mainframe = JFrame("New Account Window")
        self.buildpane()

    def buildgwinfo(self):
        self.gateways = {
            "Twisted": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField("twistedmatrix.com"),
                "port": JTextField("8787"),
                "service": JTextField("twisted.words"),
                "persp": JTextField(),
            },
            "AIM": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField("toc.oscar.aol.com"),
                "port": JTextField("9898"),
            },
            "IRC": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField(),
                "port": JTextField("6667"),
                "channels": JTextField(),
            },
        }
        self.displayorder = {
            "Twisted": [
                ["Identity Name", "ident"],
                ["Password", "passwd"],
                ["Host", "host"],
                ["Port", "port"],
                ["Service Name", "service"],
                ["Perspective Name", "persp"],
            ],
            "AIM": [["Screen Name", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"]],
            "IRC": [
                ["Nickname", "ident"],
                ["Password", "passwd"],
                ["Host", "host"],
                ["Port", "port"],
                ["Channels", "channels"],
            ],
        }

    def buildgwoptions(self, gw):
        self.gwoptions.removeAll()
        self.gwoptions.layout = GridLayout(len(self.gateways[gw]), 2)
        for mapping in self.displayorder[gw]:
            self.gwoptions.add(JLabel(mapping[0]))
            self.gwoptions.add(self.gateways[gw][mapping[1]])

    def buildpane(self):
        gw = JPanel(GridLayout(1, 2), doublebuffered)
        gw.add(JLabel("Gateway"))
        self.gwlist = JComboBox(self.gateways.keys())  # , actionPerformed=self.changegw)
        self.gwlist.setSelectedItem("Twisted")
        gw.add(self.gwlist)

        stdoptions = JPanel(GridLayout(2, 2), doublebuffered)
        stdoptions.border = TitledBorder("Standard Options")
        stdoptions.add(JLabel())
        stdoptions.add(self.autologin)
        stdoptions.add(JLabel("Account Name"))
        stdoptions.add(self.acctname)

        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(JButton("OK", actionPerformed=self.addaccount))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        mainpane = self.mainframe.getContentPane()
        mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
        mainpane.add(gw)
        mainpane.add(self.gwoptions)
        mainpane.add(stdoptions)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.setLocation(100, 100)
        self.mainframe.pack()
        self.mainframe.show()

    # actionlisteners
    def changegw(self, ae):
        self.buildgwoptions(self.gwlist.getSelectedItem())
        self.mainframe.pack()
        self.mainframe.show()

    def addaccount(self, ae):
        gwselection = self.gwlist.getSelectedItem()
        gw = self.gateways[gwselection]
        name = gw["ident"].text
        passwd = gw["passwd"].text
        host = gw["host"].text
        port = int(gw["port"].text)
        autologin = self.autologin.isSelected()
        acctname = self.acctname.text

        if gwselection == "Twisted":
            sname = gw["service"].text
            perspective = gw["persp"].text
            self.am.addAccount(PBAccount(acctname, autologin, name, passwd, host, port, [[stype, sname, perspective]]))
        elif gwselection == "AIM":
            self.am.addAccount(TOCAccount(acctname, autologin, name, passwd, host, port))
        elif gwselection == "IRC":
            channels = gw["channels"].text
            self.am.addAccount(IRCAccount(acctname, autologin, name, passwd, host, port, channels))

        self.amgui.update()
        print "Added new account"
        self.mainframe.dispose()

    def cancel(self, ae):
        print "Cancelling new account creation"
        self.mainframe.dispose()
Exemplo n.º 19
0
class TicTacToeGame(WindowAdapter):

    # Tic Tac Toe game with Mario and Dizzy animated icons/music.
    # Computer plays with Mario and player plays with Dizzy.

    # game title
    game_title = "Tic Tac Toe: You vs Mario"
    # welcome status message.
    welcome_status = "Welcome! Please make your first move."
    # in-game status message.
    in_game_status = "Mario chases You! Hurry up!"
    # board 3x3 with the default color - white
    board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
    # total number of cells
    size = len(board) * len(board)
    # size of cell
    tile_size = 128
    # status bar height
    status_bar_height = 50
    # status bar top margin
    status_bar_margin_top = -15
    # status bar left margin
    status_bar_margin_left = 10
    # number of cells in a row/column
    cells = 3
    # winner
    winner = None
    # Mario image
    mario = '/MARIO_128x128.gif'
    # Dizzy image
    dizzy = None

    # Blank
    blank = '/BLANK.gif'
    # supported musice sounds
    sounds = ['/DIZZY.wav', '/MARIO.wav']
    # currently played sound
    sound = None
    # last chosen sound
    last_sound = 0
    # won sound
    won_sound = '/WON.wav'
    # lose sound
    lose_sound = '/LOSE.wav'
    # tie sound
    tie_sound = '/TIE.wav'
    # action sound
    action_sound = '/ACTION.wav'

    def __init__(self, resources_directory):

        # Game constructor.
        #
        # Parameters:
        #   resources_directory Directory to look for images and audio files.

        is_windows = platform.platform().lower().find('win') > 0
        self.main_window_padding_right = 20 if is_windows else 0
        self.main_window_padding_bottom = 40 if is_windows else 0

        self.resources_directory = resources_directory

        self.button1 = JButton("", actionPerformed=self.clicked1)
        self.button2 = JButton("", actionPerformed=self.clicked2)
        self.button3 = JButton("", actionPerformed=self.clicked3)
        self.button4 = JButton("", actionPerformed=self.clicked4)
        self.button5 = JButton("", actionPerformed=self.clicked5)
        self.button6 = JButton("", actionPerformed=self.clicked6)
        self.button7 = JButton("", actionPerformed=self.clicked7)
        self.button8 = JButton("", actionPerformed=self.clicked8)
        self.button9 = JButton("", actionPerformed=self.clicked9)
        image_size = self.tile_size
        self.button1.setBounds(0 * image_size, 0 * image_size, image_size,
                               image_size)
        self.button2.setBounds(1 * image_size, 0 * image_size, image_size,
                               image_size)
        self.button3.setBounds(2 * image_size, 0 * image_size, image_size,
                               image_size)
        self.button4.setBounds(0 * image_size, 1 * image_size, image_size,
                               image_size)
        self.button5.setBounds(1 * image_size, 1 * image_size, image_size,
                               image_size)
        self.button6.setBounds(2 * image_size, 1 * image_size, image_size,
                               image_size)
        self.button7.setBounds(0 * image_size, 2 * image_size, image_size,
                               image_size)
        self.button8.setBounds(1 * image_size, 2 * image_size, image_size,
                               image_size)
        self.button9.setBounds(2 * image_size, 2 * image_size, image_size,
                               image_size)
        self.buttons = [
            self.button1, self.button2, self.button3, self.button4,
            self.button5, self.button6, self.button7, self.button8,
            self.button9
        ]
        self.buttons_mapped = [[self.button1, self.button2, self.button3],
                               [self.button4, self.button5, self.button6],
                               [self.button7, self.button8, self.button9]]

        width = self.tile_size * self.cells
        height = width
        self.frame = JFrame(self.game_title,
                            size=(width, height + self.status_bar_height))
        self.frame.setLocation(200, 100)
        self.frame.setLayout(None)

        for button in self.buttons:
            self.frame.add(button)

        self.status_label = JLabel("")
        self.status_label.setBounds(self.status_bar_margin_left,
                                    height + self.status_bar_margin_top, width,
                                    self.status_bar_height)
        self.frame.add(self.status_label)

        self.frame.setVisible(True)
        self.frame.addWindowListener(self)
        random.shuffle(self.sounds)

        self.restart()

    # Restarts the game.
    def restart(self):

        self.dizzy = None
        self.dizzy = self.choosePlayer()
        self.winner = None
        self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
        for button in self.buttons:
            button.setIcon(ImageIcon(self.resources_directory + self.blank))
        self.stop_playing_background()
        self.sound = self.play_sound_safe(self.sounds[self.last_sound])
        self.last_sound = self.last_sound + 1
        if self.last_sound >= len(self.sounds):
            self.last_sound = 0
        self.status_label.setText(self.welcome_status)

    # Stops playing any background music, if any playing now.
    def stop_playing_background(self):

        if self.sound != None:
            self.sound.stopPlaying()
            self.sound = None

    def set_dizzy(self, button):

        # Draws Dizzy in a given button, sets game status to "Playing" and
        # plays action sound.
        #
        # Parameters:
        #   button to set Dizzy icon to.

        button.setIcon(ImageIcon(self.resources_directory + self.dizzy))
        self.status_label.setText(self.in_game_status)
        self.play_sound_safe(self.action_sound)

    def set_mario(self, button):

        # Draws Mario in a given button.
        #
        # Parameters:
        #   button to set Mario icon to.

        button.setIcon(ImageIcon(self.resources_directory + self.mario))

    def clicked1(self, event):

        # Event listener method for the button of the game at 0x0.
        #
        # Parameters:
        #  event Click event.

        if self.board[0][0] != ' ':
            return
        self.board[0][0] = 'X'
        self.set_dizzy(self.button1)
        self.computer_move()

    def clicked2(self, event):

        # Event listener method for the button of the game at 0x1.
        #
        # Parameters:
        #  event Click event.

        if self.board[0][1] != ' ':
            return
        self.board[0][1] = 'X'
        self.set_dizzy(self.button2)
        self.computer_move()

    def clicked3(self, event):

        # Event listener method for the button of the game at 0x2.
        #
        # Parameters:
        #  event Click event.

        if self.board[0][2] != ' ':
            return
        self.board[0][2] = 'X'
        self.set_dizzy(self.button3)
        self.computer_move()

    def clicked4(self, event):

        # Event listener method for the button of the game at 1x0.
        #
        # Parameters:
        #  event Click event.

        if self.board[1][0] != ' ':
            return
        self.board[1][0] = 'X'
        self.set_dizzy(self.button4)
        self.computer_move()

    def clicked5(self, event):

        # Event listener method for the button of the game at 1x1.
        #
        # Parameters:
        #  event Click event.

        if self.board[1][1] != ' ':
            return
        self.board[1][1] = 'X'
        self.set_dizzy(self.button5)
        self.computer_move()

    def clicked6(self, event):

        # Event listener method for the button of the game at 1x2.
        #
        # Parameters:
        #  event Click event.

        if self.board[1][2] != ' ':
            return
        self.board[1][2] = 'X'
        self.set_dizzy(self.button6)
        self.computer_move()

    def clicked7(self, event):

        # Event listener method for the button of the game at 2x0.
        #
        # Parameters:
        #  event Click event.

        if self.board[2][0] != ' ':
            return
        self.board[2][0] = 'X'
        self.set_dizzy(self.button7)
        self.computer_move()

    def clicked8(self, event):

        # Event listener method for the button of the game at 2x1.

        # Parameters:
        #  event Click event.

        if self.board[2][1] != ' ':
            return
        self.board[2][1] = 'X'
        self.set_dizzy(self.button8)
        self.computer_move()

    def clicked9(self, event):

        # Event listener method for the button of the game at 2x2.
        #
        # Parameters:
        #  event Click event.

        if self.board[2][2] != ' ':
            return
        self.board[2][2] = 'X'
        self.set_dizzy(self.button9)
        self.computer_move()

    # Makes the next move on the board on behalf of the computer.
    def computer_move(self):

        # first move optimization - always start in the middle if possible
        if self.board[1][1] == ' ':
            self.board[1][1] = '0'
            self.set_mario(self.buttons_mapped[1][1])
            self.test_state()
            return
        while self.has_empty_cell():
            y = random.randint(0, self.cells - 1)
            x = random.randint(0, self.cells - 1)
            if self.board[y][x] == ' ':
                self.board[y][x] = '0'
                self.set_mario(self.buttons_mapped[y][x])
                break
        self.test_state()

    def test_state(self):

        # Tests the board for a winning state.
        # If there is a winner then stops currently playing
        # background sound, creates winning label, plays result
        # sound and notifies/asks the user about continuation.

        if self.is_any_line_filled('X'):
            self.winner = self.dizzy  # dizzy
        elif self.is_any_line_filled('0'):
            self.winner = self.mario  # mario
        elif not self.has_empty_cell():
            self.winner = self.blank  # tie
        if self.winner:
            label = 'Tie.'
            self.stop_playing_background()
            if self.winner == self.mario:
                label = 'You lose!'
                self.play_sound_safe(self.lose_sound)
            elif self.winner == self.dizzy:
                label = 'You won!'
                self.play_sound_safe(self.won_sound)
            else:
                self.play_sound_safe(self.tie_sound)
            self.notify_and_ask_about_continuation(label)

    def notify_and_ask_about_continuation(self, label):

        # Shows modal window with the result of the game and asks the use whether they want to
        # continue the game.
        # If user answers "Y" or "y" restarts the game.
        # If user answers "N" or "n" closes the game window and frees the resources.

        # Parameters:
        #   label Game result label.

        answer = None
        self.status_label.setText(label)
        while True:
            answer = str(
                requestString(label + "\r\n" +
                              "Do you want to play again? (Y/N)"))
            if answer.lower() == "y":
                self.restart()
                break
            elif answer.lower() == "n":
                self.windowClosing(None)
                break

    def is_any_line_filled(self, character):

        # Checks the winning condition for the given character 'X' or '0'.
        #
        # Returns:
        #  Whether the given character 'X' or '0' has a winning line filled.

        is_row = self.is_row_filled(character)
        is_col = self.is_col_filled(character)
        is_d1 = self.is_diag_filled1(character)
        is_d2 = self.is_diag_filled2(character)

        return is_row or is_col or is_d1 or is_d2

    def has_empty_cell(self):

        #Checks if the game board contains an empty cell for the next move.
        #
        #Returns:
        #  Whether there is an empty cell on the board.

        for row in range(len(self.board)):
            for col in range(len(self.board)):
                if self.board[row][col] == ' ':
                    return True
        return False

    def is_row_filled(self, color):

        # Check row win condition.
        #
        # Parameters:
        #   color (string) - color to check if the whole row of the same color
        # Returns:
        #   True (boolean) - if the whole row of the same color
        #   False (boolean) - if the row is not of the same color

        for row in range(len(self.board)):
            count = 0
            for col in range(len(self.board)):
                if self.board[row][col] == color:
                    count = count + 1
            if count == self.cells:
                return True
        return False

    def is_col_filled(self, color):

        #Check column win condition.
        #
        # Parameters:
        #   color (string) - color to check if the whole column of the same color
        # Returns:
        #   True (boolean) - if the whole column of the same color
        #   False (boolean) - if the column is not of the same color

        for col in range(len(self.board)):
            count = 0
            for row in range(len(self.board)):
                if self.board[row][col] == color:
                    count = count + 1
            if count == self.cells:
                return True
        return False

    def is_diag_filled1(self, color):

        # Checks first diagonal win condition.
        #
        # Parameters:
        #   color (string) - color to check if the whole diagonal of the same color
        # Returns:
        #    True (boolean) - if the whole diagonal of the same color
        #    False (boolean) - if the diagonal is not of the same color

        count = 0
        for idx in range(len(self.board)):
            if self.board[idx][idx] == color:
                count = count + 1
        return count == self.cells

    def is_diag_filled2(self, color):

        # Checks second diagonal win condition.
        #
        # Parameters:
        #   color (string) - color to check if the whole diagonal of the same color
        # Returns:
        #    True (boolean) - if the whole diagonal of the same color
        #   False (boolean) - if the diagonal is not of the same color

        count = 0
        for idx in range(len(self.board)):
            if self.board[idx][self.cells - 1 - idx] == color:
                count = count + 1
        return count == self.cells

    def play_sound_safe(self, sound):

        # Method tries to play given sound catching possible exceptions.
        # For example, if the sound wasn't found in resource directory
        #
        # Parameters:
        #    sound string with a file of a sound with leading slash '/'.
        # Returns:
        #    Created Sound object fromo makeSound.

        snd = None
        try:
            snd = makeSound(self.resources_directory + sound)
            play(snd)
        except:
            showError("Error while playing sound " + str(sound) + ".")
        return snd

    def windowClosing(self, event):

        # Method is invoked when a user closes game window or finishes playing.
        # It is the implementation of WindowAdapter interface.
        #
        # Parameters: final event from Swing/AWT

        self.stop_playing_background()
        self.buttons = []
        self.buttons_mapped = []
        self.button1 = None
        self.button2 = None
        self.button3 = None
        self.button4 = None
        self.button5 = None
        self.button6 = None
        self.button7 = None
        self.button8 = None
        self.button9 = None
        self.status_label = None
        self.frame.getContentPane().removeAll()
        self.frame.dispose()
        self.frame = None

    def choosePlayer(self):

        while true:

            select = requestString(
                "You are against Mario. Choose Your Character: penguin chrome fox fish bird charizard sonic "
            )
            selection = select.lower()

            if selection == "penguin":
                return rpenguin
                break
            if selection == "chrome":
                return rchrome
                break
            if selection == "fox":
                return rfox
                break
            if selection == "fish":
                return rfish
                break
            if selection == "bird":
                return rbird
                break
            if selection == "charizard":
                return rcharizard
                break
            if selection == "sonic":
                return rsonic
                break
Exemplo n.º 20
0
class BurpExtender(IBurpExtender, ITab, IScannerCheck, IScannerInsertionPoint, IContextMenuFactory):

    # definitions
    EXTENSION_NAME="IssueCreator"
    tmpl = dict()
    tmpl['XSS'] = dict()
    tmpl['XSS']['name'] = 'Cross-Site Scripting (reflected)'
    tmpl['XSS']['idetail'] = 'It is possible to inject arbitrary JavaScript into the application\'s response'
    tmpl['XSS']['ibackground'] = '''Reflected cross-site scripting vulnerabilities arise when data is copied from a request and echoed into the application's immediate response in an unsafe way. An attacker can use the vulnerability to construct a request which, if issued by another application user, will cause JavaScript code supplied by the attacker to execute within the user's browser in the context of that user's session with the application.  The attacker-supplied code can perform a wide variety of actions, such as stealing the victim's session token or login credentials, performing arbitrary actions on the victim's behalf, and logging their keystrokes.  Users can be induced to issue the attacker's crafted request in various ways. For example, the attacker can send a victim a link containing a malicious URL in an email or instant message. They can submit the link to popular web sites that allow content authoring, for example in blog comments. And they can create an innocuous looking web site which causes anyone viewing it to make arbitrary cross-domain requests to the vulnerable application (using either the GET or the POST method).  The security impact of cross-site scripting vulnerabilities is dependent upon the nature of the vulnerable application, the kinds of data and functionality which it contains, and the other applications which belong to the same domain and organization. If the application is used only to display non-sensitive public content, with no authentication or access control functionality, then a cross-site scripting flaw may be considered low risk. However, if the same application resides on a domain which can access cookies for other more security-critical applications, then the vulnerability could be used to attack those other applications, and so may be considered high risk. Similarly, if the organization which owns the application is a likely target for phishing attacks, then the vulnerability could be leveraged to lend credibility to such attacks, by injecting Trojan functionality into the vulnerable application, and exploiting users' trust in the organization in order to capture credentials for other applications which it owns. In many kinds of application, such as those providing online banking functionality, cross-site scripting should always be considered high risk. '''
    tmpl['XSS']['rdetail'] = ''''Input should be validated as strictly as possible on arrival, given the kind of content which it is expected to contain. For example, personal names should consist of alphabetical and a small range of typographical characters, and be relatively short; a year of birth should consist of exactly four numerals; email addresses should match a well-defined regular expression. Input which fails the validation should be rejected, not sanitized.
    User input should be HTML-encoded at any point where it is copied into application responses. All HTML metacharacters, including < > " ' and =, should be replaced with the corresponding HTML entities (&lt; &gt; etc).
    In cases where the application's functionality allows users to author content using a restricted subset of HTML tags and attributes (for example, blog comments which allow limited formatting and linking), it is necessary to parse the supplied HTML to validate that it does not use any dangerous syntax; this is a non-trivial task.
    '''
    tmpl['XSS']['rbackground'] = 'do not trust user input!'

    tmpl['SQLi'] = dict()
    tmpl['SQLi']['name'] = 'SQL Injection'
    tmpl['SQLi']['idetail'] = 'Input parameter appears to be vulnerable to SQL injection attacks.'
    tmpl['SQLi']['ibackground'] = '''SQL injection vulnerabilities arise when user-controllable data is incorporated into database SQL queries in an unsafe manner. An attacker can supply crafted input to break out of the data context in which their input appears and interfere with the structure of the surrounding query.
    Various attacks can be delivered via SQL injection, including reading or modifying critical application data, interfering with application logic, escalating privileges within the database and executing operating system commands.
    '''
    tmpl['SQLi']['rdetail'] = '''The most effective way to prevent SQL injection attacks is to use parameterized queries (also known as prepared statements) for all database access. This method uses two steps to incorporate potentially tainted data into SQL queries: first, the application specifies the structure of the query, leaving placeholders for each item of user input; second, the application specifies the contents of each placeholder. Because the structure of the query has already defined in the first step, it is not possible for malformed data in the second step to interfere with the query structure. You should review the documentation for your database and application platform to determine the appropriate APIs which you can use to perform parameterized queries. It is strongly recommended that you parameterize every variable data item that is incorporated into database queries, even if it is not obviously tainted, to prevent oversights occurring and avoid vulnerabilities being introduced by changes elsewhere within the code base of the application.
    
    '''
    tmpl['SQLi']['rbackground'] = 'SQL Injection background'

    tmpl['Insecure-Cookie'] = dict()
    tmpl['Insecure-Cookie']['name'] = 'Cookie Was Set Without Secure Flag'
    tmpl['Insecure-Cookie']['idetail'] = 'Application has set a secure cookie without the secure attribute'
    tmpl['Insecure-Cookie']['ibackground'] = 'Client will send this cookie over the clear via http.  This could be eavesdropped on.'
    tmpl['Insecure-Cookie']['rdetail'] = 'The application should set all cookies that are session related or sensitive in nature with the secure attribute.'
    tmpl['Insecure-Cookie']['rbackground'] = '...'

    tmpl['Your-Item'] = dict()
    tmpl['Your-Item']['name'] = 'My issue name'
    tmpl['Your-Item']['idetail'] = 'My issue detail'
    tmpl['Your-Item']['ibackground'] = 'the issue background here'
    tmpl['Your-Item']['rdetail'] = '''the remediation detail.  i'll put this in triple quotes. because.
    '''
    tmpl['Your-Item']['rbackground'] = 'this is remediation background information for my issue'
    
    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
       
        # define stdout writer
        self._stdout = PrintWriter(callbacks.getStdout(), True) 
        self._stdout.println(self.EXTENSION_NAME + ' by @luxcupitor')
        self._stdout.println('================================')
        self._stdout.println('')
        self._stdout.println('TIP: right click on items in proxy or repeater tab')
        self._stdout.println('and select "Add as Issue to Scanner".')
        self._stdout.println('')
        # set our extension name
        callbacks.setExtensionName(self.EXTENSION_NAME)
        
        # setup a context menu for the proxy tab. needs createMenuItems
        callbacks.registerContextMenuFactory(self)

        return

    def createMenuItems(self, caller):
      '''caller is the burpsuite context that invoked the menu'''
      menu = []
      #Proxy tab is context 6/repeater request is 0/repeater response is 3
      idx = caller.getInvocationContext()
      if idx == 6 or idx == 0 or idx == 3:
        menu.append(JMenuItem("Add as Issue to Scanner", None, actionPerformed=lambda x, c=caller: self.launchGui(c)))
      return menu if menu else None

    def getMatches(self, response, match):
      '''This finds our pattern match in the request/response and returns an int array'''
      start = 0
      count = 0
      matches = [array('i')]
      while start < len(response):
        start=self._helpers.indexOf(response, match, True, start, len(response))
        if start == -1:
          break
        try:
          matches[count]
        except:
          matches.append(array('i'))
        matches[count].append(start)
        matches[count].append(start+len(match))
        start += len(match)
        count += 1

      return matches

    def logScanIssue(self, baseRequestResponse):
      '''This is redundant (mostly) of the doPassiveScan function'''
      reqPATTERN=self.reqPattern.text
      resPATTERN=self.resPattern.text
      ISSUE_NAME=self.issueNameField.text
      ISSUE_DETAIL=self.issueDetailField.text
      ISSUE_BACKGROUND=self.issueBackgroundField.text
      REMEDIATION_BACKGROUND=self.remediationBackgroundField.text
      REMEDIATION_DETAIL=self.remediationDetailField.text
      if self.radioBtnSevHigh.isSelected():
        SEVERITY="High"
      elif self.radioBtnSevMedium.isSelected():
        SEVERITY="Medium"
      else:
        SEVERITY="Low"
      CONFIDENCE="Certain"
      self._stdout = PrintWriter(self._callbacks.getStdout(), True)
      self._stdout.println('logScanIssue has been called')
      self._stdout.println('[-] ISSUE_NAME: ' + ISSUE_NAME)
      self._stdout.println('[-] ISSUE_DETAIL: ' + ISSUE_DETAIL)
      self._stdout.println('[-] ISSUE_BACKGROUND: ' + ISSUE_BACKGROUND)
      self._stdout.println('[-] REMEDIATION_DETAIL: ' + REMEDIATION_DETAIL)
      self._stdout.println('[-] REMEDIATION_BACKGROUND: ' + REMEDIATION_BACKGROUND)
      self._stdout.println('[-] SEVERITY: ' + SEVERITY)
      self._stdout.println('[-] CONFIDENCE: ' + CONFIDENCE)
      match = False
      if reqPATTERN == "":
        reqmatch = None
      else:
        reqmatch = self.getMatches(baseRequestResponse.getRequest(), reqPATTERN)
        match = True
      if resPATTERN == "":
        resmatch = None
      else:
        resmatch = self.getMatches(baseRequestResponse.getResponse(), resPATTERN)
        match = True
      if match:
        httpmsgs = [self._callbacks.applyMarkers(baseRequestResponse,reqmatch,resmatch)]
        issue=ScanIssue(baseRequestResponse.getHttpService(), self._helpers.analyzeRequest(baseRequestResponse).getUrl(), httpmsgs, ISSUE_NAME, ISSUE_DETAIL, SEVERITY, CONFIDENCE, ISSUE_BACKGROUND, REMEDIATION_DETAIL, REMEDIATION_BACKGROUND)
        self._callbacks.addScanIssue(issue)
        self.closeUI(None)

      return

    def launchGui(self, caller):
      self._stdout = PrintWriter(self._callbacks.getStdout(), True)
      self._stdout.println('Launching gui')
      callMessage = caller.getSelectedMessages()
      self.msg1 = callMessage[0]

      #setup frame
      self.frame = JFrame('Create Issue', windowClosing=self.closeUI)
      Border = BorderFactory.createLineBorder(Color.BLACK)

      #create split panel to add issue panel and template panel
      self.splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
      self.frame.add(self.splitPane)

      #panel setup and add to splitPane
      self.issuePanel = JPanel(GridLayout(0,2))
      self.splitPane.setLeftComponent(self.issuePanel)

      #setup issue name text fields to add to panel
      self.issueNameField = JTextField('',15)
      self.issueNameLabel = JLabel("IssueName:", SwingConstants.CENTER)
      self.issuePanel.add(self.issueNameLabel)
      self.issuePanel.add(self.issueNameField)

      #add issue detail text area
      self.issueDetailField = JTextArea()
      self.issueDetailField.editable = True
      self.issueDetailField.wrapStyleWord = True
      self.issueDetailField.lineWrap = True
      self.issueDetailField.alignmentX = Component.LEFT_ALIGNMENT
      self.issueDetailField.size = (200, 20)
      self.issueDetailField.setBorder(Border)
      self.idfSp = JScrollPane()
      self.idfSp.getViewport().setView((self.issueDetailField))
      self.issuePanel.add(JLabel("Issue Detail:", SwingConstants.CENTER))
      self.issuePanel.add(self.idfSp)

      self.issueBackgroundField= JTextArea()
      self.issueBackgroundField.editable = True
      self.issueBackgroundField.wrapStyleWord = True
      self.issueBackgroundField.lineWrap = True
      self.issueBackgroundField.alignmentX = Component.LEFT_ALIGNMENT
      self.issueBackgroundField.size = (200, 20)
      self.issueBackgroundField.setBorder(Border)
      self.ibfSp = JScrollPane()
      self.ibfSp.getViewport().setView((self.issueBackgroundField))
      self.issuePanel.add(JLabel("Issue Background:", SwingConstants.CENTER))
      self.issuePanel.add(self.ibfSp)

      #add remediation detail text area
      self.remediationDetailField = JTextArea()
      self.remediationDetailField.editable = True
      self.remediationDetailField.wrapStyleWord = True
      self.remediationDetailField.lineWrap = True
      self.remediationDetailField.alignmentX = Component.LEFT_ALIGNMENT
      self.remediationDetailField.size = (200, 20)
      self.remediationDetailField.setBorder(Border)
      self.rdfSp = JScrollPane()
      self.rdfSp.getViewport().setView((self.remediationDetailField))
      self.issuePanel.add(JLabel("Remediation Detail:", SwingConstants.CENTER))
      self.issuePanel.add(self.rdfSp)

      self.remediationBackgroundField= JTextArea()
      self.remediationBackgroundField.editable = True
      self.remediationBackgroundField.wrapStyleWord = True
      self.remediationBackgroundField.lineWrap = True
      self.remediationBackgroundField.alignmentX = Component.LEFT_ALIGNMENT
      self.remediationBackgroundField.size = (200, 20)
      self.remediationBackgroundField.setBorder(Border)
      self.rbfSp = JScrollPane()
      self.rbfSp.getViewport().setView((self.remediationBackgroundField))
      self.issuePanel.add(JLabel("Remediation Background:", SwingConstants.CENTER))
      self.issuePanel.add(self.rbfSp)

      #add radio buttons for severity
      self.radioBtnSevHigh = JRadioButton('High', actionPerformed=None)
      self.radioBtnSevMedium = JRadioButton('Medium', actionPerformed=None)
      self.radioBtnSevLow = JRadioButton('Low', actionPerformed=None)
      severityButtonGroup = ButtonGroup()
      severityButtonGroup.add(self.radioBtnSevHigh)
      severityButtonGroup.add(self.radioBtnSevMedium)
      severityButtonGroup.add(self.radioBtnSevLow)
      self.radioBtnSevHigh.setSelected(True)
      self.issuePanel.add(JLabel("Severity:", SwingConstants.CENTER))
      self.issuePanel.add(self.radioBtnSevHigh)
      self.issuePanel.add(self.radioBtnSevMedium)
      self.issuePanel.add(self.radioBtnSevLow)
    
      self.reqPattern = JTextField('',15)
      self.issuePanel.add(JLabel("Mark Pattern in Request:", SwingConstants.CENTER))
      self.issuePanel.add(self.reqPattern)
      self.resPattern = JTextField('',15)
      self.issuePanel.add(JLabel("Mark Pattern in Response:", SwingConstants.CENTER))
      self.issuePanel.add(self.resPattern)

      #add a button
      self.issueButton = JButton('Add!', actionPerformed=lambda x, m=self.msg1: self.logScanIssue(m))
      self.issuePanel.add(self.issueButton)

      #template panel setup
      self.templatePanel = JPanel(GridLayout(1,2))
      self.splitPane.setRightComponent(self.templatePanel)
    
      #add a list of templates
      self.templatePanel.add(JLabel("Select from Templates", SwingConstants.CENTER))
      self.templateData = tuple(self.tmpl.keys())
      self.templateList = JList(self.templateData)
      self.templateScrollPane = JScrollPane()

      #self.templateScrollPane.setPreferredSize(Dimension(100,125))
      self.templateScrollPane.getViewport().setView((self.templateList))
      self.templatePanel.add(self.templateScrollPane)
      self.templateButton = JButton('Apply', actionPerformed=self.applyTemplate)
      self.templatePanel.add(self.templateButton)
     
      #pack up the frame and display it
      self.frame.pack()
      self.show()
     
    def applyTemplate(self, event):
      selected = self.templateList.selectedIndex
      if selected >= 0:
        self.issueNameField.text = self.tmpl[self.templateData[selected]]['name']
        self.issueDetailField.text = self.tmpl[self.templateData[selected]]['idetail']
        self.issueBackgroundField.text = self.tmpl[self.templateData[selected]]['ibackground']
        self.remediationDetailField.text = self.tmpl[self.templateData[selected]]['rdetail']
        self.remediationBackgroundField.text = self.tmpl[self.templateData[selected]]['rbackground']

    def show(self):
      self.frame.visible = True


    def closeUI(self, event):
        self.frame.setVisible(False)
        self.frame.dispose()
Exemplo n.º 21
0
class MandersPlugin(ImageListener, WindowAdapter):

	def __init__(self):
		self.imp = None
		self.preview = None
		self.createMainWindow()
		self.cells = None
		self.files = []
		self.results = ResultsTable()
		ImagePlus.addImageListener(self)
		self.selectInputDir()
		self.selectOutputDir()
		self.pairs = []
		self.methods = []
		self.processNextFile()

	def selectInputDir(self):
		inputDialog = DirectoryChooser("Please select a directory contaning your images")
		inputDir = inputDialog.getDirectory()
		for imageFile in os.listdir(inputDir):
			self.files.append(inputDir + imageFile)

	def selectOutputDir(self):
		outputDialog = DirectoryChooser("Please select a directory to save your results")
		self.outputDir = outputDialog.getDirectory()
		
	def closeImage(self):
		if self.imp is not None:
			self.imp.close()
			self.imp = None
		if self.preview is not None:
			self.preview.close()
			self.preview = None

	def openImage(self, imageFile):
		try:
			images = BF.openImagePlus(imageFile)
			self.imp = images[0]
		except UnknownFormatException:
			return None
		if self.imp.getNChannels() < 2:
			IJ.error("Bad image format", "Image must contain at lease 2 channels!")
			return None
		if not self.pairs or \
			not self.methods:
			self.getOptionsDialog(self.imp)
		title = self.imp.title
		self.imp.title = title[:title.rfind('.')]
		return self.imp

	def getOptionsDialog(self, imp):
		thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData",  "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"]
		gd = GenericDialog("Please select channels to collocalize")
		for i in range(1, imp.getNChannels() + 1):
			gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None")
		gd.showDialog()
		if gd.wasCanceled():
			self.exit()
		channels = []
		for i in range(1, imp.getNChannels() + 1):
			method = gd.getNextChoice()
			self.methods.append(method)
			if method != "None":
				channels.append(i)
		for x in channels:
			for y in channels:
				if x < y:
					self.pairs.append((x, y))

	def processNextFile(self):
		if self.files:
			imageFile = self.files.pop(0)
			return self.processFile(imageFile)
		else:
			return False
			
	def processFile(self, imageFile):
		imp = self.openImage(imageFile)
		if imp is not None:
			cell = Cell(imp.NSlices, 1)
			self.cells = DelegateListModel([])
			self.cells.append(cell)
			self.showMainWindow(self.cells)
			if self.checkbox3D.isSelected():
				self.displayImage(imp)
			else:
				self.displayImage(imp, False)
				self.preview = self.previewImage(imp)
				self.displayImage(self.preview)
			return True
		else:
			return self.processNextFile()
	
	def displayImage(self, imp, show = True):
		imp.setDisplayMode(IJ.COMPOSITE)
		enhancer = ContrastEnhancer()
		enhancer.setUseStackHistogram(True)
		splitter = ChannelSplitter()
		for c in range(1, imp.getNChannels() + 1):
			imp.c = c
			enhancer.stretchHistogram(imp, 0.35)
		if show:
			imp.show()

	def previewImage(self, imp):
		roi = imp.getRoi()
		splitter = ChannelSplitter()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c))
			projector = ZProjector(channel)
			projector.setMethod(ZProjector.MAX_METHOD)
			projector.doProjection()
			channels.append(projector.getProjection())
		image = RGBStackMerge.mergeChannels(channels, False)
		image.title = imp.title + " MAX Intensity"
		image.luts = imp.luts
		imp.setRoi(roi)
		return image

	def getCroppedChannels(self, imp, cell):
		splitter = ChannelSplitter()
		imp.setRoi(None)
		if cell.mode3D:
			cropRoi = cell.getCropRoi()
		else:
			cropRoi = cell.roi
		if cropRoi is None:
			return None
		crop = cropRoi.getBounds()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			slices = ImageStack(crop.width, crop.height)
			channel = splitter.getChannel(imp, c)
			for z in range(1, channel.getSize() + 1):
				zslice = channel.getProcessor(z)
				zslice.setRoi(cropRoi)
				nslice = zslice.crop()
				if cell.mode3D:
					oroi = cell.slices[z - 1].roi	
				else:
					oroi = cell.roi
				if oroi is not None:
					roi = oroi.clone()
					bounds = roi.getBounds()
					roi.setLocation(bounds.x - crop.x, bounds.y - crop.y)
					nslice.setColor(Color.black)
					nslice.fillOutside(roi)
					slices.addSlice(nslice)
			channels.append(ImagePlus("Channel %i" % c, slices))
		return channels

	def getThreshold(self, imp, method):
		thresholder = Auto_Threshold()
		duplicator = Duplicator()
		tmp = duplicator.run(imp)
		return thresholder.exec(tmp, method, False, False, True, False, False, True)

	def getContainer(self, impA, impB):
		imgA = ImagePlusAdapter.wrap(impA)
		imgB = ImagePlusAdapter.wrap(impB)
		return DataContainer(imgA, imgB, 1, 1, "imageA", "imageB")

	def getManders(self, imp, cell):
	
		### Crop channels according to cell mask
		channels = self.getCroppedChannels(imp, cell)
		if channels is None:
			return None
			
		### Calculate channel thresholds
		thrs = []
		thrimps = []
		for c, method in enumerate(self.methods):
			if method != "None":
				thr, thrimp = self.getThreshold(channels[c], method)
			else:
				thr, thrimp = None, None
			thrs.append(thr)
			thrimps.append(thrimp)
		
		### Calculate manders colocalization
		manders = MandersColocalization()
		raws = []
		thrds = []
		for chA, chB in self.pairs:
			container = self.getContainer(channels[chA - 1], channels[chB - 1])
			img1 = container.getSourceImage1()
			img2 = container.getSourceImage2()
			mask = container.getMask()
			cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
			rtype = img1.randomAccess().get().createVariable()
			raw = manders.calculateMandersCorrelation(cursor, rtype)
			rthr1 = rtype.copy()
			rthr2 = rtype.copy()
			rthr1.set(thrs[chA - 1])
			rthr2.set(thrs[chB - 1])
			cursor.reset()
			thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
			raws.append(raw)
			thrds.append(thrd)
		
		return (channels, thrimps, thrs, raws, thrds)

	def saveMultichannelImage(self, title, channels, luts):
		tmp = RGBStackMerge.mergeChannels(channels, False)
		tmp.luts = luts
		saver = FileSaver(tmp)
		saver.saveAsTiffStack(self.outputDir + title + ".tif")
		tmp.close()

	def createMainWindow(self):
		self.frame = JFrame('Select cells and ROIs',
			defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
		)
		self.frame.setLayout(GridBagLayout())
		self.frame.addWindowListener(self)

		self.frame.add(JLabel("Cells"),
			GridBagConstraints(0, 0, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.cellList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectCell
		)
		self.frame.add(JScrollPane(self.cellList),
			GridBagConstraints(0, 1, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Add cell', actionPerformed = self.addCell),
			GridBagConstraints(1, 2, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))
    	
		self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell),
			GridBagConstraints(1, 4, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 5, 0, 5), 0, 0
		))
		
		self.frame.add(JLabel("Slices"),
			GridBagConstraints(0, 6, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.sliceList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectSlice
		)
		self.frame.add(JScrollPane(self.sliceList),
			GridBagConstraints(0, 7, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice),
			GridBagConstraints(1, 8, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.frame.add(JButton('Done', actionPerformed = self.doneSelecting),
			GridBagConstraints(1, 10, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D)
		self.frame.add(self.checkbox3D,
			GridBagConstraints(0, 13, 2, 1, 0, 1,
				GridBagConstraints.WEST, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

	def showMainWindow(self, cells = None):
		if cells is not None:
			self.cellList.model = cells
			if cells:
				self.cellList.selectedIndex = 0
		self.frame.pack()
		self.frame.visible = True

	def hideMainWindow(self):
		self.frame.visible = False

	def closeMainWindow(self):
		self.frame.dispose()

	def toggle3D(self, event):
		mode3D = self.checkbox3D.isSelected()
		if mode3D:
			self.sliceList.enabled = True
			if self.imp is not None:
				self.imp.show()
			if self.preview is not None:
				self.preview.hide()
		else:
			self.sliceList.enabled = False
			if self.preview is None:
				self.preview = self.previewImage(self.imp)
				self.displayImage(self.preview)
			else:
				self.preview.show()
			if self.imp is not None:
				self.imp.hide()
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0:
			cell = self.cells[selectedCell]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		
	def addCell(self, event):
		size = len(self.cells)
		if (size > 0):
			last = self.cells[size - 1]
			n = last.n + 1
		else:
			n = 1
		self.cells.append(Cell(self.imp.NSlices, n))
		self.cellList.selectedIndex = size

	def removeCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			self.cells.remove(self.cells[selected])
			if (selected >= 1):
				self.cellList.selectedIndex = selected - 1
			else:
				self.cellList.selectedIndex = 0

	def selectCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			cell = self.cells[selected]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		else:
			self.sliceList.model = DelegateListModel([])
		if self.preview is not None:
			self.preview.setRoi(cell.roi)

	def selectSlice(self, event):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0:
			cell = self.cells[selectedCell]
			image = self.imp
			mode3D = self.checkbox3D.isSelected()
			if image is not None and cell is not None and mode3D:
				roi = cell.slices[selectedSlice].roi
				if (image.z - 1 != selectedSlice):
					image.z = selectedSlice + 1				
				image.setRoi(roi, True)
			if self.preview is not None and not mode3D:
				self.preview.setRoi(cell.roi, True)

	def updateSlice(self, event):
		if self.checkbox3D.isSelected():
			self.updateSlice3D(self.imp)
		else:
			self.updateSlice2D(self.preview)

	def updateSlice3D(self, imp):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				index = selectedSlice + 1
				roi = ShapeRoi(impRoi, position = index)
				cell.mode3D = True
				cell.name = "Cell %i (3D)" % cell.n
				cell.slices[selectedSlice].roi = roi
				if (index + 1 <= len(cell.slices)):
					imp.z = index + 1			
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
			self.sliceList.repaint(self.sliceList.getCellBounds(selectedSlice, selectedSlice))

	def updateSlice2D(self, imp):
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				roi = ShapeRoi(impRoi, position = 1)
				cell.mode3D = False
				cell.name = "Cell %i (2D)" % cell.n
				cell.roi = roi	
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
	
	def imageOpened(self, imp):
		pass

	def imageClosed(self, imp):
		pass

	def imageUpdated(self, imp):
		if self.checkbox3D.isSelected():
			if imp is not None:
				selectedCell = self.cellList.selectedIndex
				selectedSlice = imp.z - 1
			if imp == self.imp and selectedSlice != self.sliceList.selectedIndex:
				self.sliceList.selectedIndex = selectedSlice

	def doneSelecting(self, event):
		oluts = self.imp.luts
		luts = []
		channels = []
		for c, method in enumerate(self.methods):
			if method != "None":
				luts.append(oluts[c])
				channels.append(c)
		for cell in self.cells:
			manders = self.getManders(self.imp, cell)
			if manders is not None:
				chimps, thrimps, thrs, raws, thrds = manders
				index = self.cells.index(cell) + 1
				title = "Cell_%i-" % index + self.imp.title
				self.saveMultichannelImage(title, chimps, oluts)
				title = "Cell_%i_thrd-" % index + self.imp.title
				self.saveMultichannelImage(title, thrimps, luts)
				self.results.incrementCounter()
				row = self.results.getCounter() - 1
				for i, thr in enumerate(thrs):
					if thr is not None:
						self.results.setValue("Threshold %i" % (i + 1), row, int(thr))
				for i, pair in enumerate(self.pairs):
					self.results.setValue("%i-%i M1 raw" % pair, row, float(raws[i].m1))
					self.results.setValue("%i-%i M2 raw" % pair, row, float(raws[i].m2))
					self.results.setValue("%i-%i M1 thrd" % pair, row, float(thrds[i].m1))
					self.results.setValue("%i-%i M2 thrd" % pair, row, float(thrds[i].m2))
		self.closeImage()
		if not self.processNextFile():
			print "All done - happy analysis!"
			self.results.show("Manders collocalization results")
			self.exit()

	def windowClosing(self, e):
		print "Closing plugin - BYE!!!"
		self.exit()

	def exit(self):
		ImagePlus.removeImageListener(self)
		self.closeImage()
		self.closeMainWindow()
class correctionTable(TextPanel):
    """A class that displays an imagePlus and a resultstable. Resultstable and imp are linked in such a 
     way that click on a table row shows the imps respective timeframe."""
    def __init__(self, cell, mF, title="Results"): # add mF?
        # Call constructor of superclass
        TextPanel.__init__(self)
        # pass menue for setting save active/inactive
        self.cell = cell
        self.mF = mF
        # Create a window to show the content in
        self.window = JFrame()
        self.window.add(self)
        self.window.setTitle(title)
        # Add event listeners for keyboard and mouse responsiveness
        
        self.addKeyListener(ListenToKey())
        self.addMouseListener(ListenToMouse())
        
        # TODO: unpacking info out of cell object should be done in cell object itself and accessible e. g. via getData()
        self.imp = self.openImp(self.cell.getMeasTifPath())
        csvFile = open(self.cell.getCsvPath())        
        lines = csvFile.readlines()
        heads = lines.pop(0)
        self.setColumnHeadings("Frame\tDistance\tAnaphase")
        self.XYZtable = []
        for line in lines:      # load file lines in textPanel.
            frame, timepoint, dist, ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = line.split(",")
            self.append(frame + "\t" + dist + "\t" )
            self.XYZtable.append((ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol))
        self.setSelection(0,0) # int startline, int endline
        self.changeFrame()
        self.mF.setSaveInactive()
        self.requestFocus()

        self.window.setSize(Dimension(220, 600))
        x = int(self.imp.getWindow().getLocation().getX()) + int(self.imp.getWindow().getWidth()) + 10
        self.window.setLocation(x, int(self.imp.getWindow().getLocation().getY()) )
        self.window.show()

    # Methods implementing KeyAdapter and MouseListener
    #... no multiple inheritance for Java classes?
    

    # - - - - Event driven methods - - - -
    # ------------------------------------

    def changeFrame(self):
        if self.getSelectionEnd() >= 0:
            frame, dist, AOCol = self.getLine(self.getSelectionEnd()).split("\t")
            self.imp.setSlice(int(frame)+1)
    
    def setAnaphase(self):
        frame, Distance, x = self.getLine(self.getSelectionEnd()).split("\t")
        #set anaphase onset
        self.cell.setAnOn(frame)
        for i in range(self.getLineCount()):   # very unelegantly solved, but it works.
            blFr, blDist, blAOCol = self.getLine(i).split("\t")
            self.setLine(i, blFr + "\t" + blDist + "\t")
            frame, distance, AOCol = self.getLine(self.getSelectionEnd()).split("\t") # get old line
            self.setLine(self.getSelectionEnd(), frame + "\t" + distance + "\tX")
        # setFocus back to tw,tp
        self.mF.setSaveActive()
        print "Anaphase set to", self.cell.getAnOn()

    def delVal(self):
        frame, distance, AOCol = self.getLine(self.getSelectionEnd()).split("\t")
        self.setLine(self.getSelectionEnd(), frame + "\tNA" + "\t" + AOCol)

    # - other methods
    def openImp(self, path):
        imp = ImagePlus(path)  # open associated tif file
        imp.show()
        imp.getWindow().setLocationAndSize(280, 120, imp.getWidth()*4, imp.getHeight()*4) # int x, int y, int width, int height
        return imp

    def getImp(self):
        return self.imp

    def getXYZtable(self):
        return self.XYZtable
        
    def closeWindows(self):
        self.imp.close()
        WindowManager.removeWindow(self.window)
        self.window.dispose()