Пример #1
0
 def _prepare_components(self, values):
     for scope_tool in Application.SCOPE_TOOLS:
         check_box = JCheckBox(scope_tool)
         check_box.setSelected(scope_tool in values['scope_tools'])
         check_box.addItemListener(self)
         self._check_boxes.append(check_box)
         self.add(check_box)
Пример #2
0
 def display(self, values):
     self.add(JLabel('<html><b>Statuses:</b></html>'))
     for status in Application.ITEM_STATUSES:
         check_box = JCheckBox(status)
         check_box.setSelected(status in values['statuses'])
         check_box.addItemListener(self)
         self._check_boxes.append(check_box)
         self.add(check_box)
Пример #3
0
    def initUserInterface(self):
        class TriggerLoggingListener(ItemListener):
            def __init__(self, extender):
                self.extender = extender

            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    self.extender.loggingEnabled = True
                else:
                    self.extender.loggingEnabled = False

        loggingTrigger = JCheckBox("Enable logging (clearing browser cache might be needed to reflect the change)")
        loggingTrigger.addItemListener(TriggerLoggingListener(self))

        self.configurationPanel = JPanel()
        self.configurationPanel.setLayout(FlowLayout(FlowLayout.LEFT))
        self.configurationPanel.add(loggingTrigger)
Пример #4
0
    def run(self):
        #-----------------------------------------------------------------------
        # Create and set up the window.
        #-----------------------------------------------------------------------
        frame = JFrame('GlassPaneDemo')
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # Start creating and adding components.
        #-----------------------------------------------------------------------
        changeButton = JCheckBox('Glass pane "visible"')
        changeButton.setSelected(0)

        #-----------------------------------------------------------------------
        # Set up the content pane, where the 'main GUI' lives.
        #-----------------------------------------------------------------------
        contentPane = frame.getContentPane()
        contentPane.setLayout(FlowLayout())
        contentPane.add(changeButton)
        contentPane.add(JButton('Button 1'))
        contentPane.add(JButton('Button 2'))

        #-----------------------------------------------------------------------
        # Set up the menu bar, which appears above the content pane.
        #-----------------------------------------------------------------------
        menuBar = JMenuBar()
        menu = JMenu('Menu')
        menu.add(JMenuItem('Do nothing'))
        menuBar.add(menu)
        frame.setJMenuBar(menuBar)

        #-----------------------------------------------------------------------
        # Set up the glass pane, which appears over both menu bar and
        # content pane and is an item listener on the change button
        #-----------------------------------------------------------------------
        myGlassPane = MyGlassPane(changeButton, menuBar, contentPane)
        changeButton.addItemListener(myGlassPane)
        frame.setGlassPane(myGlassPane)

        #-----------------------------------------------------------------------
        # Resize the frame to display the visible components contain therein,
        # and have the frame (application) make itself visisble.
        #-----------------------------------------------------------------------
        frame.pack()
        frame.setVisible(1)
Пример #5
0
class CheckBoxPanel(JPanel, ItemListener):
    __metaclass__ = Singleton

    def __init__(self):
        super(CheckBoxPanel, self).__init__()
        self._check_box = None

    def itemStateChanged(self, event):
        Application.get_instance().execute(
            SetDomainDictValueCommand(self._get_domain_dict_type(),
                                      self._get_domain_dict_key(),
                                      self._check_box.isSelected()))

    def display(self, values):
        self._check_box = JCheckBox(self._get_label())
        self._check_box.setSelected(values[self._get_domain_dict_key()])
        self._check_box.addItemListener(self)
        self.add(self._check_box)
