示例#1
0
def makeColor(*args):
    if len(args) == 3 and type(args[0]) == int and type(args[1]) == int and type(args[2]) == int:
        return Color(args[0], args[1], args[2])
    return _makeColor(*args)
示例#2
0
    def registerExtenderCallbacks(self, this_callbacks):  ### IBurpExtender
        global callbacks, helpers
        global extension_enable
        global remove_csrf_headers, remove_csrf_params, change_method_to_post
        global change_ct_to_json, change_ct_to_plain, change_to_get

        callbacks = this_callbacks
        helpers = callbacks.getHelpers()
        callbacks.setExtensionName(NAME)

        self.settings = JPanel(GridBagLayout())
        c = GridBagConstraints()

        self.extension_enable_box = JCheckBox('Enable extension',
                                              extension_enable)
        self.extension_enable_box.setFont(Font("Serif", Font.BOLD, 20))
        self.extension_enable_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 0
        c.gridwidth = 1
        c.weightx = 1
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.WEST
        self.settings.add(self.extension_enable_box, c)

        self.remove_csrf_headers_box = JCheckBox('Remove CSRF headers',
                                                 remove_csrf_params)
        self.remove_csrf_headers_box.setFont(Font("Serif", Font.BOLD, 20))
        self.remove_csrf_headers_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.remove_csrf_headers_box, c)

        remove_csrf_headers_box_lbl = JLabel(
            'Check to remove headers with CSRF tokens from all requests.')
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(remove_csrf_headers_box_lbl, c)

        self.remove_csrf_params_box = JCheckBox('Remove CSRF parameters',
                                                remove_csrf_params)
        self.remove_csrf_params_box.setFont(Font("Serif", Font.BOLD, 20))
        self.remove_csrf_params_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 3
        self.settings.add(self.remove_csrf_params_box, c)

        remove_csrf_params_box_lbl = JLabel(
            'Check to remove URL/body parameters with CSRF tokens from all requests. URL-encoded, multipart, JSON parameters are supported.'
        )
        c.gridx = 0
        c.gridy = 4
        self.settings.add(remove_csrf_params_box_lbl, c)

        self.change_method_to_post_box = JCheckBox(
            'Change HTTP method to POST', change_method_to_post)
        self.change_method_to_post_box.setFont(Font("Serif", Font.BOLD, 20))
        self.change_method_to_post_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 5
        self.settings.add(self.change_method_to_post_box, c)

        change_method_to_post_lbl = JLabel(
            'Check to convert PUT/DELETE/PATCH method to POST in all requests.'
        )
        c.gridx = 0
        c.gridy = 6
        self.settings.add(change_method_to_post_lbl, c)

        self.change_ct_to_json_box = JCheckBox('Change media type to json',
                                               change_ct_to_json)
        self.change_ct_to_json_box.setFont(Font("Serif", Font.BOLD, 20))
        self.change_ct_to_json_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 7
        self.settings.add(self.change_ct_to_json_box, c)

        change_ct_to_json_lbl = JLabel(
            'Check to convert body to json and set Content-Type to application/json in url-encoded requests.'
        )
        c.gridx = 0
        c.gridy = 8
        self.settings.add(change_ct_to_json_lbl, c)

        self.change_ct_to_plain_box = JCheckBox(
            'Change Content-Type to text/plain', change_ct_to_plain)
        self.change_ct_to_plain_box.setFont(Font("Serif", Font.BOLD, 20))
        self.change_ct_to_plain_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 9
        self.settings.add(self.change_ct_to_plain_box, c)

        change_ct_to_plain_lbl = JLabel(
            'Check to set Content-Type to text/plain in request with non-simple media type. Simple media types - application/application/x-www-form-urlencoded, text/plain, multipart/form-data.'
        )
        c.gridx = 0
        c.gridy = 10
        self.settings.add(change_ct_to_plain_lbl, c)

        self.change_to_get_box = JCheckBox('Change to GET', change_to_get)
        self.change_to_get_box.setFont(Font("Serif", Font.BOLD, 20))
        self.change_to_get_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 11
        self.settings.add(self.change_to_get_box, c)

        change_to_get_lbl = JLabel(
            'Check to convert POST/PUT/DELETE/PATCH url-encoded requests to GET.'
        )
        c.gridx = 0
        c.gridy = 12
        self.settings.add(change_to_get_lbl, c)

        callbacks.customizeUiComponent(self.settings)
        callbacks.addSuiteTab(self)

        callbacks.registerProxyListener(self)

        print "Successfully loaded %s v%s" % (NAME, VERSION)
class MonitoredExpression (object):
	_currentSuite = None

	def __init__(self):
		self._name = 'value'
		self._expr = EmbeddedPython2Expr()
		self._suite = None
		self._code = None
		self._incr = IncrementalValueMonitor()
		self.__change_history__ = None


	def __getstate__(self):
		return { 'name' : self._name,  'expr' : self._expr }

	def __setstate__(self, state):
		self._name = state['name']
		self._expr = state['expr']
		self._suite = None
		self._code = None
		self._incr = IncrementalValueMonitor()
		self.__change_history__ = None


	def __get_trackable_contents__(self):
		return [ self._name, self._expr ]


	def __py_compile_visit__(self, codeGen):
		self._code = codeGen.compileForEvaluation( self._expr.model )
		self._suite = self._currentSuite
		if self._suite is not None:
			self._suite._registerMonitoredExpression( self )


	def __py_eval__(self, _globals, _locals, codeGen):
		value = eval( self._code, _globals, _locals )
		if self._suite is not None:
			self._suite._logValue( self, value )
		return value

	def __py_replacement__(self):
		return deepcopy( self._expr.model['expr'] )


	def __present__(self, fragment, inheritedState):
		self._incr.onAccess()

		def _setName(editableLabel, text):
			self._name = text
			self._incr.onChanged()


		namePres = EditableLabel( self._name, self._nameNotSetStyle( Label( '<not set>' ) ), _setName ).regexValidated( Pattern.compile( '[a-zA-Z_][a-zA-Z0-9_]*' ), 'Please enter a valid identifier' )

		exprPres = self._expr

		contents = Row( [ namePres, Label( ': ' ), exprPres ] )
		return ObjectBox( 'Monitored exp.', contents )

	_nameNotSetStyle = StyleSheet.style( Primitive.foreground( Color( 0.5, 0.0, 0.0 ) ), Primitive.fontItalic( True ) )
示例#4
0
from BritefuryJ.Pres.UI import Section, SectionHeading2
from BritefuryJ.StyleSheet import StyleSheet

from BritefuryJ.Graphics import FilledOutlinePainter

from Britefury.Config import Configuration
from Britefury.Config.UserConfig import loadUserConfig, saveUserConfig
from Britefury.Config.ConfigurationPage import ConfigurationPage




_pathsConfigFilename = 'paths'


_itemHoverHighlightStyle = StyleSheet.style( Primitive.hoverBackground( FilledOutlinePainter( Color( 0.8, 0.825, 0.9 ), Color( 0.125, 0.341, 0.574 ), BasicStroke( 1.0 ) ) ) )




class PathsConfigurationPage (ConfigurationPage):
	def __init__(self):
		super( PathsConfigurationPage, self ).__init__()
		self._pluginPaths = []
		self._libraryPaths = []
		self._incr = IncrementalValueMonitor()
	
	
	def __getstate__(self):
		state = super( PathsConfigurationPage, self ).__getstate__()
		state['pluginPaths'] = self._pluginPaths
示例#5
0
    def registerExtenderCallbacks(self, callbacks):
        print "Load:" + self._name + " " + self._version

        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        #Create Tab layout
        self.jVarsPane = JTextPane()
        self.jVarsPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jVarsPane.addFocusListener(self)

        self.jMenuPanel = JPanel()
        self.jLeftUpPanel = JPanel()

        self.jEnable = JCheckBox()
        self.jEnable.setFont(Font('Monospaced', Font.BOLD, 11))
        self.jEnable.setForeground(Color(0, 0, 204))
        self.jEnable.setText(self._name)
        self.jEnable.addActionListener(self)

        self.jDocs = JLabel()
        self.jDocs.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jDocs.setForeground(Color(51, 102, 255))
        self.jDocs.setText(Strings.docs_titel)
        self.jDocs.setToolTipText(Strings.docs_tooltip)
        self.jDocs.addMouseListener(self)

        self.jConsoleText = JTextArea()
        self.jConsoleText.setFont(Font('Monospaced', Font.PLAIN, 10))
        self.jConsoleText.setBackground(Color(244, 246, 247))
        self.jConsoleText.setEditable(0)
        self.jConsoleText.setWrapStyleWord(1)
        self.jConsoleText.setRows(10)
        self.jScrollConsolePane = JScrollPane()
        self.jScrollConsolePane.setViewportView(self.jConsoleText)
        #set initial text
        self.jConsoleText.setText(Strings.console_disable)

        self.jMenuPanelLayout = GroupLayout(self.jMenuPanel)
        self.jMenuPanel.setLayout(self.jMenuPanelLayout)
        self.jMenuPanelLayout.setHorizontalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addComponent(
                        self.jEnable).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED, 205,
                            32767).addComponent(self.jDocs)))

        self.jMenuPanelLayout.setVerticalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addGroup(
                        self.jMenuPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).addComponent(
                                self.jEnable).addComponent(self.jDocs)).addGap(
                                    0, 7, 32767)))

        self.jConsolePane = JPanel()
        self.jConsoleLayout = GroupLayout(self.jConsolePane)
        self.jConsolePane.setLayout(self.jConsoleLayout)
        self.jConsoleLayout.setHorizontalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jScrollConsolePane))
        self.jConsoleLayout.setVerticalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    GroupLayout.Alignment.TRAILING,
                    self.jConsoleLayout.createSequentialGroup().addComponent(
                        self.jScrollConsolePane, GroupLayout.DEFAULT_SIZE, 154,
                        32767).addContainerGap()))
        self.jLeftUpPanelLayout = GroupLayout(self.jLeftUpPanel)
        self.jLeftUpPanel.setLayout(self.jLeftUpPanelLayout)
        self.jLeftUpPanelLayout.setHorizontalGroup(
            self.jLeftUpPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    32767).addComponent(self.jMenuPanel,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE))
        self.jLeftUpPanelLayout.setVerticalGroup(
            self.jLeftUpPanelLayout.
            createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                GroupLayout.Alignment.TRAILING,
                self.jLeftUpPanelLayout.createSequentialGroup().addComponent(
                    self.jMenuPanel, GroupLayout.PREFERRED_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE).addPreferredGap(
                        LayoutStyle.ComponentPlacement.RELATED).addComponent(
                            self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.DEFAULT_SIZE, 32767)))

        self.jScrollpaneLeftDown = JScrollPane()
        self.jScrollpaneLeftDown.setViewportView(self.jVarsPane)

        self.jSplitPaneLeft = JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                         self.jLeftUpPanel,
                                         self.jScrollpaneLeftDown)
        self.jSplitPaneLeft.setDividerLocation(300)

        self.jScriptPane = JTextPane()
        self.jScriptPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jScriptPane.addMouseListener(self)

        self.JScrollPaneRight = JScrollPane()
        self.JScrollPaneRight.setViewportView(self.jScriptPane)

        self.jSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                     self.jSplitPaneLeft,
                                     self.JScrollPaneRight)
        self.jSplitPane.setDividerLocation(400)

        #Load saved saved settings
        ##Load vars
        vars = callbacks.loadExtensionSetting(self._varsStorage)
        if vars:
            vars = base64.b64decode(vars)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-vars.py") as fvars:
                    vars = fvars.read()
            # load the default text
            except:
                vars = Strings.vars

        ## initiate the persistant variables
        locals_ = {}
        try:
            exec(vars, {}, locals_)
        except Exception as e:
            print e
        self._vars = locals_

        ## update the vars screen
        self.jVarsPane.document.insertString(self.jVarsPane.document.length,
                                             vars, SimpleAttributeSet())

        ##Load script
        script = callbacks.loadExtensionSetting(self._scriptStorage)
        if script:
            script = base64.b64decode(script)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-script.py") as fscript:
                    script = fscript.read()
            # load the default text
            except:
                script = Strings.script

        ## compile the rules
        self._script = script
        self._code = ''

        try:
            self._code = compile(script, '<string>', 'exec')
        except Exception as e:
            print(
                '{}\nReload extension after you correct the error.'.format(e))

        ## update the rules screen
        self.jScriptPane.document.insertString(
            self.jScriptPane.document.length, script, SimpleAttributeSet())

        #Register Extension
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)

        self.jScriptPane.requestFocus()