Пример #6
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory):
    def registerExtenderCallbacks(self, callbacks):
        # smart xss feature (print conclusion and observation)
        # mark resulsts
        # add automatic check pages in the same domain

        self.tagPayloads = [
            "<b>test", "<b onmouseover=test()>test",
            "<img src=err onerror=test()>", "<script>test</script>"
            "", "<scr ipt>test</scr ipt>", "<SCRIPT>test;</SCRIPT>",
            "<scri<script>pt>test;</scr</script>ipt>",
            "<SCRI<script>PT>test;</SCR</script>IPT>",
            "<scri<scr<script>ipt>pt>test;</scr</sc</script>ript>ipt>",
            "<IMG \"\"\"><SCRIPT>test</SCRIPT>\">",
            "<IMG '''><SCRIPT>test</SCRIPT>'>", "<SCR%00IPT>test</SCR%00IPT>",
            "<IFRAME SRC='f' onerror=\"test\"></IFRAME>",
            "<IFRAME SRC='f' onerror='test'></IFRAME>",
            "<<SCRIPT>test//<</SCRIPT>", "<img src=\"1\" onerror=\"test\">",
            "<img src='1' onerror='test'",
            "<STYLE TYPE=\"text/javascript\">test;</STYLE>",
            "<<SCRIPT>test//<</SCRIPT>"
        ]
        self.attributePayloads = [
            "\"\"\"><SCRIPT>test", "'''><SCRIPT>test'",
            "\"><script>test</script>", "\"><script>test</script><\"",
            "'><script>test</script>", "'><script>test</script><'",
            "\";test;\"", "';test;'", ";test;", "\";test;//",
            "\"onmouseover=test ", "onerror=\"test\"", "onerror='test'",
            "onload=\"test\"", "onload='test'"
        ]
        self.xssKey = 'xssme'
        # keep a reference to our callbacks object
        self._callbacks = callbacks

        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("XSSor")

        self.affectedResponses = ArrayList()
        self._log = ArrayList()
        self._lock = Lock()

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        self._splitpane.setLeftComponent(scrollPane)

        # tabs with request/response viewers
        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Request", self._requestViewer.getComponent())
        tabs.addTab("Response", self._responseViewer.getComponent())

        clearAPListBtn = JButton("Clear List",
                                 actionPerformed=self.clearAPList)
        clearAPListBtn.setBounds(10, 85, 120, 30)
        apListLabel = JLabel('Affected Pages List:')
        apListLabel.setBounds(10, 10, 140, 30)
        self.affectedModel = DefaultListModel()
        self.affectedList = JList(self.affectedModel)
        self.affectedList.addListSelectionListener(listSelectedChange(self))
        scrollAList = JScrollPane(self.affectedList)
        scrollAList.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollAList.setBounds(150, 10, 550, 200)
        scrollAList.setBorder(LineBorder(Color.BLACK))

        APtabs = JTabbedPane()
        self._requestAPViewer = callbacks.createMessageEditor(self, False)
        self._responseAPViewer = callbacks.createMessageEditor(self, False)
        APtabs.addTab("Request", self._requestAPViewer.getComponent())
        APtabs.addTab("Affeced Page Response",
                      self._responseAPViewer.getComponent())
        APtabs.setBounds(0, 250, 700, 350)
        APtabs.setSelectedIndex(1)

        self.APpnl = JPanel()
        self.APpnl.setBounds(0, 0, 1000, 1000)
        self.APpnl.setLayout(None)
        self.APpnl.add(scrollAList)
        self.APpnl.add(clearAPListBtn)
        self.APpnl.add(APtabs)
        self.APpnl.add(apListLabel)
        tabs.addTab("Affected Pages", self.APpnl)
        self.intercept = 0

        ## init conf panel
        startLabel = JLabel("Plugin status:")
        startLabel.setBounds(10, 10, 140, 30)

        payloadLabel = JLabel("Basic Payload:")
        payloadLabel.setBounds(10, 50, 140, 30)

        self.basicPayload = "<script>alert(1)</script>"
        self.basicPayloadTxt = JTextArea(self.basicPayload, 5, 30)
        self.basicPayloadTxt.setBounds(120, 50, 305, 30)

        self.bruteForceMode = JCheckBox("Brute Force Mode")
        self.bruteForceMode.setBounds(120, 80, 300, 30)
        self.bruteForceMode.addItemListener(handleBFModeChange(self))

        self.tagPayloadsCheck = JCheckBox("Tag paylods")
        self.tagPayloadsCheck.setBounds(120, 100, 300, 30)
        self.tagPayloadsCheck.setSelected(True)
        self.tagPayloadsCheck.setEnabled(False)
        self.tagPayloadsCheck.addItemListener(handleBFModeList(self))

        self.attributePayloadsCheck = JCheckBox("Attribute payloads")
        self.attributePayloadsCheck.setBounds(260, 100, 300, 30)
        self.attributePayloadsCheck.setSelected(True)
        self.attributePayloadsCheck.setEnabled(False)
        self.attributePayloadsCheck.addItemListener(handleBFModeList(self))

        payloadListLabel = JLabel("Payloads list (for BF mode):")
        payloadListLabel.setBounds(10, 130, 140, 30)

        self.payloadsModel = DefaultListModel()
        self.payloadsList = JList(self.payloadsModel)
        scrollPayloadsList = JScrollPane(self.payloadsList)
        scrollPayloadsList.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollPayloadsList.setBounds(120, 170, 300, 200)
        scrollPayloadsList.setBorder(LineBorder(
            Color.BLACK))  # add buttons to remove payloads and add

        for payload in self.tagPayloads:
            self.payloadsModel.addElement(payload)

        for payload in self.attributePayloads:
            self.payloadsModel.addElement(payload)

        self.startButton = JButton("XSSor is off",
                                   actionPerformed=self.startOrStop)
        self.startButton.setBounds(120, 10, 120, 30)
        self.startButton.setBackground(Color(255, 100, 91, 255))

        consoleTab = JTabbedPane()
        self.consoleLog = JTextArea("", 5, 30)
        scrollLog = JScrollPane(self.consoleLog)
        scrollLog.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollLog.setBounds(120, 170, 550, 200)
        scrollLog.setBorder(LineBorder(Color.BLACK))
        scrollLog.getVerticalScrollBar().addAdjustmentListener(
            autoScrollListener(self))
        consoleTab.addTab("Console", scrollLog)
        consoleTab.setBounds(0, 400, 500, 200)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000)
        self.pnl.setLayout(None)
        self.pnl.add(self.startButton)
        self.pnl.add(startLabel)
        self.pnl.add(payloadLabel)
        self.pnl.add(self.basicPayloadTxt)
        self.pnl.add(self.bruteForceMode)
        self.pnl.add(payloadListLabel)
        self.pnl.add(scrollPayloadsList)
        self.pnl.add(self.attributePayloadsCheck)
        self.pnl.add(self.tagPayloadsCheck)
        self.pnl.add(consoleTab)

        tabs.addTab("Configuration", self.pnl)
        tabs.setSelectedIndex(3)
        self._splitpane.setRightComponent(tabs)

        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(tabs)

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)
        self._callbacks.registerContextMenuFactory(self)

        print "Thank you for installing XSSor v0.1 extension"
        print "Created by Barak Tawily"
        print "\nGithub:\nhttps://github.com/Quitten/XSSor"
        return

    #
    # implement ITab
    #

    def getTabCaption(self):
        return "XSSor"

    def getUiComponent(self):
        return self._splitpane

    #
    # implement IHttpListener
    #

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if self.intercept == 1:
            if toolFlag == 4:
                # only process requests
                if not messageIsRequest:
                    self.checkForKey(messageInfo)

        return

    def printLog(self, message):
        self.consoleLog.setText(self.consoleLog.getText() + '\r\n' + message)

    def checkXSS(self, messageInfo, urlStr, requestBody, currentPayload):
        self.printLog('trying exploit with the payload: ' + currentPayload)
        requestURL = URL(urlStr.replace(self.xssKey, currentPayload))
        requestBody = requestBody.replace(self.xssKey,
                                          urllib.pathname2url(currentPayload))
        httpService = self._helpers.buildHttpService(
            str(requestURL.getHost()), int(requestURL.getPort()),
            requestURL.getProtocol() == "https")
        response = self._callbacks.makeHttpRequest(httpService, requestBody)
        responseInfo = self._helpers.analyzeResponse(response.getResponse())
        analyzedResponse = self._helpers.bytesToString(response.getResponse(
        ))  # change body offeset + make ui for affeccted pages
        responseBody = analyzedResponse.encode('utf-8')
        vulnOrNot = 'no'

        if currentPayload in responseBody:
            self.printLog('payload: ' + currentPayload +
                          ' found to be vulnarble')
            vulnOrNot = 'yes'
            # mark the payload
        if not len(self.affectedResponses) == 0:
            for request in self.affectedResponses:  # bug in case of no response in messageinfo
                self.printLog('checking affeccted page' +
                              str(request.getUrl()))
                requestURL = request.getUrl()
                httpService = self._helpers.buildHttpService(
                    str(requestURL.getHost()), int(requestURL.getPort()),
                    requestURL.getProtocol() == "https")
                affectedPageResponse = self._callbacks.makeHttpRequest(
                    httpService, request.getRequest())
                analyzedResponse = self._helpers.bytesToString(
                    affectedPageResponse.getResponse())
                responseBody = analyzedResponse.encode('utf-8')

            if currentPayload in responseBody:
                vulnOrNot = 'yes, affected page'
                self.printLog('affeccted page has been found as vulnerable')

        self._lock.acquire()
        row = self._log.size()
        self._log.add(
            LogEntry(
                self._helpers.analyzeRequest(response).getUrl(),
                self._callbacks.saveBuffersToTempFiles(response),
                currentPayload, vulnOrNot))
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    def checkForKey(self, messageInfo):

        currentPayload = self.tagPayloads[0]
        requestInfo = self._helpers.analyzeRequest(messageInfo)
        requestHeaders = list(requestInfo.getHeaders())

        requestURL = requestInfo.getUrl()
        urlStr = str(requestURL)
        self.printLog('checking for xss key in URL: ' + urlStr)
        requestBody = self._helpers.bytesToString(messageInfo.getRequest())
        requestBody = re.sub(
            'Referer:.*\n', '', requestBody, flags=re.MULTILINE,
            count=1)  # workaround avoid xsskey in the referer newHeaders
        if self.xssKey in urlStr or self.xssKey in requestBody:
            self.printLog('xss key has been found')
            if self.bruteForceMode.isSelected():
                for i in range(0, self.payloadsModel.getSize()):
                    payload = self.payloadsModel.getElementAt(i)
                    self.checkXSS(messageInfo, urlStr, requestBody, payload)
            else:
                self.checkXSS(messageInfo, urlStr, requestBody,
                              self.basicPayloadTxt.getText())

                #

    # extend AbstractTableModel
    #

    def getRowCount(self):
        try:
            return self._log.size()
        except:
            return 0

    def getColumnCount(self):
        return 3

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "URL"
        if columnIndex == 1:
            return "Payload"
        if columnIndex == 2:
            return "Vulnerable?"

        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            # return self._callbacks.getToolName(logEntry._tool)
            return logEntry._url.toString()

        if columnIndex == 1:
            return logEntry._payload

        if columnIndex == 2:
            return logEntry._vulnOrNot

        return ""

    #
    # implement IMessageEditorController
    # this allows our request/response viewers to obtain details about the messages being displayed
    #

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()

    def startOrStop(self, event):
        if self.startButton.getText() == "XSSor is off":
            self.startButton.setText("XSSor is on")
            self.startButton.setBackground(Color.GREEN)
            self.printLog('on, waiting for key word to be found (' +
                          self.xssKey + ')')
            self.intercept = 1
        else:
            self.startButton.setText("XSSor is off")
            self.startButton.setBackground(Color(255, 100, 91, 255))
            self.intercept = 0

    def clearAPList(self, event):
        self.affectedModel.clear()
        self.affectedResponses = ArrayList()

    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages()
        if responses > 0:
            ret = LinkedList()
            affectedMenuItem = JMenuItem("XSSor: Add affected page")
            affectedMenuItem.addActionListener(
                handleMenuItems(self, responses[0], "affected"))
            ret.add(affectedMenuItem)
            return (ret)
        return null

    def addAfectedPage(self, messageInfo):
        self.affectedModel.addElement(
            str(self._helpers.analyzeRequest(messageInfo).getUrl()))
        self.affectedResponses.add(messageInfo)
Пример #7
0
    class ConfigurationController(IMessageEditorController):
        def __init__(self, parent):
            self._parent = parent

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

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

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

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

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

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

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

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

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

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

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

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

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

        class WafSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._waf = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._waf = False
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

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

        self.selected_input_file = None
        self.selected_output_file = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True
    def show_detectable_objects_dialog(self, e):
        parentComponent = SwingUtilities.windowForComponent(self.panel0)
        self.detectable_obejcts_dialog = JDialog(
            parentComponent, "List of Objects to Detect",
            ModalityType.APPLICATION_MODAL)
        panel = JPanel()
        self.detectable_obejcts_dialog.add(panel)
        gbPanel = GridBagLayout()
        gbcPanel = GridBagConstraints()
        panel.setLayout(gbPanel)

        y = 0
        x = 0
        for line in self.local_settings.getClassesOfInterest():
            if y > 15:
                y = 0
                x = x + 1

            class_check_box = JCheckBox(line['name'])
            self.classes_of_interest_checkboxes.append(class_check_box)
            class_check_box.setEnabled(True)
            class_check_box.setSelected(line['enabled'])
            class_check_box.addItemListener(self.on_class_checkbox_clicked)
            gbcPanel.gridx = x
            gbcPanel.gridy = y
            gbcPanel.gridwidth = 1
            gbcPanel.gridheight = 1
            gbcPanel.fill = GridBagConstraints.BOTH
            gbcPanel.weightx = 1
            gbcPanel.weighty = 1
            gbcPanel.anchor = GridBagConstraints.NORTH
            gbPanel.setConstraints(class_check_box, gbcPanel)
            panel.add(class_check_box)
            y = y + 1

        blank_1_L = JLabel(" ")
        blank_1_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 1
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_1_L, gbcPanel)
        panel.add(blank_1_L)

        deselect_all_button = JButton("Deselect all")
        deselect_all_button.setEnabled(True)
        deselect_all_button.addActionListener(self.on_deselect_all_clicked)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(deselect_all_button, gbcPanel)
        panel.add(deselect_all_button)

        select_all_button = JButton("Select all")
        select_all_button.setEnabled(True)
        select_all_button.addActionListener(self.on_select_all_clicked)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(select_all_button, gbcPanel)
        panel.add(select_all_button)

        blank_2_L = JLabel(" ")
        blank_2_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 3
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_2_L, gbcPanel)
        panel.add(blank_2_L)

        cancel_button = JButton("Cancel")
        cancel_button.setEnabled(True)
        cancel_button.addActionListener(
            self.on_cancel_classes_of_interest_click)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(cancel_button, gbcPanel)
        panel.add(cancel_button)

        save_button = JButton("Save")
        save_button.setEnabled(True)
        save_button.addActionListener(self.on_save_classes_of_interest_click)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(save_button, gbcPanel)
        panel.add(save_button)

        blank_3_L = JLabel(" ")
        blank_3_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 5
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_3_L, gbcPanel)
        panel.add(blank_3_L)

        self.detectable_obejcts_dialog.pack()
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        self.detectable_obejcts_dialog.setLocation(
            int((screenSize.getWidth() / 2) -
                (self.detectable_obejcts_dialog.getWidth() / 2)),
            int((screenSize.getHeight() / 2) -
                (self.detectable_obejcts_dialog.getHeight() / 2)))
        self.detectable_obejcts_dialog.setVisible(True)