示例#6
0
    def drawUI(self):
        self.tab = swing.JPanel()
        self.uiLabel = swing.JLabel('Site Map Extractor Options')
        self.uiLabel.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiLabel.setForeground(Color(235, 136, 0))

        self.uiScopeOnly = swing.JRadioButton('In-scope only', True)
        self.uiScopeAll = swing.JRadioButton('Full site map', False)
        self.uiScopeButtonGroup = swing.ButtonGroup()
        self.uiScopeButtonGroup.add(self.uiScopeOnly)
        self.uiScopeButtonGroup.add(self.uiScopeAll)

        self.uipaneA = swing.JSplitPane(swing.JSplitPane.HORIZONTAL_SPLIT)
        self.uipaneA.setMaximumSize(Dimension(900, 125))
        self.uipaneA.setDividerSize(2)
        self.uipaneB = swing.JSplitPane(swing.JSplitPane.HORIZONTAL_SPLIT)
        self.uipaneB.setDividerSize(2)
        self.uipaneA.setRightComponent(self.uipaneB)
        self.uipaneA.setBorder(BorderFactory.createLineBorder(Color.black))

        # UI for Export <a href Links
        self.uiLinksPanel = swing.JPanel()
        self.uiLinksPanel.setPreferredSize(Dimension(200, 75))
        self.uiLinksPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.uiLinksPanel.setLayout(BorderLayout())
        self.uiLinksLabel = swing.JLabel("Extract '<a href=' Links")
        self.uiLinksLabel.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiLinksAbs = swing.JCheckBox('Absolute     ', True)
        self.uiLinksRel = swing.JCheckBox('Relative     ', True)
        # create a subpanel so Run button will be centred
        self.uiLinksRun = swing.JButton('Run',
                                        actionPerformed=self.extractLinks)
        self.uiLinksSave = swing.JButton('Save Log to CSV File',
                                         actionPerformed=self.savetoCsvFile)
        self.uiLinksClear = swing.JButton('Clear Log',
                                          actionPerformed=self.clearLog)
        self.uiLinksButtonPanel = swing.JPanel()
        self.uiLinksButtonPanel.add(self.uiLinksRun)
        self.uiLinksButtonPanel.add(self.uiLinksSave)
        self.uiLinksButtonPanel.add(self.uiLinksClear)
        # add all elements to main Export Links panel
        self.uiLinksPanel.add(self.uiLinksLabel, BorderLayout.NORTH)
        self.uiLinksPanel.add(self.uiLinksAbs, BorderLayout.WEST)
        self.uiLinksPanel.add(self.uiLinksRel, BorderLayout.CENTER)
        self.uiLinksPanel.add(self.uiLinksButtonPanel, BorderLayout.SOUTH)
        self.uipaneA.setLeftComponent(
            self.uiLinksPanel)  # add Export Links panel to splitpane

        # UI for Export Response Codes
        self.uiCodesPanel = swing.JPanel()
        self.uiCodesPanel.setPreferredSize(Dimension(200, 75))
        self.uiCodesPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.uiCodesPanel.setLayout(BorderLayout())
        self.uiCodesLabel = swing.JLabel('Extract Response Codes')
        self.uiCodesLabel.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiRcodePanel = swing.JPanel()
        self.uiRcodePanel.setLayout(GridLayout(1, 1))
        self.uiRcode1xx = swing.JCheckBox('1XX  ', False)
        self.uiRcode2xx = swing.JCheckBox('2XX  ', True)
        self.uiRcode3xx = swing.JCheckBox('3XX  ', True)
        self.uiRcode4xx = swing.JCheckBox('4XX  ', True)
        self.uiRcode5xx = swing.JCheckBox('5XX  ', True)
        self.uiCodesRun = swing.JButton('Run',
                                        actionPerformed=self.exportCodes)
        self.uiCodesSave = swing.JButton('Save Log to CSV File',
                                         actionPerformed=self.savetoCsvFile)
        self.uiCodesClear = swing.JButton('Clear Log',
                                          actionPerformed=self.clearLog)
        self.uiCodesButtonPanel = swing.JPanel()
        self.uiCodesButtonPanel.add(self.uiCodesRun)
        self.uiCodesButtonPanel.add(self.uiCodesSave)
        self.uiCodesButtonPanel.add(self.uiCodesClear)
        self.uiRcodePanel.add(self.uiRcode1xx)
        self.uiRcodePanel.add(self.uiRcode2xx)
        self.uiRcodePanel.add(self.uiRcode3xx)
        self.uiRcodePanel.add(self.uiRcode4xx)
        self.uiRcodePanel.add(self.uiRcode5xx)
        self.uiCodesPanel.add(self.uiCodesLabel, BorderLayout.NORTH)
        self.uiCodesPanel.add(self.uiRcodePanel, BorderLayout.WEST)
        self.uiCodesPanel.add(self.uiCodesButtonPanel, BorderLayout.SOUTH)
        self.uipaneB.setLeftComponent(self.uiCodesPanel)

        # Option 3 UI for Export Sitemap
        self.uiExportPanel = swing.JPanel()
        self.uiExportPanel.setPreferredSize(Dimension(200, 75))
        self.uiExportPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.uiExportPanel.setLayout(BorderLayout())
        self.uiExportLabel = swing.JLabel('Export Site Map to File')
        self.uiExportLabel.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiMustHaveResponse = swing.JRadioButton(
            'Must have a response     ', True)
        self.uiAllRequests = swing.JRadioButton('All     ', False)
        self.uiResponseButtonGroup = swing.ButtonGroup()
        self.uiResponseButtonGroup.add(self.uiMustHaveResponse)
        self.uiResponseButtonGroup.add(self.uiAllRequests)
        self.uiExportRun = swing.JButton('Run',
                                         actionPerformed=self.exportSiteMap)
        self.uiExportClear = swing.JButton('Clear Log',
                                           actionPerformed=self.clearLog)
        self.uiExportButtonPanel = swing.JPanel()
        self.uiExportButtonPanel.add(self.uiExportRun)
        self.uiExportButtonPanel.add(self.uiExportClear)
        self.uiExportPanel.add(self.uiExportLabel, BorderLayout.NORTH)
        self.uiExportPanel.add(self.uiMustHaveResponse, BorderLayout.WEST)
        self.uiExportPanel.add(self.uiAllRequests, BorderLayout.CENTER)
        self.uiExportPanel.add(self.uiExportButtonPanel, BorderLayout.SOUTH)
        self.uipaneB.setRightComponent(self.uiExportPanel)

        # UI Common Elements
        self.uiLogLabel = swing.JLabel('Log:')
        self.uiLogLabel.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiLogPane = swing.JScrollPane()
        layout = swing.GroupLayout(self.tab)
        self.tab.setLayout(layout)

        # Thank you to Smeege (https://github.com/SmeegeSec/Burp-Importer/) for helping me figure out how this works.
        # He in turn gave credit to Antonio Sanchez (https://github.com/Dionach/HeadersAnalyzer/)
        layout.setHorizontalGroup(
            layout.createParallelGroup(
                swing.GroupLayout.Alignment.LEADING).addGroup(
                    layout.createSequentialGroup().addGap(10, 10, 10).addGroup(
                        layout.createParallelGroup(
                            swing.GroupLayout.Alignment.LEADING).addComponent(
                                self.uiLabel).addGroup(
                                    layout.createSequentialGroup().addGap(
                                        10, 10, 10).addComponent(
                                            self.uiScopeOnly).addGap(
                                                10, 10, 10).addComponent(
                                                    self.uiScopeAll)).
                        addGap(15, 15,
                               15).addComponent(self.uipaneA).addComponent(
                                   self.uiLogLabel).addComponent(
                                       self.uiLogPane)).addContainerGap(
                                           26, lang.Short.MAX_VALUE)))

        layout.setVerticalGroup(
            layout.createParallelGroup(swing.GroupLayout.Alignment.LEADING).
            addGroup(layout.createSequentialGroup().addGap(
                15, 15,
                15).addComponent(self.uiLabel).addGap(15, 15, 15).addGroup(
                    layout.createParallelGroup().addComponent(
                        self.uiScopeOnly).addComponent(
                            self.uiScopeAll)).addGap(
                                20, 20, 20).addComponent(self.uipaneA).addGap(
                                    20, 20,
                                    20).addComponent(self.uiLogLabel).addGap(
                                        5, 5,
                                        5).addComponent(self.uiLogPane).addGap(
                                            20, 20, 20)))