Пример #10
0
    def __init__(self, extender):
        super(BeautifierOptionsPanel, self).__init__()
        self._extender = extender

        self.contentWrapper = JPanel(GridBagLayout())
        self.setViewportView(self.contentWrapper)
        self.getVerticalScrollBar().setUnitIncrement(16)
        self.addMouseListener(self.RequestFocusListener(
            self))  # Let textArea lose focus when click empty area

        innerContainer = JPanel(GridBagLayout())
        innerContainer.setFocusable(
            True
        )  # make sure the maxSizeText TextField is not focused when BeautifierOptionsPanel display

        # generalOptionPanel and it's inner component
        maxSizeLabel = JLabel("Max Size: ")
        self.maxSizeText = JTextField(5)
        self.maxSizeText.setHorizontalAlignment(SwingConstants.RIGHT)
        self.maxSizeText.addFocusListener(self.MaxSizeTextListener(self))
        sizeUnitLabel = JLabel("KB")

        generalOptionPanel = JPanel(GridBagLayout())
        generalOptionPanel.setBorder(
            BorderFactory.createTitledBorder("General Options"))
        gbc = GridBagConstraints()
        gbc.anchor = GridBagConstraints.WEST
        gbc.gridx = 0
        gbc.gridy = 0
        generalOptionPanel.add(maxSizeLabel, gbc)
        gbc.fill = GridBagConstraints.HORIZONTAL
        gbc.gridx = 1
        gbc.gridy = 0
        generalOptionPanel.add(self.maxSizeText, gbc)
        gbc.fill = GridBagConstraints.NONE
        gbc.gridx = 2
        gbc.gridy = 0
        gbc.weightx = 1.0
        generalOptionPanel.add(sizeUnitLabel, gbc)

        gbc = GridBagConstraints()
        gbc.fill = GridBagConstraints.BOTH
        gbc.gridx = 1
        gbc.gridy = 0
        gbc.gridheight = 2
        innerContainer.add(generalOptionPanel, gbc)

        # messageTabOptionPanel and it's inner component
        self.messageTabFormatCheckBoxs = []
        for f in supportedFormats:
            ckb = JCheckBox(f)
            ckb.addItemListener(self.messageTabFormatListener)
            self.messageTabFormatCheckBoxs.append(ckb)

        messageTabOptionPanel = JPanel()
        messageTabOptionPanel.setLayout(
            BoxLayout(messageTabOptionPanel, BoxLayout.Y_AXIS))
        messageTabOptionPanel.setBorder(
            BorderFactory.createTitledBorder("Enable in MessageEditorTab"))
        for b in self.messageTabFormatCheckBoxs:
            messageTabOptionPanel.add(b)

        gbc.gridx = 1
        gbc.gridy = 2
        gbc.gridheight = 9

        innerContainer.add(messageTabOptionPanel, gbc)

        # replaceResponsePanel and it's inner component
        self.chkEnableReplace = JCheckBox("Enable")
        self.chkEnableReplace.addItemListener(self.repalceResponseBoxListener)
        replaceResponseFormatLabel = JLabel("Format")
        self.replaceResponseFormatCheckBoxs = []
        for f in supportedFormats:
            ckb = JCheckBox(f)
            ckb.addItemListener(self.replaceResponseFormatListener)
            self.replaceResponseFormatCheckBoxs.append(ckb)
        replaceResponseIncludeLabel = JLabel(
            "Include URL that matches below(one item one line)")
        self.URLIncludeTextArea = JTextArea(6, 32)
        self.URLIncludeTextArea.addFocusListener(
            self.URLIncludeFocusListener(self))
        URLIncludeScrollPane = JScrollPane(self.URLIncludeTextArea)
        URLIncludeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        replaceResponseExcludeLabel = JLabel(
            "Exclude URL that matches below(one item one line)")
        self.URLExcludeTextArea = JTextArea(5, 32)
        self.URLExcludeTextArea.addFocusListener(
            self.URLExcludeFocusListener(self))
        URLExcludeScrollPane = JScrollPane(self.URLExcludeTextArea)
        URLExcludeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT)

        replaceResponsePanel = JPanel()
        replaceResponsePanel.setLayout(
            BoxLayout(replaceResponsePanel, BoxLayout.Y_AXIS))
        replaceResponsePanel.setBorder(
            BorderFactory.createTitledBorder("Replace PROXY Response"))
        replaceResponsePanel.add(self.chkEnableReplace)
        replaceResponsePanel.add(Box.createVerticalStrut(10))
        replaceResponsePanel.add(replaceResponseFormatLabel)
        for b in self.replaceResponseFormatCheckBoxs:
            replaceResponsePanel.add(b)
        replaceResponsePanel.add(Box.createVerticalStrut(10))
        replaceResponsePanel.add(replaceResponseIncludeLabel)
        replaceResponsePanel.add(URLIncludeScrollPane)
        replaceResponsePanel.add(Box.createVerticalStrut(10))
        replaceResponsePanel.add(replaceResponseExcludeLabel)
        replaceResponsePanel.add(URLExcludeScrollPane)

        gbc.gridy = 11
        innerContainer.add(replaceResponsePanel, gbc)

        # let innerContainer keep away from left and up
        gbc = GridBagConstraints()
        gbc.gridx = 1
        gbc.gridy = 1
        self.contentWrapper.add(Box.createHorizontalStrut(15), gbc)

        # gbc.ipadx = gbc.ipady = 25
        gbc.gridx = 2
        self.contentWrapper.add(innerContainer, gbc)

        # let innerContainer stay left side
        gbc = GridBagConstraints()
        gbc.gridx = 3
        gbc.gridy = 2
        gbc.gridwidth = 1
        gbc.weightx = gbc.weighty = 1
        paddingPanel = JPanel()
        self.contentWrapper.add(paddingPanel, gbc)

        self.setDefaultOptionDisplay()