示例#7
0
    def start(self):

        self.target = space.Sphere(0.2, mass=1, color=Color(0xFF0000))
        self.add(self.target, 0, 0, 2)

        torso = space.Box(0.1,
                          0.1,
                          1.5,
                          mass=100000,
                          draw_as_cylinder=True,
                          color=Color(0x4444FF))
        self.add(torso, 0, 0, 1)

        upperarm = space.Box(0.1,
                             0.7,
                             0.1,
                             mass=0.5,
                             draw_as_cylinder=True,
                             color=Color(0x8888FF),
                             overdraw_radius=1.2,
                             overdraw_length=1.2)
        self.add(upperarm, 0.7, 0.5, 2)
        upperarm.add_sphere_at(0, 0.5, 0, 0.1, Color(0x4444FF), self)
        upperarm.add_sphere_at(0, -0.5, 0, 0.1, Color(0x4444FF), self)

        lowerarm = space.Box(0.1,
                             0.75,
                             0.1,
                             mass=0.1,
                             draw_as_cylinder=True,
                             color=Color(0x8888FF),
                             overdraw_radius=1.2,
                             overdraw_length=1.1)
        self.add(lowerarm, 0.7, 1.5, 2)

        shoulder = HingeConstraint(torso.physics, upperarm.physics,
                                   Vector3f(0.7, 0.1, 1), Vector3f(0, -0.5, 0),
                                   Vector3f(0, 0, 1), Vector3f(0, 0, 1))

        elbow = HingeConstraint(upperarm.physics, lowerarm.physics,
                                Vector3f(0, 0.5, 0), Vector3f(0, -0.5, 0),
                                Vector3f(0, 0, 1), Vector3f(0, 0, 1))

        shoulder.setLimit(-pi / 2, pi / 2 + .1)
        elbow.setLimit(-pi, 0)

        self.physics.addConstraint(elbow)
        self.physics.addConstraint(shoulder)

        #upperarm.physics.applyTorqueImpulse(Vector3f(0,0,300))
        #lowerarm.physics.applyTorqueImpulse(Vector3f(0,0,300))

        self.sch.add(space.Room.start, args=(self, ))
        self.update_neurons()
        self.upperarm = upperarm
        self.lowerarm = lowerarm
        self.shoulder = shoulder
        self.elbow = elbow
        self.hinge1 = self.shoulder.hingeAngle
        self.hinge2 = self.elbow.hingeAngle
        self.upperarm.physics.setSleepingThresholds(0, 0)
        self.lowerarm.physics.setSleepingThresholds(0, 0)
示例#8
0
def enumSwitchButtonEditorWithLabels(live, enumType, labelTexts):
	return enumSwitchButtonEditor(live, enumType, [Label(t)   for t in labelTexts])
	@LiveFunction
	def displayLive():
		return live.getValue().ordinal()

	def _onChoice(control, prevChoice, choice):
		live.setLiteralValue(enumType.values()[choice])

	options = [Label(t)   for t in ['Larger', 'Smaller', 'Fixed', 'None']]

	return SwitchButton(options, options, SwitchButton.Orientation.HORIZONTAL, displayLive, _onChoice)



_plusStyle = StyleSheet.style(Primitive.fontBold(True), Primitive.foreground(Color(0.0, 0.6, 0.0)), Primitive.fontSize(12))

def optionalTypedEditor(live, initialValue, editorFn):
	valueEditor = LiveValue(editorFn(live))

	@LiveFunction
	def editor():
		x = live.getValue()

		if x is None:
			def on_add(button, event):
				live.setLiteralValue(initialValue)
			return Button(_plusStyle(Label('+')), on_add).alignHPack()
		else:
			def on_delete(button, event):
				live.setLiteralValue(None)
示例#9
0
			row=[ str(p[i]) for p in profiles ]
			row=",".join(row)
			f.write(row+"\n")

# Generate a plot
if doPlot:
	from ij.gui import Plot
	from java.awt import Color
	p = Plot('Profiles','Channel #','Intensity')
	p.setSize(640,480)
	maxP = len(profiles)
	maxV = 0
	for iprofile,profile in enumerate(profiles):
		h = 0.66-(float(iprofile)/maxP)
		if h<0:
			h=h+1
		p.setColor(Color.getHSBColor( h,.8,1))
		p.addPoints(range(len(profile)),profile,p.LINE)
	
		maxV_=max(profile)
		if maxV < maxV_:
			maxV = maxV_
	p.setLimits(0,len(profile)-1,0,maxV*1.2)
	p.setLegend("\n".join(names),p.TOP_LEFT|p.LEGEND_TRANSPARENT)
	p.show()
	
	# Save the plot as PNG
	if doSavePlot:
		imp = p.getImagePlus()
		IJ.saveAs(imp,'PNG',file.absolutePath + "_compensationPlot.png")
示例#10
0
from java.awt import Color

print("red")

c = Color(1, 0, 0)

print(c.getRed())
print(c.getGreen())
print(c.getBlue())
print(c.getAlpha())

print("")

print(c.red)
print(c.green)
print(c.blue)
print(c.alpha)

print("\n\nyellow")

c2 = Color.YELLOW

print(c2.red)
print(c2.green)
print(c2.blue)
print(c2.alpha)
示例#11
0
    def initUI(self):
        self.tab = swing.JPanel()

        # UI for Decrypt Key
        self.decryptLabel = swing.JLabel("Decrypt Key:")
        self.decryptLabel.setFont(Font("Tahoma", Font.BOLD, 14))
        self.decryptLabel.setForeground(Color(255,102,52))
        self.urlLabel = swing.JLabel("URL:")
        self.urlTxtField = swing.JTextField("http://localhost/Telerik.Web.UI.DialogHandler.aspx", 40)
        self.charLabel = swing.JLabel("Character Set:")
        self.hexRadio = swing.JRadioButton("Hex", True)
        self.asciiRadio = swing.JRadioButton("ASCII", False)
        self.btnGroup = swing.ButtonGroup()
        self.btnGroup.add(self.hexRadio)
        self.btnGroup.add(self.asciiRadio)
        self.decryptBtn = swing.JButton("Decrypt Key", actionPerformed=self.mode_brutekey)
        self.cancelBtn = swing.JButton("Cancel", actionPerformed=self.cancel)

        # UI for Output
        self.outputLabel = swing.JLabel("Log:")
        self.outputLabel.setFont(Font("Tahoma", Font.BOLD, 14))
        self.outputLabel.setForeground(Color(255,102,52))
        self.logPane = swing.JScrollPane()
        self.outputTxtArea = swing.JTextArea()
        self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12))
        self.outputTxtArea.setLineWrap(True)
        self.logPane.setViewportView(self.outputTxtArea)
        self.clearBtn = swing.JButton("Clear Log", actionPerformed=self.clearLog)

        # Layout
        layout = swing.GroupLayout(self.tab)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)
        self.tab.setLayout(layout)

        layout.setHorizontalGroup(
            layout.createParallelGroup()
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup()
                    .addComponent(self.decryptLabel)
                    .addComponent(self.urlLabel)
                    .addComponent(self.urlTxtField, swing.GroupLayout.PREFERRED_SIZE, swing.GroupLayout.DEFAULT_SIZE, swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(self.charLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(self.hexRadio)
                        .addComponent(self.asciiRadio)
                    )
                    .addGroup(layout.createSequentialGroup()
                    	.addComponent(self.decryptBtn)
                    	.addComponent(self.cancelBtn)
                    )
                )
                .addGroup(layout.createParallelGroup()
                    .addComponent(self.outputLabel)
                    .addComponent(self.logPane)
                    .addComponent(self.clearBtn)
                )
            )
        )
        
        layout.setVerticalGroup(
            layout.createParallelGroup()
            .addGroup(layout.createParallelGroup()
                .addGroup(layout.createSequentialGroup()
                    .addComponent(self.decryptLabel)
                    .addComponent(self.urlLabel)
                    .addComponent(self.urlTxtField, swing.GroupLayout.PREFERRED_SIZE, swing.GroupLayout.DEFAULT_SIZE, swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(self.charLabel)
                    .addGroup(layout.createParallelGroup()
                        .addComponent(self.hexRadio)
                        .addComponent(self.asciiRadio)
                    )
                    .addGroup(layout.createParallelGroup()
	                    .addComponent(self.decryptBtn)
	                    .addComponent(self.cancelBtn)
                    )
                )
                .addGroup(layout.createSequentialGroup()
                    .addComponent(self.outputLabel)
                    .addComponent(self.logPane)
                    .addComponent(self.clearBtn)
                )
            )
        )
示例#12
0
impProc.setInterpolationMethod(ImageProcessor.NONE)
impProc = impProc.resize(canvasWidth,canvasHeight)
imp.setProcessor(impProc)
imp.show()

IJ.run(imp, "Rainbow RGB", "");
IJ.run(imp, "Canvas Size...", "width=800 height=1024 position=Top-Center zero");

testROI = Roi(0,canvasHeight,canvasWidth,6)
testROI.setFillColor(Color.WHITE)
imp.setRoi(testROI,True)

overlay = Overlay(testROI)
font = Font("SansSerif",Font.PLAIN,fontSize)

# Write the EmissionWavelengths according
# to the metadata read earlier.
for i in xrange(1,len(pixelInt2[0]),tickInterval):
    pixelSize = (canvasWidth/(len(pixelInt2[0])*1.0))
    calc      = (pixelSize)*(i)
    roi       = TextRoi(calc+(pixelSize*0.2),canvasHeight+10,str(emissionWL[i]),font)
    roi.setStrokeColor(Color(1.00, 1.00, 1.00));
    overlay.add(roi)

imp.setOverlay(overlay)
imp.show()
IJ.run(imp, "Calibration Bar...", "location=[Upper Right] fill=None label=White number=3 decimal=1 font=9 zoom=2 bold overlay");

# Saves the output file.
IJ.saveAs(imp,"png",hyperspaceImage)
示例#13
0
            if child is not None:
                e.append(child)
            return e
        else:
            return child

    def store_value_from_element(self, rich_text_attributes, element):
        rich_text_attributes.putOverride(self.tag_name, True)


_italic_style = StyleSheet.instance.withValues(Primitive.fontItalic(True))
_bold_style = StyleSheet.instance.withValues(Primitive.fontBold(True))
_code_style = StyleSheet.instance.withValues(
    Primitive.fontFace(Primitive.monospacedFontName),
    Primitive.background(
        FilledOutlinePainter(Color(0.9, 0.9, 0.9), Color(0.75, 0.75, 0.75))))
_cmd_style = StyleSheet.instance.withValues(
    Primitive.fontFace(Primitive.monospacedFontName),
    Primitive.background(
        FilledOutlinePainter(Color(0.9, 0.9, 0.9), Color(0.75, 0.75, 0.75))),
    Primitive.foreground(Color(0.0, 0.5, 0.0)))
_cmd_prompt_style = StyleSheet.instance.withValues(
    Primitive.foreground(Color(0.0, 0.6, 0.5)))
_app_style = StyleSheet.instance.withValues(
    Primitive.fontItalic(True), Primitive.foreground(Color(0.5, 0.0, 0.0)))
_sys_style = StyleSheet.instance.withValues(
    Primitive.fontFace(Primitive.monospacedFontName),
    Primitive.foreground(Color(0.25, 0.0, 0.5)))

italic_style_attr = BooleanStyleAttribute('i')
示例#14
0
from BritefuryJ.Graphics import SolidBorder, FillPainter

from BritefuryJ.StyleSheet import StyleSheet

from BritefuryJ.DefaultPerspective import DefaultPerspective
from BritefuryJ.Projection import TransientSubject
from Britefury.Kernel.Document import Document

from LarchCore.MainApp.MainAppViewer.View import perspective
from LarchCore.MainApp.MainAppViewer.AboutPage import AboutPage


_info_style = StyleSheet.style(Primitive.selectable(False), Primitive.editable(False))
_editable_style = StyleSheet.style(Primitive.selectable(True), Primitive.editable(True))

_section_heading_style = StyleSheet.style(Primitive.background(FillPainter(Color(0.925, 0.925, 0.925))))

_section_border = SolidBorder(1.0, 3.0, 4.0, 4.0, Color(0.4, 0.4, 0.4), None)


def unload_modules_starting_with(prefixes):
	to_remove = []
	for m in sys.modules:
		for prefix in prefixes:
			if m.startswith(prefix):
				to_remove.append(m)
	for m in to_remove:
		del sys.modules[m]


class EditorPage (object):
示例#15
0
# Color(Red) all Jump(s) in Listing Window.
# https://ghidra.re/ghidra_docs/api/ghidra/program/model/symbol/FlowType.html#isJump()
# @author : Harshil Patel
# @category : Tools

from java.awt import Color

jump_count = 0
JUMP_COLOR = Color(255, 143, 143)  # Red

#get all memory ranges
addr_ranges = currentProgram.getMemory().getAddressRanges()

for addr_range in addr_ranges:
    insts = currentProgram.getListing().getInstructions(
        addr_range.getMinAddress(), True)
    for inst in insts:
        flow_type = inst.getFlowType()
        addr = inst.getAddress()
        if flow_type.isJump():
            print("0x{} : {}".format(addr, inst))
            setBackgroundColor(addr, JUMP_COLOR)
            jump_count += 1

print('[*] Total Jump(s) : {}'.format(jump_count))
示例#16
0
    def __init__(self):
        self.jScrollPane1 = JScrollPane()
        self.jTable1 = JTable()
        self.jPanel1 = JPanel()
        self.labelName = JLabel()
        self.textName = JTextField()
        self.labelSeverity = JLabel()
        self.comboSeverity = None
        self.labelHost = JLabel()
        self.labelPath = JLabel()
        self.textHost = JTextField()
        self.textPath = JTextField()
        self.tabIssue = JTabbedPane()
        self.panelDescription = JPanel()
        self.panelRequest = JPanel()
        self.panelResponse = JPanel()
        self.panelRemediation = JPanel()
        
        # setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

        # setting up the table
        # initial data in the table
        tableData = [
            [None, None, None, None, None],
            [None, None, None, None, None],
            [None, None, None, None, None]
        ]
        tableColumns = ["#", "Issue Type/Name", "Severity", "Host", "Path"]
        # create the table model
        tableModel = table.DefaultTableModel(tableData, tableColumns)
        # model.types = array.array([java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class], java.lang.Class)
        # model.canEdit = array.array([False, False, False, False, False], java.lang.Boolean)
        # public Class getColumnClass(int columnIndex) {
        # return types [columnIndex]
        # }
        #
        # public boolean isCellEditable(int rowIndex, int columnIndex) {
        # return canEdit [columnIndex]
        # }

        # set the table model
        # if this fails, we have to use
        self.jTable1.setModel(tableModel)
        self.jTable1.setAutoCreateRowSorter(True)

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

        # top panel containing the table
        from java.awt import Color
        self.jPanel1.setBorder(BorderFactory.createLineBorder(Color(0, 0, 0)))

        # create the labels and textfields
        self.labelName.text = "Issue Type/Name"
        self.textName.text = "Issue Name/Type"
        self.labelSeverity.text = "Severity"
        # create and populate the combobox
        self.comboSeverity = JComboBox(["Critical", "High", "Medium", "Low", "Info"])

        self.labelHost.text = "Host"
        self.labelPath.text = "Path"
        self.textHost.text = "Issue Host"
        self.textPath.text = "Issue Path"

        from java.lang import Short
        # description panel
        panelDescriptionLayout = GroupLayout(self.panelDescription)
        self.panelDescription.setLayout(panelDescriptionLayout)
        panelDescriptionLayout.setHorizontalGroup(
            panelDescriptionLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 948, Short.MAX_VALUE)
        )
        panelDescriptionLayout.setVerticalGroup(
            panelDescriptionLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 287, Short.MAX_VALUE)
        )
        self.tabIssue.addTab("Description", self.panelDescription)

        # request tab
        panelRequestLayout = GroupLayout(self.panelRequest)
        self.panelRequest.setLayout(panelRequestLayout)
        panelRequestLayout.setHorizontalGroup(
            panelRequestLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 948, Short.MAX_VALUE)
        )
        panelRequestLayout.setVerticalGroup(
            panelRequestLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 287, Short.MAX_VALUE)
        )
        self.tabIssue.addTab("Request", self.panelRequest)

        # response tab
        panelResponseLayout = GroupLayout(self.panelResponse)
        self.panelResponse.setLayout(panelResponseLayout)
        panelResponseLayout.setHorizontalGroup(
            panelResponseLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 948, Short.MAX_VALUE)
        )
        panelResponseLayout.setVerticalGroup(
            panelResponseLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 287, Short.MAX_VALUE)
        )
        self.tabIssue.addTab("Response", self.panelResponse)

        # remediation tab
        panelRemediationLayout = GroupLayout(self.panelRemediation)
        self.panelRemediation.setLayout(panelRemediationLayout)
        panelRemediationLayout.setHorizontalGroup(
            panelRemediationLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 948, Short.MAX_VALUE)
        )
        panelRemediationLayout.setVerticalGroup(
            panelRemediationLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGap(0, 287, Short.MAX_VALUE)
        )
        self.tabIssue.addTab("Remediation", self.panelRemediation)

        # jpanel1?
        jPanel1Layout = GroupLayout(self.jPanel1)
        self.jPanel1.setLayout(jPanel1Layout)
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                    .addComponent(self.labelHost)
                    .addComponent(self.labelSeverity)
                    .addComponent(self.labelName))
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(self.textName)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(self.comboSeverity, GroupLayout.PREFERRED_SIZE, 98, GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(self.textHost, GroupLayout.PREFERRED_SIZE, 330, GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(self.labelPath)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(self.textPath))))
        .addComponent(self.tabIssue))
        .addContainerGap())
        )

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                          .addContainerGap()
                          .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
        .addComponent(self.labelName)
        .addComponent(self.textName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
        .addComponent(self.labelSeverity)
        .addComponent(self.comboSeverity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
        .addComponent(self.labelHost)
        .addComponent(self.labelPath)
        .addComponent(self.textHost, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        .addComponent(self.textPath, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(self.tabIssue)
            .addContainerGap())
        )

        layout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(layout)
        layout.setAutoCreateGaps(True)

        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                          .addContainerGap()
                          .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        .addComponent(self.jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(self.jScrollPane1))
        .addContainerGap())
        )
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                          .addContainerGap()
                          .addComponent(self.jScrollPane1, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE)
                          .addGap(18, 18, 18)
                          .addComponent(self.jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                          .addContainerGap())
        )

    # end of converted code
示例#17
0
 def testGetSetColor(self):
     color1 = Color(self.consts['1RED'], self.consts['1GREEN'],
                    self.consts['1BLUE'])
     setColor(self.pix1, color1)
     color2 = getColor(self.pix1)
     self.assert_(color1 == color2, 'Pixel did not setColor correctly.')
示例#18
0
 def set_basic_block_colors(self, start_addr, size):
     service.setBackgroundColor(start_addr, start_addr.add(size),
                                Color(0, 255, 172))
示例#19
0
bstRing_0_1 = factory.createRingLayer(data, 0, 0, 0)

bstRingUp = factory.createRingLayer(data, 0, 0, 0)
bstRingDown = factory.createRingLayer(data, 0, 1, 0)

bstTransform = factory.getDetectorTransform(data)

bstRing_2_0.setTransformation(bstTransform.get(2, 0, 0))
bstRing_2_1.setTransformation(bstTransform.get(2, 0, 1))

bstRing_0_0.setTransformation(bstTransform.get(0, 0, 0))
bstRing_0_1.setTransformation(bstTransform.get(0, 0, 1))

viewer = CLASVisualizer(100, 100, 1400, 1200)

viewer.setBackgroundColor(Color(150, 150, 255))
viewer.getDisplay().setBackgroundColor(Color(150, 150, 255))
viewer.setVisible(True)
#viewer.setTransparancy(0.5)

#viewer.add(bstRingUp.getBoundary(),Color(100,100,255))
#viewer.add(bstRingDown,Color(100,100,155))
#boundary = bstRing_2_0.getBoundary()
#boundary.show()
#viewer.add(boundary,Color(100,100,155))
viewer.add(bstRing_2_1, Color(100, 100, 155))
viewer.add(bstRing_0_0, Color(100, 100, 155))
viewer.add(bstRing_0_1, Color(100, 100, 155))