Пример #11
0
class BeautifierOptionsPanel(JScrollPane):
    def __init__(self, extender):
        super(BeautifierOptionsPanel, self).__init__()
        self._extender = extender

        self.contentWrapper = JPanel(GridBagLayout())
        self.setViewportView(self.contentWrapper)
        self.getVerticalScrollBar().setUnitIncrement(16)
        self.addMouseListener(self.RequestFocusListener(
            self))  # Let textArea lose focus when click empty area

        innerContainer = JPanel(GridBagLayout())
        innerContainer.setFocusable(
            True
        )  # make sure the maxSizeText TextField is not focused when BeautifierOptionsPanel display

        # generalOptionPanel and it's inner component
        maxSizeLabel = JLabel("Max Size: ")
        self.maxSizeText = JTextField(5)
        self.maxSizeText.setHorizontalAlignment(SwingConstants.RIGHT)
        self.maxSizeText.addFocusListener(self.MaxSizeTextListener(self))
        sizeUnitLabel = JLabel("KB")

        generalOptionPanel = JPanel(GridBagLayout())
        generalOptionPanel.setBorder(
            BorderFactory.createTitledBorder("General Options"))
        gbc = GridBagConstraints()
        gbc.anchor = GridBagConstraints.WEST
        gbc.gridx = 0
        gbc.gridy = 0
        generalOptionPanel.add(maxSizeLabel, gbc)
        gbc.fill = GridBagConstraints.HORIZONTAL
        gbc.gridx = 1
        gbc.gridy = 0
        generalOptionPanel.add(self.maxSizeText, gbc)
        gbc.fill = GridBagConstraints.NONE
        gbc.gridx = 2
        gbc.gridy = 0
        gbc.weightx = 1.0
        generalOptionPanel.add(sizeUnitLabel, gbc)

        gbc = GridBagConstraints()
        gbc.fill = GridBagConstraints.BOTH
        gbc.gridx = 1
        gbc.gridy = 0
        gbc.gridheight = 2
        innerContainer.add(generalOptionPanel, gbc)

        # messageTabOptionPanel and it's inner component
        self.messageTabFormatCheckBoxs = []
        for f in supportedFormats:
            ckb = JCheckBox(f)
            ckb.addItemListener(self.messageTabFormatListener)
            self.messageTabFormatCheckBoxs.append(ckb)

        messageTabOptionPanel = JPanel()
        messageTabOptionPanel.setLayout(
            BoxLayout(messageTabOptionPanel, BoxLayout.Y_AXIS))
        messageTabOptionPanel.setBorder(
            BorderFactory.createTitledBorder("Enable in MessageEditorTab"))
        for b in self.messageTabFormatCheckBoxs:
            messageTabOptionPanel.add(b)

        gbc.gridx = 1
        gbc.gridy = 2
        gbc.gridheight = 9

        innerContainer.add(messageTabOptionPanel, gbc)

        # replaceResponsePanel and it's inner component
        self.chkEnableReplace = JCheckBox("Enable")
        self.chkEnableReplace.addItemListener(self.repalceResponseBoxListener)
        replaceResponseFormatLabel = JLabel("Format")
        self.replaceResponseFormatCheckBoxs = []
        for f in supportedFormats:
            ckb = JCheckBox(f)
            ckb.addItemListener(self.replaceResponseFormatListener)
            self.replaceResponseFormatCheckBoxs.append(ckb)
        replaceResponseIncludeLabel = JLabel(
            "Include URL that matches below(one item one line)")
        self.URLIncludeTextArea = JTextArea(6, 32)
        self.URLIncludeTextArea.addFocusListener(
            self.URLIncludeFocusListener(self))
        URLIncludeScrollPane = JScrollPane(self.URLIncludeTextArea)
        URLIncludeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        replaceResponseExcludeLabel = JLabel(
            "Exclude URL that matches below(one item one line)")
        self.URLExcludeTextArea = JTextArea(5, 32)
        self.URLExcludeTextArea.addFocusListener(
            self.URLExcludeFocusListener(self))
        URLExcludeScrollPane = JScrollPane(self.URLExcludeTextArea)
        URLExcludeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT)

        replaceResponsePanel = JPanel()
        replaceResponsePanel.setLayout(
            BoxLayout(replaceResponsePanel, BoxLayout.Y_AXIS))
        replaceResponsePanel.setBorder(
            BorderFactory.createTitledBorder("Replace PROXY Response"))
        replaceResponsePanel.add(self.chkEnableReplace)
        replaceResponsePanel.add(Box.createVerticalStrut(10))
        replaceResponsePanel.add(replaceResponseFormatLabel)
        for b in self.replaceResponseFormatCheckBoxs:
            replaceResponsePanel.add(b)
        replaceResponsePanel.add(Box.createVerticalStrut(10))
        replaceResponsePanel.add(replaceResponseIncludeLabel)
        replaceResponsePanel.add(URLIncludeScrollPane)
        replaceResponsePanel.add(Box.createVerticalStrut(10))
        replaceResponsePanel.add(replaceResponseExcludeLabel)
        replaceResponsePanel.add(URLExcludeScrollPane)

        gbc.gridy = 11
        innerContainer.add(replaceResponsePanel, gbc)

        # let innerContainer keep away from left and up
        gbc = GridBagConstraints()
        gbc.gridx = 1
        gbc.gridy = 1
        self.contentWrapper.add(Box.createHorizontalStrut(15), gbc)

        # gbc.ipadx = gbc.ipady = 25
        gbc.gridx = 2
        self.contentWrapper.add(innerContainer, gbc)

        # let innerContainer stay left side
        gbc = GridBagConstraints()
        gbc.gridx = 3
        gbc.gridy = 2
        gbc.gridwidth = 1
        gbc.weightx = gbc.weighty = 1
        paddingPanel = JPanel()
        self.contentWrapper.add(paddingPanel, gbc)

        self.setDefaultOptionDisplay()

    def disableReplaceResponseDisplay(self):
        for chb in self.replaceResponseFormatCheckBoxs:
            chb.setEnabled(False)
        self.URLIncludeTextArea.setEnabled(False)
        self.URLExcludeTextArea.setEnabled(False)

    def enableReplaceResponseDisplay(self):
        for chb in self.replaceResponseFormatCheckBoxs:
            chb.setEnabled(True)
        self.URLIncludeTextArea.setEnabled(True)
        self.URLExcludeTextArea.setEnabled(True)

    def setDefaultOptionDisplay(self):
        self.maxSizeText.setText(
            str(options.get("general").get("dataMaxSize") / 1024))

        for chb in self.messageTabFormatCheckBoxs:
            format = chb.getText()
            chb.setSelected(options.get("messageEditorTabFormat").get(format))

        self.chkEnableReplace.setSelected(
            options.get("replaceProxyResponse").get("enable"))
        for chb in self.replaceResponseFormatCheckBoxs:
            format = chb.getText()
            chb.setSelected(
                options.get("replaceProxyResponse").get("formats").get(format))

        self.URLIncludeTextArea.setText("\n".join(
            options.get("replaceProxyResponse").get("include", [])))
        self.URLExcludeTextArea.setText("\n".join(
            options.get("replaceProxyResponse").get("exclude", [])))

        if self.chkEnableReplace.isSelected():
            self.enableReplaceResponseDisplay()
        else:
            self.disableReplaceResponseDisplay()

    def saveOptions(self):
        if self._extender:
            self._extender._callbacks.saveExtensionSetting(
                "options", json.dumps(options))

    class RequestFocusListener(MouseAdapter):
        def __init__(self, beautifierOptionsPanel):
            super(BeautifierOptionsPanel.RequestFocusListener, self).__init__()
            self.beautifierOptionsPanel = beautifierOptionsPanel

        def mouseClicked(self, e):
            self.beautifierOptionsPanel.requestFocusInWindow()

    class MaxSizeTextListener(FocusListener):
        def __init__(self, beautifierOptionsPanel):
            super(BeautifierOptionsPanel.MaxSizeTextListener, self).__init__()
            self.beautifierOptionsPanel = beautifierOptionsPanel

        def focusGained(self, e):
            pass

        def focusLost(self, e):
            size = e.getSource().getText()
            try:
                size = int(float(size))
                options.get("general").update({"dataMaxSize": size * 1024})
                e.getSource().setText(str(size))
                self.beautifierOptionsPanel.saveOptions()
            except:
                e.getSource().setText(
                    str(options.get("general").get("dataMaxSize") / 1024))

    def messageTabFormatListener(self, e):
        format = e.getSource().getText()
        if e.getStateChange() == ItemEvent.SELECTED:
            options.get("messageEditorTabFormat").update({format: True})
        else:
            options.get("messageEditorTabFormat").update({format: False})
        self.saveOptions()

    def repalceResponseBoxListener(self, e):
        if e.getStateChange() == ItemEvent.SELECTED:
            options.get("replaceProxyResponse").update({"enable": True})
            self.enableReplaceResponseDisplay()
        else:
            options.get("replaceProxyResponse").update({"enable": False})
            self.disableReplaceResponseDisplay()
        self.saveOptions()

    def replaceResponseFormatListener(self, e):
        format = e.getSource().getText()
        if e.getStateChange() == ItemEvent.SELECTED:
            options.get("replaceProxyResponse").get("formats").update(
                {format: True})
        else:
            options.get("replaceProxyResponse").get("formats").update(
                {format: False})
        self.saveOptions()

    class URLIncludeFocusListener(FocusListener):
        def __init__(self, beautifierOptionsPanel):
            super(BeautifierOptionsPanel.URLIncludeFocusListener,
                  self).__init__()
            self.beautifierOptionsPanel = beautifierOptionsPanel

        def focusGained(self, e):
            pass

        def focusLost(self, e):
            text = e.getSource().getText()  # <unicode>
            urlPatterns = [
                p.strip() for p in text.split("\n") if p.strip() != ""
            ]
            options.get("replaceProxyResponse").update(
                {"include": urlPatterns})
            self.beautifierOptionsPanel.saveOptions()

    class URLExcludeFocusListener(FocusListener):
        def __init__(self, beautifierOptionsPanel):
            super(BeautifierOptionsPanel.URLExcludeFocusListener,
                  self).__init__()
            self.beautifierOptionsPanel = beautifierOptionsPanel

        def focusGained(self, e):
            pass

        def focusLost(self, e):
            text = e.getSource().getText()  # <unicode>
            urlPatterns = [
                p.strip() for p in text.split("\n") if p.strip() != ""
            ]
            options.get("replaceProxyResponse").update(
                {"exclude": urlPatterns})
            self.beautifierOptionsPanel.saveOptions()