viewer.update()
示例#20
0
class UI:
    global dssFile
    dssFile = HecDss.open(r"C:\jy\SnowMelt\snotel_3v6.dss")
    global frame, lbl_close, list_locations, chckbxShowLocationPlot, eventsTable, dm_events, dm_meltRate
    global swePaths, precipPaths, tempPaths, bList, meltRateTable, startDateField, endDateField
    
    frame = JFrame("Snow PAC - Parameter Aggregator & Calculator")
#     frame.setUndecorated(True)  
    frame.setBackground(Color.WHITE)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100, 100, 1110, 775);
    
    contentPane = JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(EmptyBorder(5, 5, 5, 5));
    
    frame.setContentPane(contentPane);
    contentPane.setLayout(None);
    
    class MouseListener(MouseAdapter):
#       @Override
        def mousePressed(self, e):              
            global xx
            global xy
            xx = e.getX()
            xy = e.getY()

    class MouseMotionListener(MouseMotionAdapter):
#       @Override
        def mouseDragged(self, arg0):      
                x = arg0.getXOnScreen();
                y = arg0.getYOnScreen();
                frame.setLocation(x - xx, y - xy)
    
    mL = MouseListener()
    mML = MouseMotionListener()
    contentPane.addMouseListener(mL)
    contentPane.addMouseMotionListener(mML)
    
    
    
    btnIcon = ImageIcon("./Images/button.jpg")
    
    scrollPane_events = JScrollPane()
    scrollPane_events.setBounds(270, 372, 403, 263)
    contentPane.add(scrollPane_events)
     
    scrollPane_locations = JScrollPane();
    scrollPane_locations.setBounds(270, 49, 403, 203);
    contentPane.add(scrollPane_locations);  
    
    class deleteAction(AbstractAction):
    
        def actionPerformed(self, deleteEvent):
            # Get selected Rows and reverse list. Removes each row in list one at a time.
            # List is Reversed using [::-1], so it doesn't mess up the ordering as it deletes through the loop.
            for row in meltRateTable.getSelectedRows()[::-1]:
                dm_meltRate.removeRow(row)
                dm_meltRate.insertRow(row, [None, None])

    scrollPane_table =  JScrollPane();
    scrollPane_table.setBounds(708, 49, 338, 586);
    contentPane.add(scrollPane_table);
    
    meltRateTable =  JTable();
    scrollPane_table.setViewportView(meltRateTable);
    scrollPane_table.setBorder(LineBorder(Color(1, 1, 1), 2, True))
    meltRateTable.setFont( Font("Tahoma", Font.PLAIN, 11));
    
    columns = ("ATI (Deg F-Day)", "Meltrate (Inches/Deg F-Day)")
    data = []
    datarows = 100
    data.append([0,None])
    for i in range(datarows):
            data.append([None, None])
    dm_meltRate = DefaultTableModel(data, columns)
    
    meltRateTable.setModel(dm_meltRate)
    
    meltRateTable.getColumnModel().getColumn(0).setPreferredWidth(154);
    meltRateTable.getColumnModel().getColumn(1).setResizable(False);
    meltRateTable.getColumnModel().getColumn(1).setPreferredWidth(154);
    meltRateTable.setCellSelectionEnabled(True);
    
#    Delete data from the table using the Delete Key.
#     meltRateTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    inputMap = meltRateTable.getInputMap(JComponent.WHEN_FOCUSED);
    actionMap = meltRateTable.getActionMap();

    deleteActionStr = "delete";
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), deleteActionStr);
    actionMap.put(deleteActionStr, deleteAction())
                  
#     jLabelStartDate = JLabel()
#     jLabelStartDate.setText("Optional Start Date:")
#     jLabelStartDate.setToolTipText("Optional User Specified Date Range for Paired Data. If Specified, Will be Calculated for each Water Year.")
#     jLabelStartDate.setBounds(420, 263, 120, 20);
#     jLabelStartDate.setFont( Font("Tahoma", Font.PLAIN, 12))
#     contentPane.add(jLabelStartDate)
#     
#     startDateField = CalendarField();
#     jLabelStartDate.setLabelFor(startDateField);
#     startDateField.setMargin(Insets(0, 4, 0, 0));
#     startDateField.setBounds(540, 263, 118, 22);
#     startDateField.setFont(Font("Tahoma", Font.PLAIN, 12));
#     startDateField.setToolTipText("Optional User Specified Date Range for Paired Data. If Specified, Will be Calculated for each Water Year.")
#     contentPane.add(startDateField);
#     
#     jLabelEndDate = JLabel()
#     jLabelEndDate.setText("Optional End Date:")
#     jLabelEndDate.setToolTipText("Optional User Specified Date Range for Paired Data. If Specified, Will be Calculated for each Water Year.")
#     jLabelEndDate.setBounds(420, 293, 120, 20);
#     jLabelEndDate.setFont( Font("Tahoma", Font.PLAIN, 12))
#     contentPane.add(jLabelEndDate)
#     
#     endDateField = CalendarField();
#     jLabelEndDate.setLabelFor(endDateField);
#     endDateField.setMargin(Insets(0, 4, 0, 0));
#     endDateField.setBounds(540, 293, 118, 22);
#     endDateField.setFont(Font("Tahoma", Font.PLAIN, 12));
#     endDateField.setToolTipText("Optional User Specified Date Range for Paired Data. If Specified, Will be Calculated for each Water Year.")
#     contentPane.add(endDateField);

    def recalcBtnSelect(event):
        global swePaths, precipPaths, tempPaths
        selectedLocations = list_locations.getSelectedValuesList()
        swePaths, precipPaths, tempPaths = Locations.getSelectedLocations(selectedLocations)
        pathsNoDPart, sList, pList, tList = CalcAtiMelt.processPathsLists(swePaths, precipPaths, tempPaths)
        dList = CalcAtiMelt.processPathsDatesList(pathsNoDPart)
        aList, mList = CalcAtiMelt.calcATIMelt(selectedLocations, sList, pList, tList, dList)
        
        # Write Melt-Cum and ATI Locations to DSS.
        CalcAtiMelt.writeAtiMelt(selectedLocations, dList, aList, mList)
       
        # Plot Locations if checkbox.selected = True.
        if chckbxShowLocationPlot.selected is True:
#             print '\nPLOT TEAM ACTIVATE'
            PlotAtiMelt.plotAtiMelt(selectedLocations)
            
        # Use optional specified dates if fields are not blank.
#         if startDateField.getText() and endDateField.getText() is not None:
#             pdStart, pdEnd = ProcessPD.getSpecifiedDates(startDateField, endDateField)
#         else:
        pdStart = None
        pdEnd = None
            
        # Create Paired Data for Selected Locations.
        ProcessPD.processPairedData(selectedLocations, dList, mList, aList, pdStart, pdEnd)
        
        # Populate the UI Paired Data Table.
        CalcPD.updatePDTable(dssFile, eventsTable, dm_events)
        
        # Close the DSS File.
        dssFile.close()
        
    def plotPDBtnSelect(event):
        selected_Events = eventsTable.getSelectedRows()
#         print 'selected_Events: ', selected_Events
        # Sorting of the table by selecting the headers is doen by using: eventsTable.setAutoCreateRowSorter(True)
        # This sorts the table but does not update the table model.
        # To ensure sorting and selecting of resulting paths works properly, 
        # we must convert our selection using: eventsTable.convertRowIndexToModel(event)
        selectedEvents = []
        for event in selected_Events:
            selectedEvents.append(eventsTable.convertRowIndexToModel(event))
#         print 'selectedEvents: ', selectedEvents
        PlotPD.plotPD(eventsTable, selectedEvents, dssFile)
        dssFile.close()
    def calcMeltRateBtnSelect(event):
        selected_Events = eventsTable.getSelectedRows()
        selectedEvents = []
        for event in selected_Events:
            selectedEvents.append(eventsTable.convertRowIndexToModel(event))
        meltRateList = CalcMeltRate.calcMeltRate(selectedEvents, eventsTable, meltRateTable, dssFile)
        CalcMeltRate.updateTable(meltRateTable, meltRateList, dm_meltRate)
        dssFile.close()
    locDict, bList = Locations.getPaths(dssFile)
    locList = Locations.getList(locDict)
        
    list_locations = JList(locList);
    scrollPane_locations.setViewportView(list_locations);
    list_locations.setBorder(LineBorder(Color(0, 0, 0), 2, True))
    
    
    eventsTable =  JTable();
    scrollPane_events.setViewportView(eventsTable)
    scrollPane_events.setBorder(LineBorder(Color(1, 1, 1), 2, True))
    eventsTable.setFont( Font("Tahoma", Font.PLAIN, 11));
    
    locationsList, eventsList = Locations.getPairedData(dssFile)
    
    columns = ("Location", "Event")
    data = []
    for l, e in zip(locationsList, eventsList):
            data.append([l, e])
    dm_events = DefaultTableModel(data, columns)
    
    eventsTable.setModel(dm_events)
    eventsTable.setAutoCreateRowSorter(True)
    
    eventsTable.getColumnModel().getColumn(0).setPreferredWidth(154);
    eventsTable.getColumnModel().getColumn(1).setResizable(False);
    eventsTable.getColumnModel().getColumn(1).setPreferredWidth(154);
    eventsTable.setRowSelectionAllowed(True)
    
    inputPanel =  JPanel();
    inputPanel.setBorder( EmptyBorder(0, 0, 0, 0));
    inputPanel.setBackground( Color(255, 255, 255));
    inputPanel.setBounds(270, 11, 410, 27);
    contentPane.add(inputPanel);
    inputPanel.setLayout(None);
    inputPanel.setVisible(True);
    
    lbl_locations =  JLabel("DSS Locations that have PRECIP-INC, TEMPERATURE-AIR-AVG, and SWE. ");
    lbl_locations.setFont( Font("Tahoma", Font.PLAIN, 12));
    lbl_locations.setBounds(0, 11, 410, 15);
    inputPanel.add(lbl_locations);
    
    btnRecalc = JButton(btnIcon, actionPerformed=recalcBtnSelect);
    btnRecalc.setText("Calculate Paired Data")
    btnRecalc.setFont(Font("Tahoma", Font.BOLD, 12));
    btnRecalc.setForeground(Color.WHITE);
    btnRecalc.setBackground(Color.WHITE);
    btnRecalc.setBorderPainted(False); 
    btnRecalc.setContentAreaFilled(False); 
    btnRecalc.setFocusPainted(False); 
    btnRecalc.setOpaque(True);
    btnRecalc.setVerticalTextPosition(SwingConstants.CENTER);
    btnRecalc.setHorizontalTextPosition(SwingConstants.CENTER);
    btnRecalc.setBounds(382, 293, 165, 54);
    contentPane.add(btnRecalc);
    
    
    leftPanel = JPanel();
    leftPanel.setBackground(Color.DARK_GRAY);
    leftPanel.setBounds(0, 0, 250, 780);
    contentPane.add(leftPanel);
    leftPanel.setLayout(None);
     
    lbl_castle = JLabel("");
    lbl_castle.setBounds(110, 678, 40, 25);
    leftPanel.add(lbl_castle);
    
    i_corps = ImageIO.read(File("./Images/CorpsCastle.png"));
     
    corpsCastle = i_corps.getScaledInstance(lbl_castle.getWidth(), lbl_castle.getHeight(), Image.SCALE_SMOOTH);
     
    lbl_castle.setVerticalAlignment(SwingConstants.TOP);
    lbl_castle.setIcon(ImageIcon(corpsCastle));
     
    lbl_logo = JLabel("");
    lbl_logo.setBounds(18, 294, 218, 148);
    leftPanel.add(lbl_logo);
     

    snowLogo = ImageIO.read(File("./images/melted-snowman.png"));
     
    dssLogo = snowLogo.getScaledInstance(lbl_logo.getWidth(), lbl_logo.getHeight(),
            Image.SCALE_SMOOTH);
 
    lbl_logo.setVerticalAlignment(SwingConstants.TOP);
    lbl_logo.setIcon(ImageIcon(dssLogo));    
     
    lbl_logo2 = JLabel("");
    lbl_logo2.setBounds(18, 11, 218, 148);
    leftPanel.add(lbl_logo2);
     
    snowPacLogo = ImageIO.read(File("./images/SnowPac.png"));
     
    snowPac = snowPacLogo.getScaledInstance(lbl_logo2.getWidth(), lbl_logo2.getHeight(),
            Image.SCALE_SMOOTH);
 
    lbl_logo2.setVerticalAlignment(SwingConstants.TOP);
    lbl_logo2.setIcon(ImageIcon(snowPac));
    
#     lbl_close = JLabel("X")
#     
#     class CloseClickListener(MouseAdapter):
# #       @Override
#         def mouseEntered(self):     
#             lbl_close.setBorder(LineBorder.createGrayLineBorder())
# #       @Override
#         def mouseExited(self):
#             lbl_close.setBorder(None)
# #       @Override
#         def mouseClicked(self):
#             lbl_close.setBorder(BorderFactory.createLineBorder(Color.red));
#             sys.exit();
     
#     cL = CloseClickListener()
#     lbl_close.addMouseListener(cL)
#     
#     lbl_close.setHorizontalAlignment(SwingConstants.CENTER);
#     lbl_close.setForeground(Color(241, 57, 83));
#     lbl_close.setFont(Font("Tahoma", Font.PLAIN, 18));
#     lbl_close.setBounds(1071, 0, 37, 27);
#     contentPane.add(lbl_close);
    
    lblPxf = JLabel("Base Temperature (F):");
    lblPxf.setToolTipText("The temperature at which melt will occur.");
    lblPxf.setFont(Font("Tahoma", Font.PLAIN, 12));
    lblPxf.setBounds(400, 263, 132, 15);
    contentPane.add(lblPxf);

    
    textField_8 = JTextField();
    textField_8.setFont(Font("Tahoma", Font.PLAIN, 12));
    textField_8.setToolTipText("The temperature at which melt will occur.");
    textField_8.setText("32.0");
    textField_8.setBounds(548, 263, 40, 20);
    contentPane.add(textField_8);
    textField_8.setColumns(10);
    
    chckbxShowLocationPlot =  JCheckBox("Plot Locations");
    chckbxShowLocationPlot.setToolTipText("Will plot the Temp, Precip, SWE, ATI, and Melt for each selected location.");
    chckbxShowLocationPlot.setSelected(True);
    chckbxShowLocationPlot.setBackground(Color.WHITE);
    chckbxShowLocationPlot.setFont( Font("Tahoma", Font.PLAIN, 12));
    chckbxShowLocationPlot.setBounds(547, 310, 120, 23);
    contentPane.add(chckbxShowLocationPlot);
    
    
    
    lblEvents =  JLabel("Paired Data");
    lblEvents.setBounds(270, 346, 72, 15);
    contentPane.add(lblEvents);
    lblEvents.setFont( Font("Tahoma", Font.PLAIN, 12));
     
#     lblAtiThreshold = JLabel("ATI Threshold:");
#     lblAtiThreshold.setToolTipText("Some Melt Events are small & can be ignored. The ATI Threshold is a value that must be reached for the event to be listed.");
#     lblAtiThreshold.setFont(Font("Tahoma", Font.PLAIN, 12));
#     lblAtiThreshold.setBounds(500, 610, 82, 15);
#     contentPane.add(lblAtiThreshold);
    
#     textField_9 = JTextField();
#     textField_9.setFont(Font("Tahoma", Font.PLAIN, 12));
#     textField_9.setText("0.0");
#     textField_9.setToolTipText("Some Melt Events are small & can be ignored. The ATI Threshold is a value that must be reached for the event to be listed.");
#     textField_9.setColumns(10);
#     textField_9.setBounds(600, 608, 60, 20);
#     contentPane.add(textField_9);   
    
    btnPlot = JButton(btnIcon, actionPerformed=plotPDBtnSelect);
    btnPlot.setText("Plot Paired Data")
    btnPlot.setFont(Font("Tahoma", Font.BOLD, 12));
    btnPlot.setForeground(Color.WHITE);
    btnPlot.setBackground(Color.WHITE);
    btnPlot.setBorderPainted(False); 
    btnPlot.setContentAreaFilled(False); 
    btnPlot.setFocusPainted(False); 
    btnPlot.setOpaque(False);
    btnPlot.setVerticalTextPosition(SwingConstants.CENTER);
    btnPlot.setHorizontalTextPosition(SwingConstants.CENTER);
    btnPlot.setBounds(385, 657, 163, 54);
    contentPane.add(btnPlot);
    
    lblAtimeltrateTable =  JLabel("ATI-Meltrate Table");
    lblAtimeltrateTable.setFont(Font("Tahoma", Font.PLAIN, 12));
    lblAtimeltrateTable.setBounds(708, 10, 410, 15);
    contentPane.add(lblAtimeltrateTable);
    
    lblAtimeltrateTable2 =  JLabel("The first ATI value should be 0. ATI values must be ascending.");
    lblAtimeltrateTable2.setFont(Font("Tahoma", Font.PLAIN, 11));
    lblAtimeltrateTable2.setBounds(708, 30, 410, 15);
    contentPane.add(lblAtimeltrateTable2);
    
    btnCalculateMeltrate =  JButton(btnIcon, actionPerformed=calcMeltRateBtnSelect);
    btnCalculateMeltrate.setText("Calculate Meltrate")
    btnCalculateMeltrate.setFont( Font("Tahoma", Font.BOLD, 12));
    btnCalculateMeltrate.setToolTipText("Calculate Meltrate for ATI values in the ATI-Meltrate Table. Calculation will performed on the Paired Data Records Selected in the Paired Data Table.")
    btnCalculateMeltrate.setForeground(Color.WHITE);
    btnCalculateMeltrate.setBackground(Color.WHITE);
    btnCalculateMeltrate.setBorderPainted(False); 
    btnCalculateMeltrate.setContentAreaFilled(False); 
    btnCalculateMeltrate.setFocusPainted(False); 
    btnCalculateMeltrate.setOpaque(False);
    btnCalculateMeltrate.setVerticalTextPosition(SwingConstants.CENTER);
    btnCalculateMeltrate.setHorizontalTextPosition(SwingConstants.CENTER);
    btnCalculateMeltrate.setBounds(792, 657, 163, 54);
    contentPane.add(btnCalculateMeltrate);                        
            
    
         
    
    
    frame.setVisible(True)
    dssFile.close()
from ghidra.program.model.listing import CodeUnit
from ghidra.app.plugin.core.colorizer import ColorizingService
from java.awt import Color

#get all memory ranges
ranges = currentProgram.getMemory().getAddressRanges()
print("--------------------------------")

service = state.getTool().getService(ColorizingService)
if service is None:
    print "Can't find ColorizingService service"

for r in ranges:
    begin = r.getMinAddress()
    length = r.getLength()

    ins = getInstructionAt(begin)
    while (ins == None):
        ins = getInstructionAfter(ins)
    for i in range(length):
        mnemonic = ins.getMnemonicString()
        if mnemonic == "CALL":
            service.setBackgroundColor(ins.address, ins.address,
                                       Color(3, 169, 244))
        elif mnemonic == "JE" or mnemonic == "JZ" or mnemonic == "JNE" or mnemonic == "JNZ" or mnemonic == "JA" or mnemonic == "JAE" or mnemonic == "JBE" or mnemonic == "JB" or mnemonic == "JL" or mnemonic == "JLE" or mnemonic == "JG" or mnemonic == "JGE":
            service.setBackgroundColor(ins.address, ins.address,
                                       Color(205, 220, 57))
        ins = getInstructionAfter(ins)
        while (ins == None):
            ins = getInstructionAfter(ins)