Пример #12
0
    def __init__(self, parent, title, app):
        from javax.swing import JCheckBox, JRadioButton, ButtonGroup
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.getContentPane().setLayout(BorderLayout(0, 5))
        self.tabbedPane = JTabbedPane()

        #1 Tab: general
        panel1 = JPanel()
        panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS))

        #Checkbutton to enable/disable update check when script starts
        self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn"))
        self.updateCBtn.setToolTipText(
            self.app.strings.getString("updateCBtn_tooltip"))

        #Download tools
        downloadBtn = JButton(self.app.strings.getString("updatesBtn"),
                              ImageProvider.get("dialogs", "refresh"),
                              actionPerformed=self.on_downloadBtn_clicked)
        downloadBtn.setToolTipText(
            self.app.strings.getString("updatesBtn_tooltip"))

        #Checkbuttons for enabling/disabling tools
        toolsPanel = JPanel(BorderLayout(0, 5))
        title = self.app.strings.getString("enable_disable_tools")
        toolsPanel.setBorder(BorderFactory.createTitledBorder(title))
        infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning"))
        infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC))
        toolsPanel.add(infoLbl, BorderLayout.PAGE_START)

        toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0))
        self.toolsCBtns = []
        for tool in self.app.realTools:
            toolCBtn = JCheckBox()
            toolCBtn.addItemListener(self)
            toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT)
            self.toolsCBtns.append(toolCBtn)

            toolPane = JPanel()
            toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS))
            toolPane.add(toolCBtn)
            toolPane.add(toolLbl)
            toolsStatusPane.add(toolPane)
        toolsPanel.add(toolsStatusPane, BorderLayout.CENTER)

        #Radiobuttons for enabling/disabling layers when a new one
        #is added
        layersPanel = JPanel(GridLayout(0, 1))
        title = self.app.strings.getString("errors_layers_manager")
        layersPanel.setBorder(BorderFactory.createTitledBorder(title))
        errorLayersLbl = JLabel(
            self.app.strings.getString("errors_layers_info"))
        errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(
            Font.ITALIC))
        layersPanel.add(errorLayersLbl)
        self.layersRBtns = {}
        group = ButtonGroup()
        for mode in self.app.layersModes:
            layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode))
            group.add(layerRBtn)
            layersPanel.add(layerRBtn)
            self.layersRBtns[mode] = layerRBtn

        #Max number of errors text field
        self.maxErrorsNumberTextField = JTextField()
        self.maxErrorsNumberTextField.setToolTipText(
            self.app.strings.getString("maxErrorsNumberTextField_tooltip"))
        self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder(
        )
        self.maxErrorsNumberTextField.getDocument().addDocumentListener(
            ErrNumTextListener(self))

        #layout
        self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(self.updateCBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(downloadBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(toolsPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(layersPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        maxErrP = JPanel(BorderLayout(5, 0))
        maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")),
                    BorderLayout.LINE_START)
        maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER)
        p = JPanel(BorderLayout())
        p.add(maxErrP, BorderLayout.PAGE_START)
        p.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None,
                               panel1, None)

        #2 Tab: favourite zones
        panel2 = JPanel(BorderLayout(5, 15))
        panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))

        #status
        topPanel = JPanel()
        topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
        infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info"))
        infoPanel.getEditorPane().addHyperlinkListener(self)
        infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.favZoneStatusCBtn = JCheckBox(
            self.app.strings.getString("activate_fav_area"),
            actionListener=self)
        self.favZoneStatusCBtn.setToolTipText(
            self.app.strings.getString("activate_fav_area_tooltip"))
        self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        topPanel.add(infoPanel)
        topPanel.add(Box.createRigidArea(Dimension(0, 10)))
        topPanel.add(self.favZoneStatusCBtn)
        #table
        self.zonesTable = JTable()
        tableSelectionModel = self.zonesTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ZonesTableListener(self))
        columns = [
            "",
            self.app.strings.getString("Type"),
            self.app.strings.getString("Name")
        ]
        tableModel = ZonesTableModel([], columns)
        self.zonesTable.setModel(tableModel)
        self.scrollPane = JScrollPane(self.zonesTable)
        #map
        self.zonesMap = JMapViewer()
        self.zonesMap.setZoomContolsVisible(False)
        self.zonesMap.setMinimumSize(Dimension(100, 200))

        #buttons
        self.removeBtn = JButton(self.app.strings.getString("Remove"),
                                 ImageProvider.get("dialogs", "delete"),
                                 actionPerformed=self.on_removeBtn_clicked)
        self.removeBtn.setToolTipText(
            self.app.strings.getString("remove_tooltip"))
        newBtn = JButton(self.app.strings.getString("New"),
                         ImageProvider.get("dialogs", "add"),
                         actionPerformed=self.on_newBtn_clicked)
        newBtn.setToolTipText(self.app.strings.getString("new_tooltip"))

        #layout
        panel2.add(topPanel, BorderLayout.PAGE_START)
        panel2.add(self.scrollPane, BorderLayout.LINE_START)
        panel2.add(self.zonesMap, BorderLayout.CENTER)
        self.buttonsPanel = JPanel()
        self.buttonsPanel.add(self.removeBtn)
        self.buttonsPanel.add(newBtn)
        panel2.add(self.buttonsPanel, BorderLayout.PAGE_END)

        self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None,
                               panel2, None)

        #3 Tab Tools options
        panel3 = JPanel()
        panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS))
        panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        for tool in self.app.realTools:
            if hasattr(tool, 'prefs'):
                p = JPanel(FlowLayout(FlowLayout.LEFT))
                p.setBorder(BorderFactory.createTitledBorder(tool.title))
                p.add(tool.prefsGui)
                panel3.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None,
                               panel3, None)

        self.add(self.tabbedPane, BorderLayout.CENTER)

        exitPanel = JPanel()
        saveBtn = JButton(self.app.strings.getString("OK"),
                          ImageProvider.get("ok"),
                          actionPerformed=self.on_saveBtn_clicked)
        cancelBtn = JButton(self.app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=self.on_cancelBtn_clicked)
        saveBtn.setToolTipText(self.app.strings.getString("save_preferences"))
        saveBtn.setAlignmentX(0.5)
        exitPanel.add(saveBtn)
        exitPanel.add(cancelBtn)
        self.add(exitPanel, BorderLayout.PAGE_END)

        self.addWindowListener(self)
        self.pack()
Пример #13
0
    def __init__(self, parent, title, app):
        from javax.swing import JCheckBox, JRadioButton, ButtonGroup
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.getContentPane().setLayout(BorderLayout(0, 5))
        self.tabbedPane = JTabbedPane()

        #1 Tab: general
        panel1 = JPanel()
        panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS))

        #Checkbutton to enable/disable update check when script starts
        self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn"))
        self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip"))

        #Download tools
        downloadBtn = JButton(self.app.strings.getString("updatesBtn"),
                              ImageProvider.get("dialogs", "refresh"),
                              actionPerformed=self.on_downloadBtn_clicked)
        downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip"))

        #Checkbuttons for enabling/disabling tools
        toolsPanel = JPanel(BorderLayout(0, 5))
        title = self.app.strings.getString("enable_disable_tools")
        toolsPanel.setBorder(BorderFactory.createTitledBorder(title))
        infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning"))
        infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC))
        toolsPanel.add(infoLbl, BorderLayout.PAGE_START)

        toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0))
        self.toolsCBtns = []
        for tool in self.app.realTools:
            toolCBtn = JCheckBox()
            toolCBtn.addItemListener(self)
            toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT)
            self.toolsCBtns.append(toolCBtn)

            toolPane = JPanel()
            toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS))
            toolPane.add(toolCBtn)
            toolPane.add(toolLbl)
            toolsStatusPane.add(toolPane)
        toolsPanel.add(toolsStatusPane, BorderLayout.CENTER)

        #Radiobuttons for enabling/disabling layers when a new one
        #is added
        layersPanel = JPanel(GridLayout(0, 1))
        title = self.app.strings.getString("errors_layers_manager")
        layersPanel.setBorder(BorderFactory.createTitledBorder(title))
        errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info"))
        errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC))
        layersPanel.add(errorLayersLbl)
        self.layersRBtns = {}
        group = ButtonGroup()
        for mode in self.app.layersModes:
            layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode))
            group.add(layerRBtn)
            layersPanel.add(layerRBtn)
            self.layersRBtns[mode] = layerRBtn

        #Max number of errors text field
        self.maxErrorsNumberTextField = JTextField()
        self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip"))
        self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder()
        self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self))

        #layout
        self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(self.updateCBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(downloadBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(toolsPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(layersPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        maxErrP = JPanel(BorderLayout(5, 0))
        maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START)
        maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER)
        p = JPanel(BorderLayout())
        p.add(maxErrP, BorderLayout.PAGE_START)
        p.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"),
                          None,
                          panel1,
                          None)

        #2 Tab: favourite zones
        panel2 = JPanel(BorderLayout(5, 15))
        panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))

        #status
        topPanel = JPanel()
        topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
        infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info"))
        infoPanel.getEditorPane().addHyperlinkListener(self)
        infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"),
                                           actionListener=self)
        self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip"))
        self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        topPanel.add(infoPanel)
        topPanel.add(Box.createRigidArea(Dimension(0, 10)))
        topPanel.add(self.favZoneStatusCBtn)
        #table
        self.zonesTable = JTable()
        tableSelectionModel = self.zonesTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ZonesTableListener(self))
        columns = ["",
                   self.app.strings.getString("Type"),
                   self.app.strings.getString("Name")]
        tableModel = ZonesTableModel([], columns)
        self.zonesTable.setModel(tableModel)
        self.scrollPane = JScrollPane(self.zonesTable)
        #map
        self.zonesMap = JMapViewer()
        self.zonesMap.setZoomContolsVisible(False)
        self.zonesMap.setMinimumSize(Dimension(100, 200))

        #buttons
        self.removeBtn = JButton(self.app.strings.getString("Remove"),
                            ImageProvider.get("dialogs", "delete"),
                            actionPerformed=self.on_removeBtn_clicked)
        self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip"))
        newBtn = JButton(self.app.strings.getString("New"),
                         ImageProvider.get("dialogs", "add"),
                         actionPerformed=self.on_newBtn_clicked)
        newBtn.setToolTipText(self.app.strings.getString("new_tooltip"))

        #layout
        panel2.add(topPanel, BorderLayout.PAGE_START)
        panel2.add(self.scrollPane, BorderLayout.LINE_START)
        panel2.add(self.zonesMap, BorderLayout.CENTER)
        self.buttonsPanel = JPanel()
        self.buttonsPanel.add(self.removeBtn)
        self.buttonsPanel.add(newBtn)
        panel2.add(self.buttonsPanel, BorderLayout.PAGE_END)

        self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"),
                          None,
                          panel2,
                          None)

        #3 Tab Tools options
        panel3 = JPanel()
        panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS))
        panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        for tool in self.app.realTools:
            if hasattr(tool, 'prefs'):
                p = JPanel(FlowLayout(FlowLayout.LEFT))
                p.setBorder(BorderFactory.createTitledBorder(tool.title))
                p.add(tool.prefsGui)
                panel3.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"),
                          None,
                          panel3,
                          None)

        self.add(self.tabbedPane, BorderLayout.CENTER)

        exitPanel = JPanel()
        saveBtn = JButton(self.app.strings.getString("OK"),
                          ImageProvider.get("ok"),
                          actionPerformed=self.on_saveBtn_clicked)
        cancelBtn = JButton(self.app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=self.on_cancelBtn_clicked)
        saveBtn.setToolTipText(self.app.strings.getString("save_preferences"))
        saveBtn.setAlignmentX(0.5)
        exitPanel.add(saveBtn)
        exitPanel.add(cancelBtn)
        self.add(exitPanel, BorderLayout.PAGE_END)

        self.addWindowListener(self)
        self.pack()