示例#22
0
def getcolor(style, alpha=None):
    '''
    Get color.
    
    :param style: (*color object*) Color object.
    :param alpha: (*float*) Color alpha.
    '''
    if style is None:
        return None
        
    if isinstance(style, Color):
        c = style
        if not alpha is None:
            alpha = (int)(alpha * 255)
            c = Color(c.getRed(), c.getGreen(), c.getBlue(), alpha)
        return c
        
    c = Color.black
    if isinstance(style, str):
        if style == 'red':
            c = Color.red
        elif style == 'black':
            c = Color.black
        elif style == 'blue':
            c = Color.blue
        elif style == 'green':
            c = Color.green
        elif style == 'white':
            c = Color.white
        elif style == 'yellow':
            c = Color.yellow
        elif style == 'gray':
            c = Color.gray
        elif style == 'lightgray':
            c = Color.lightGray
        else:
            if 'r' in style:
                c = Color.red
            elif 'k' in style:
                c = Color.black
            elif 'b' in style:
                c = Color.blue
            elif 'g' in style:
                c = Color.green
            elif 'w' in style:
                c = Color.white
            elif 'c' in style:
                c = Color.cyan
            elif 'm' in style:
                c = Color.magenta
            elif 'y' in style:
                c = Color.yellow 
    elif isinstance(style, (tuple, list)):
        if len(style) == 3:
            c = Color(style[0], style[1], style[2])
        else:
            c = Color(style[0], style[1], style[2], style[3])
    
    if not alpha is None:
        alpha = (int)(alpha * 255)
        c = Color(c.getRed(), c.getGreen(), c.getBlue(), alpha)
    
    return c    
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self.helpers = callbacks.helpers
        callbacks.setExtensionName("Orchy-Webhook")
        self.frame = JPanel()
        self.frame.setSize(1024, 786)
        self.frame.setLayout(None)
        self.plugin_path = os.getcwd()
        self.db_file_path = os.path.join(os.getcwd(), 'burp_db.json')
        self.cwe_dict = json.load(open(self.db_file_path, 'r'))
        self.results = {}
        self.severity_dict = {
            'Low': 1,
            'Medium': 2,
            'High': 3,
            'Information': 0,
            'Info': 0,
        }
        self.urls = []
        self.confidence_dict = {'Certain': 3, 'Firm': 2, 'Tentative': 1}

        callbacks.registerScannerListener(self)

        button1 = JButton(ImageIcon(
            ((ImageIcon(self.plugin_path +
                        "/refresh.jpg")).getImage()).getScaledInstance(
                            13, 13, SCALE_SMOOTH)),
                          actionPerformed=self.refresh)
        button1.setBounds(30, 50, 22, 22)
        lbl0 = JLabel("Orchestron Webhook:")
        lbl0.setFont(Font("", Font.BOLD, 12))
        lbl0.setForeground(Color(0xFF7F50))
        lbl0.setBounds(60, 20, 200, 20)
        lbl1 = JLabel('Host')
        lbl1.setBounds(60, 50, 100, 20)
        self.txt1 = JComboBox()
        self.txt1.setBounds(200, 50, 220, 24)
        lbl2 = JLabel("Webhook Url")
        lbl2.setBounds(60, 80, 100, 20)
        self.txt2 = JTextField('', 300)
        self.txt2.setBounds(200, 80, 220, 24)
        lbl3 = JLabel("Authorization Token")
        lbl3.setBounds(60, 110, 200, 20)
        self.txt3 = JTextField('', 60)
        self.txt3.setBounds(200, 110, 220, 24)
        lbl4 = JLabel("Engagement-ID")
        lbl4.setBounds(60, 140, 200, 20)
        self.txt4 = JTextField('', 40)
        self.txt4.setBounds(200, 140, 220, 24)
        button2 = JButton('Push Results', actionPerformed=self.push)
        button2.setBounds(200, 170, 120, 24)
        self.message = JLabel('')
        self.message.setBounds(330, 170, 180, 24)
        self.frame.add(button1)
        self.frame.add(lbl0)
        self.frame.add(lbl1)
        self.frame.add(self.txt1)
        self.frame.add(lbl2)
        self.frame.add(self.txt2)
        self.frame.add(lbl3)
        self.frame.add(self.txt3)
        self.frame.add(lbl4)
        self.frame.add(self.txt4)
        self.frame.add(button2)
        self.frame.add(self.message)

        callbacks.customizeUiComponent(self.frame)
        callbacks.addSuiteTab(self)
示例#24
0
    def initUI(self):

        font = Font("Courier New", Font.BOLD, 14)

        #create the output text panel
        self.outText = JTextArea()
        self.outText.setEditable(False)
        self.outText.setFont(font)
        self.outText.setWrapStyleWord(True)
        self.outText.setLineWrap(True)

        #self.outText.setLineWrap(True)
        #self.outText.setWrapStyleWord(True)
        class NoGhostScroller(JScrollPane):
            def paintComponent(self, g):

                g.setColor(self.getBackground())
                g.fillRect(0, 0, self.getWidth(), self.getHeight())
                #super(NoGhostScroller, self).paintComponent(g)

        self.outTextScroller = JScrollPane(self.outText)
        self.outTextScroller.setHorizontalScrollBarPolicy(
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)
        self.outTextScroller.getVerticalScrollBar().setForeground(
            Color(255, 0, 0))
        #self.outText.setOpaque(False)
        self.outText.setBackground(Color(0, 20, 0))
        self.outText.setForeground(Color.WHITE)

        #self.outTextScroller.setOpaque(False)
        self.outTextScroller.setBackground(Color(0, 20, 0))

        #self.outText.repaint()

        #self.layered = JLayeredPane()
        #self.layered.setLayer(self.outTextScroller, 0)

        #create the input text box
        self.inText = JTextField()
        self.inText.setFocusTraversalKeysEnabled(False)
        self.inText.setFont(font)
        self.inText.setBackground(Color(0, 20, 0))
        self.inText.setForeground(Color.WHITE)
        self.inText.getCaret().setVisible(True)
        self.inText.getCaret().setBlinkRate(500)
        self.inText.setCaretColor(Color(200, 255, 200))

        class InFocusAdapter(FocusAdapter):
            def focusLost(adap, e):
                self.inText.setVisible(True)

        self.inText.addFocusListener(InFocusAdapter())

        self.nestedInputPanel = Panel("Insets 0 0 0 0")

        #create the directory text box
        self.directoryText = JTextField()
        self.directoryText.setEditable(False)
        self.directoryText.setFont(font)
        self.directoryText.setBackground(Color(0, 20, 0))
        self.directoryText.setForeground(Color.WHITE)
        #set up the console
        sys.stdout = FakeOut(self.outText)
        self.console = BashED_Console(stdout=sys.stdout)
        self.directoryText.setText(self.console.get_prompt())
        self.revalidate()

        dirTex = self.directoryText

        #create the listener that fires when the 'return' key is pressed
        class InputTextActionListener(ActionListener):
            def __init__(self, parent, inp, out, console):
                self.parent = parent
                self.inp = inp
                self.out = out
                self.console = console

            def actionPerformed(self, e):
                #print self.getCommandText()
                # print(self.console.get_prompt())
                # self.console.onecmd(self.inp.getText())
                # self.parent.write_out("\n" + self.inp.getText())
                # dirTex.setText(self.console.get_prompt())
                # self.inp.setText("")

                self.parent.write_out(self.console.get_prompt() +
                                      self.inp.getText() + '\n')
                if 'clear' in self.inp.getText().split(' ')[0]:
                    self.out.setText("")  #clear the screen
                else:
                    self.console.onecmd(self.inp.getText())

                dirTex.setText(self.console.get_prompt())
                self.inp.setText("")

        #create the listener that fires whenever a user hits a key
        class InputKeyActionListener(KeyAdapter):
            def __init__(self, parent, inp, out, console):
                self.parent = parent
                self.inp = inp
                self.out = out
                self.console = console

            def keyReleased(self, k):
                inp = self.inp.getText()
                if k.getKeyCode() == 9:  #tab character
                    autos = self.console.tabcomplete(self.inp.getText())
                    if len(autos) == 1:
                        self.inp.setText(autos[0])
                    else:
                        i = 0
                        for option in autos:
                            self.parent.write_out(option)
                            if i % 3 == 0:
                                print('\n')
                            else:
                                print('\t')
                hist = None
                if k.getKeyCode() == 38:
                    hist = self.console.next_hist()
                if k.getKeyCode() == 40:
                    hist = self.console.last_hist()

                if hist:
                    self.inp.setText(hist.rstrip('\n'))  #prevent from firing

        self.inText.addActionListener(
            InputTextActionListener(self, self.inText, self.outText,
                                    self.console))
        self.inText.addKeyListener(
            InputKeyActionListener(self, self.inText, self.outText,
                                   self.console))
示例#25
0
def getcolor(style, alpha=None):
    if style is None:
        return None
        
    if isinstance(style, Color):
        c = style
        if not alpha is None:
            alpha = (int)(alpha * 255)
            c = Color(c.getRed(), c.getGreen(), c.getBlue(), alpha)
        return c
        
    c = Color.black
    if isinstance(style, str):
        if style == 'red' or style == 'r':
            c = Color.red
        elif style == 'black' or style == 'k':
            c = Color.black
        elif style == 'blue' or style == 'b':
            c = Color.blue
        elif style == 'green' or style == 'g':
            c = Color.green
        elif style == 'white' or style == 'w':
            c = Color.white
        elif style == 'yellow' or style == 'y':
            c = Color.yellow
        elif style == 'gray':
            c = Color.gray
        elif style == 'lightgray':
            c = Color.lightGray
        elif style == 'cyan' or style == 'c':
            c = Color.cyan
        elif style == 'magenta' or style == 'm':
            c = Color.magenta
        else:
            c = Color.decode(style)
    elif isinstance(style, (tuple, list)):
        if len(style) == 3:
            c = Color(style[0], style[1], style[2])
        else:
            c = Color(style[0], style[1], style[2], style[3])
    
    if not alpha is None:
        alpha = (int)(alpha * 255)
        c = Color(c.getRed(), c.getGreen(), c.getBlue(), alpha)
    
    return c
示例#26
0
 def set_username(hunter):
     txt = "Connected as {}".format(hunter.username)
     self.status.set(txt, Color(0x006400), Color.WHITE)
示例#27
0
from BritefuryJ.Projection import Perspective, Subject, SubjectPathEntry

from LarchCore.Languages.Python2 import Python2
from LarchCore.Languages.Python2.CodeGenerator import compileForModuleExecution

from LarchCore.Worksheet import Schema
from LarchCore.Worksheet.WorksheetViewer import ViewSchema
from LarchCore.Worksheet.WorksheetEditor.View import WorksheetEditorSubject

_editableStyle = StyleSheet.style(Primitive.editable(True))

_worksheetMargin = 10.0

_pythonCodeBorderStyle = StyleSheet.style(
    Primitive.border(
        SolidBorder(1.0, 5.0, 10.0, 10.0, Color(0.2, 0.4, 0.8), None)))
_pythonCodeEditorBorderStyle = StyleSheet.style(
    Primitive.border(
        SolidBorder(1.5, 4.0, 10.0, 10.0, Color(0.4, 0.4, 0.5), None)))


def _worksheetContextMenuFactory(element, menu):
    def _onRefresh(button, event):
        model.refreshResults()

    model = element.getFragmentContext().getModel()

    refreshButton = Button.buttonWithLabel('Refresh', _onRefresh)
    worksheetControls = ControlsRow([refreshButton.alignHPack()])
    menu.add(Section(SectionHeading2('Worksheet'), worksheetControls))
    return True
示例#28
0
 def set_error(error):
     txt = "Disconnected  - {}".format(error.message)
     self.status.set(txt, Color(0xB80000), Color.WHITE)
示例#29
0
    def registerExtenderCallbacks(self, this_callbacks):  ### IBurpExtender
        global callbacks, helpers
        global extension_enable, in_scope_only
        global remove_csrf_headers, remove_csrf_params, change_method_to_post
        global change_ct_to_json, change_ct_to_plain, change_to_get

        callbacks = this_callbacks
        helpers = callbacks.getHelpers()
        callbacks.setExtensionName(NAME)

        self.settings = JPanel(GridBagLayout())
        c = GridBagConstraints()

        self.extension_enable_box = JCheckBox('Enable extension',
                                              extension_enable)
        self.setFontBold(self.extension_enable_box)
        self.extension_enable_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 0
        c.gridwidth = 1
        c.weightx = 1
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.WEST
        self.settings.add(self.extension_enable_box, c)

        self.in_scope_only_box = JCheckBox('Modify only in-scope requests',
                                           in_scope_only)
        self.setFontBold(self.in_scope_only_box)
        self.in_scope_only_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.in_scope_only_box, c)

        self.remove_csrf_headers_box = JCheckBox('Remove CSRF headers',
                                                 remove_csrf_params)
        self.setFontBold(self.remove_csrf_headers_box)
        self.remove_csrf_headers_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(self.remove_csrf_headers_box, c)

        remove_csrf_headers_box_lbl = JLabel(
            'Check to remove headers with CSRF tokens from all requests.')
        self.setFontItalic(remove_csrf_headers_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.settings.add(remove_csrf_headers_box_lbl, c)

        self.remove_csrf_params_box = JCheckBox('Remove CSRF parameters',
                                                remove_csrf_params)
        self.setFontBold(self.remove_csrf_params_box)
        self.remove_csrf_params_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 4
        self.settings.add(self.remove_csrf_params_box, c)

        remove_csrf_params_box_lbl = JLabel(
            'Check to remove URL/body parameters with CSRF tokens from all requests. URL-encoded, multipart, JSON parameters are supported.'
        )
        self.setFontItalic(remove_csrf_params_box_lbl)
        c.gridx = 0
        c.gridy = 5
        self.settings.add(remove_csrf_params_box_lbl, c)

        self.change_method_to_post_box = JCheckBox(
            'Change HTTP method to POST', change_method_to_post)
        self.setFontBold(self.change_method_to_post_box)
        self.change_method_to_post_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 6
        self.settings.add(self.change_method_to_post_box, c)

        change_method_to_post_lbl = JLabel(
            'Check to convert PUT/DELETE/PATCH method to POST in all requests.'
        )
        self.setFontItalic(change_method_to_post_lbl)
        c.gridx = 0
        c.gridy = 7
        self.settings.add(change_method_to_post_lbl, c)

        self.change_ct_to_json_box = JCheckBox('Change media type to json',
                                               change_ct_to_json)
        self.setFontBold(self.change_ct_to_json_box)
        self.change_ct_to_json_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 8
        self.settings.add(self.change_ct_to_json_box, c)

        change_ct_to_json_lbl = JLabel(
            'Check to convert body to json and set Content-Type to application/json in url-encoded requests.'
        )
        self.setFontItalic(change_ct_to_json_lbl)
        c.gridx = 0
        c.gridy = 9
        self.settings.add(change_ct_to_json_lbl, c)

        self.change_ct_to_plain_box = JCheckBox(
            'Change Content-Type to text/plain', change_ct_to_plain)
        self.setFontBold(self.change_ct_to_plain_box)
        self.change_ct_to_plain_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 10
        self.settings.add(self.change_ct_to_plain_box, c)

        change_ct_to_plain_lbl = JLabel(
            'Check to set Content-Type to text/plain in request with non-simple media type. Simple media types - application/application/x-www-form-urlencoded, text/plain, multipart/form-data.'
        )
        self.setFontItalic(change_ct_to_plain_lbl)
        c.gridx = 0
        c.gridy = 11
        self.settings.add(change_ct_to_plain_lbl, c)

        self.change_to_get_box = JCheckBox('Change to GET', change_to_get)
        self.setFontBold(self.change_to_get_box)
        self.change_to_get_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 12
        self.settings.add(self.change_to_get_box, c)

        change_to_get_lbl = JLabel(
            'Check to convert POST/PUT/DELETE/PATCH url-encoded requests to GET.'
        )
        self.setFontItalic(change_to_get_lbl)
        c.gridx = 0
        c.gridy = 13
        self.settings.add(change_to_get_lbl, c)

        self.csrf_headers_params = JPanel(GridBagLayout())
        c = GridBagConstraints()

        lblParams = JLabel("CSRF parameters:")
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.csrf_headers_params.add(lblParams, c)

        self.csrf_param_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.csrf_headers_params.add(self.csrf_param_text_field, c)

        lblParamsNote = JLabel(
            "Remove parameter from request if name contains")
        self.setFontItalic(lblParamsNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.csrf_headers_params.add(lblParamsNote, c)

        self.csrf_params_text_area = JTextArea()
        self.csrf_params_text_area.setColumns(20)
        self.csrf_params_text_area.setRows(10)
        self.csrf_params_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.csrf_params_mouse_listener = TextAreaMouseListener(
            self.csrf_params_text_area)
        self.csrf_params_text_area.addMouseListener(
            self.csrf_params_mouse_listener)
        for name in csrf_params_names:
            self.csrf_params_text_area.append(name + os.linesep)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.csrf_params_text_area)
        self.csrf_headers_params.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.csrf_param_text_field,
                                  self.csrf_params_text_area,
                                  self.csrf_params_mouse_listener,
                                  csrf_params_names)
        self.csrf_param_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.csrf_param_rm_button = JButton(
            'Remove', actionPerformed=handlers.handler_rm)
        self.csrf_param_restore_button = JButton(
            'Restore', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.csrf_param_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.csrf_param_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.csrf_param_restore_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.csrf_headers_params.add(buttonsPanel, c)

        lblHeaders = JLabel("CSRF headers:")
        self.setFontBold(lblHeaders)
        lblHeaders.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(40, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.csrf_headers_params.add(lblHeaders, c)

        self.csrf_header_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 2
        self.csrf_headers_params.add(self.csrf_header_text_field, c)

        lblHeadersNote = JLabel("Remove header from request if name equals to")
        self.setFontItalic(lblHeadersNote)
        c.fill = GridBagConstraints.NONE
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.csrf_headers_params.add(lblHeadersNote, c)

        self.csrf_headers_text_area = JTextArea()
        self.csrf_headers_text_area.setColumns(20)
        self.csrf_headers_text_area.setRows(10)
        self.csrf_headers_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.csrf_headers_mouse_listener = TextAreaMouseListener(
            self.csrf_headers_text_area)
        self.csrf_headers_text_area.addMouseListener(
            self.csrf_headers_mouse_listener)
        for name in csrf_headers_names:
            self.csrf_headers_text_area.append(name + os.linesep)
        c.gridx = 1
        c.gridy = 3
        sp = JScrollPane(self.csrf_headers_text_area)
        self.csrf_headers_params.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.csrf_header_text_field,
                                  self.csrf_headers_text_area,
                                  self.csrf_headers_mouse_listener,
                                  csrf_headers_names)
        self.csrf_header_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.csrf_header_rm_button = JButton(
            'Remove', actionPerformed=handlers.handler_rm)
        self.csrf_header_restore_button = JButton(
            'Restore', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.csrf_header_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.csrf_header_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.csrf_header_restore_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 3
        c.fill = GridBagConstraints.NONE
        self.csrf_headers_params.add(buttonsPanel, c)

        self.whitelist = JPanel(GridBagLayout())
        c = GridBagConstraints()

        lblWhitelist = JLabel("URLs whitelist:")
        self.setFontBold(lblWhitelist)
        lblWhitelist.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.whitelist.add(lblWhitelist, c)

        self.whitelist_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.whitelist.add(self.whitelist_text_field, c)

        lblWhitelistNote = JLabel(
            "Do not perform request modification if URL starts with")
        self.setFontItalic(lblWhitelistNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.whitelist.add(lblWhitelistNote, c)

        self.whitelist_text_area = JTextArea()
        self.whitelist_text_area.setColumns(30)
        self.whitelist_text_area.setRows(10)
        self.whitelist_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.whitelist_mouse_listener = TextAreaMouseListener(
            self.whitelist_text_area)
        self.whitelist_text_area.addMouseListener(
            self.whitelist_mouse_listener)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.whitelist_text_area)
        self.whitelist.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.whitelist_text_field,
                                  self.whitelist_text_area,
                                  self.whitelist_mouse_listener, [])
        self.whitelist_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.whitelist_rm_button = JButton('Remove',
                                           actionPerformed=handlers.handler_rm)
        self.whitelist_clear_button = JButton(
            'Clear', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.whitelist_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.whitelist_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.whitelist_clear_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.whitelist.add(buttonsPanel, c)

        self.tabs = JTabbedPane()
        self.tabs.addTab('Settings', self.settings)
        self.tabs.addTab('CSRF params/headers to remove',
                         self.csrf_headers_params)
        self.tabs.addTab('Requests whitelist', self.whitelist)

        callbacks.customizeUiComponent(self.tabs)
        callbacks.addSuiteTab(self)

        callbacks.registerProxyListener(self)

        callbacks.registerContextMenuFactory(
            SendToWhitelist(self.whitelist_text_area))

        print "Successfully loaded %s v%s by Mikhail Egorov @0ang3el" % (
            NAME, VERSION)
示例#30
0
from java.awt import Color

from BritefuryJ.Pres.Primitive import Primitive, Label
from BritefuryJ.StyleSheet import StyleSheet
from BritefuryJ.Graphics import SolidBorder

_error_border = SolidBorder(1.0, 4.0, 5.0, 5.0, Color(1.0, 0.5, 0.5),
                            Color(1.0, 0.95, 0.95))
_error_style = StyleSheet.style(Primitive.foreground(Color(0.3, 0.0, 0.0)))


def error_message(message):
    return _error_border.surround(_error_style(Label(message)))


# Error sentinel value


class ErrorSentinel(object):
    error_message = 'Generic error'

    def __present__(self, fragment, inh):
        return error_message(self.error_message)