Пример #1
0
class cbRenderer(DefaultTableCellRenderer):

    #---------------------------------------------------------------------------
    # Name: __init__()
    # Role: Constructor
    #---------------------------------------------------------------------------
    def __init__(self):
        DefaultTableCellRenderer.__init__(self)
        self.comboBox = JComboBox(choices)

    #---------------------------------------------------------------------------
    # Name: getTableCellRendererComponent()
    # Role: Return the component containing the rendered value
    # Note: Called frequently, don't create a new component each time
    #---------------------------------------------------------------------------
    def getTableCellRendererComponent(
            self,
            table,  # JTable  - table for which cell is being rendered
            value,  # Object  - value being rendered
            isSelected,  # boolean - Is value selected?
            hasFocus,  # boolean - Does this cell have focus?
            rowIndex,  # int     - Row # (0..N)
            vColIndex  # int     - Col # (0..N)
    ):
        self.comboBox.setSelectedItem(value)
        return self.comboBox
Пример #2
0
class EditSymbolAttr(JPanel):
    def __init__(self, sattr):
	self.attr = sattr
	self.cbox = JColorChooser(self.attr.color)
	self.sz_field = JTextField(str(self.attr.size))
	szpanel = JPanel()
	szpanel.add(self.sz_field)
	szpanel.setBorder(BorderFactory.createTitledBorder("symbol size (integer)"))
	self.filled_box = JCheckBox("Filled ?:",self.attr.filled)
	self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys())
	self.shape_cbox.setSelectedItem(self.attr.shape)
	self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape"))
	panel1 = JPanel()
	panel1.setLayout(BorderLayout())
	panel1.add(szpanel,BorderLayout.NORTH)
	panel2 = JPanel()
	panel2.setLayout(GridLayout(1,2))
	panel2.add(self.shape_cbox)
	panel2.add(self.filled_box)
	panel1.add(panel2,BorderLayout.SOUTH)
	self.setLayout(BorderLayout())
	self.add(self.cbox,BorderLayout.CENTER)
	self.add(panel1,BorderLayout.SOUTH)
    def setAttribute(self,sattr):
	self.attr = sattr
	self.cbox.color = self.attr.color
	self.sz_field.text = str(self.attr.size)
	self.shape_cbox.setSelectedItem(self.attr.shape)
    def update(self):
	self.attr.color = self.cbox.getColor()
	self.attr.size = string.atoi(self.sz_field.getText())
	self.attr.filled = self.filled_box.isSelected()
	self.attr.shape = self.shape_cbox.getSelectedItem()
	self.attr.sym = self.attr.createSymbol()
Пример #3
0
    def update_table(self):
        """Updates the table with new data"""

        columns = ["Type", "Action", "Name", "Value"]
        data = []
        for param in self._extender.sm.selected_session.params:
            data.append(param.as_table_row())

        data.append([
            Parameter.type_mapping[Parameter.PARAM_COOKIE],
            Parameter.ACTION_MODIFY, "", ""
        ])
        data_model = DefaultTableModel(data,
                                       columns,
                                       tableChanged=self.tableChanged)
        self.modification_table.setModel(data_model)

        # type combobox
        type_combo = JComboBox(self._types)
        type_column = self.modification_table.getColumnModel().getColumn(0)
        type_column.setCellEditor(DefaultCellEditor(type_combo))
        type_column.setMaxWidth(75)

        # action combobox
        action_combo = JComboBox(self._actions)
        action_column = self.modification_table.getColumnModel().getColumn(1)
        action_column.setCellEditor(DefaultCellEditor(action_combo))
        action_column.setMaxWidth(75)
        action_combo.setSelectedItem("replace")
Пример #4
0
class EditCurveAttr(JPanel):
    def __init__(self, cattr):
        self.attr = cattr
        self.cbox = JColorChooser(self.attr.color)
        self.sym_panel = EditSymbolAttr(cattr.sym_prop)
        self.thickness_field = JTextField(str(cattr.thickness), 2)
        self.draw_symbol_box = JCheckBox("Draw Symbol?", cattr.draw_symbol)
        self.dps_field = JTextField(str(self.attr.data_per_symbol), 2)
        self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys())
        self.dash_box.setSelectedItem(self.attr.dash_type)
        self.dash_box.setBorder(
            BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)"))
        tpanelx = JPanel()
        tpanelx.add(self.thickness_field)
        tpanelx.setBorder(
            BorderFactory.createTitledBorder("curve thickness (integer)"))
        tpanely = JPanel()
        tpanely.add(self.dps_field)
        tpanely.setBorder(
            BorderFactory.createTitledBorder("data per symbol(integer)"))
        tpanel = JPanel()
        tpanel.setLayout(GridLayout(2, 2))
        tpanel.add(self.draw_symbol_box)
        tpanel.add(tpanelx)
        tpanel.add(tpanely)
        tpanel.add(self.dash_box)
        panel1 = JPanel()
        panel1.setLayout(BorderLayout())
        panel1.add(self.cbox, BorderLayout.CENTER)
        panel1.add(tpanel, BorderLayout.SOUTH)
        panel2 = JPanel()
        panel2.setLayout(BorderLayout())
        panel2.add(self.sym_panel, BorderLayout.CENTER)
        tp1 = JTabbedPane()
        tp1.addTab("Curve Attributes", panel1)
        tp1.addTab("Symbol Attributes", panel2)
        tp1.setSelectedComponent(panel1)
        self.setLayout(BorderLayout())
        self.add(tp1, BorderLayout.CENTER)

    def setAttribute(self, cattr):
        self.attr = cattr
        self.cbox.color = self.attr.color
        self.sym_panel.setAttribute(cattr.sym_prop)
        self.thickness_field.text = str(cattr.thickness)
        self.dps_field.text = str(cattr.data_per_symbol)
        self.draw_symbol_box.setSelected(cattr.draw_symbol)
        self.dash_box.setSelectedItem(cattr.dash_type)

    def update(self):
        self.attr.color = self.cbox.getColor()
        self.attr.thickness = string.atoi(self.thickness_field.text)
        self.attr.data_per_symbol = string.atoi(self.dps_field.text)
        self.attr.draw_symbol = self.draw_symbol_box.isSelected()
        self.attr.dash_type = self.dash_box.getSelectedItem()
        #print 'Updating Self.draw_symbol',self.draw_symbol,self.attr
        self.sym_panel.update()
Пример #5
0
 def build_combobox(self, choices, default):
     '''
     Generic method to construct a combobox. choices should be an iterable
     of strings of the choices to be made and default should be a string
     which is equal to one of the values within the iterable.
     '''
     combo = JComboBox()
     for choice in choices:
         combo.addItem(choice)
     combo.setSelectedItem(default)
     return combo
Пример #6
0
 def build_combobox(self, choices, default):
     '''
     Generic method to construct a combobox. choices should be an iterable
     of strings of the choices to be made and default should be a string
     which is equal to one of the values within the iterable.
     '''
     combo = JComboBox()
     for choice in choices:
         combo.addItem(choice)
     combo.setSelectedItem(default)
     return combo
Пример #7
0
def makeLanguageSelectionComboBox(obj, value):
        modelsDir = os.path.dirname(os.path.realpath(__file__)) + "/models/"
        languages = []
        for root, _, _ in os.walk(modelsDir):
            if root != modelsDir:
                languages.append(os.path.split(root)[1])
        obj.add(JLabel("Language: "))
        combo = JComboBox(languages)
        combo.setSelectedItem(value)
        obj.add(combo)
        return combo
Пример #8
0
    def buildAddEditPrompt(self,
                           typeValue=None,
                           searchValue=None,
                           replacementValue=None):
        """
        Builds the replacement rules add/edit prompt.

        Args:
            typeValue: the value that will be set on the type JLabel.
            searchValue: the value that will be set on the search JLabel.
            replacementValue: the value that will be set on the replacement JLabel.

        Return:
            tuple: (type, search, replacement) as input by user.
        """
        panel = Box.createVerticalBox()

        typeLabel = JLabel("Replacement type")
        type = JComboBox([REPLACE_HEADER_NAME])
        searchLabel = JLabel("Header Name / Search String")
        search = JTextField()
        replaceLabel = JLabel("Replacement Value")
        replacement = JTextField()

        panel.add(typeLabel)
        panel.add(type)
        panel.add(searchLabel)
        panel.add(search)
        panel.add(replaceLabel)
        panel.add(replacement)

        if typeValue:
            type.setSelectedItem(typeValue)

        if searchValue:
            search.text = searchValue

        if replacementValue:
            replacement.text = replacementValue

        title = "Add Replacement Rule" if type == None else "Edit Replacement Rule"

        result = JOptionPane.showConfirmDialog(None, panel,
                                               "Add Replacement Rule",
                                               JOptionPane.PLAIN_MESSAGE)

        if result == JOptionPane.OK_OPTION:
            if search.text.strip() == "":
                self.messageDialog("Header name must be non-blank.")
                raise InvalidInputException()
            else:
                return type.selectedItem, search.text, replacement.text
        else:
            raise InvalidInputException()
Пример #9
0
 def build_servers_combobox(self):
     combo = JComboBox()
     # Go through list of servers and add to combo box.
     for server in self.servers.keys():
         if server != "default":
             combo_item = "{}: {}:{}".format(server,
                                             self.servers[server]['url'],
                                             self.servers[server]['port'])
             combo.addItem(combo_item)
             # If this item is the default one, set it as selected
             if server == self.servers['default']:
                 combo.setSelectedItem(combo_item)
     return combo
Пример #10
0
 def build_servers_combobox(self):
     combo = JComboBox()
     # Go through list of servers and add to combo box.
     for server in self.servers.keys():
         if server != "default":
             combo_item = "{}: {}:{}".format(server,
                                             self.servers[server]['url'],
                                             self.servers[server]['port'])
             combo.addItem(combo_item)
             # If this item is the default one, set it as selected
             if server == self.servers['default']:
                 combo.setSelectedItem(combo_item)
     return combo
Пример #11
0
class CurveDialog(JDialog):
    def __init__(self, cattrs):
        #JDialog.__init__(self,"Curve Attribute Editor")
        #("Curve Attribute Editor")
        if cattrs == None or len(cattrs) == 0:
            raise "No curve attributes specified"
        self.attrs = cattrs
        self.cpanel = EditCurveAttr(cattrs[0])
        pane = self.getContentPane()
        pane.setLayout(BorderLayout())
        x = map(lambda x: x + 1, range(len(self.attrs)))
        self.curveBox = JComboBox(x)
        self.curveBox.setBorder(BorderFactory.createTitledBorder("Curve #"))
        self.curveBox.setSelectedItem(0)

        class CListener(ItemListener):
            def __init__(self, cbox, cpanel, cattrs):
                self.cbox = cbox
                self.cpanel = cpanel
                self.attrs = cattrs

            def itemStateChanged(self, evt):
                crvNo = self.cbox.getSelectedItem()
                self.cpanel.update()
                self.cpanel.setAttribute(self.attrs[crvNo - 1])

        self.curveBox.addItemListener(
            CListener(self.curveBox, self.cpanel, self.attrs))
        okBtn = JButton("OK", actionPerformed=self.ok_action)
        cancelBtn = JButton("Cancel", actionPerformed=self.cancel_action)
        btnPanel = JPanel()
        btnPanel.setLayout(GridLayout(1, 3))
        btnPanel.add(self.curveBox)
        btnPanel.add(okBtn)
        btnPanel.add(cancelBtn)
        pane.add(self.cpanel, BorderLayout.CENTER)
        pane.add(btnPanel, BorderLayout.SOUTH)
        self.setLocation(100, 100)
        self.pack()
        self.setVisible(1)

    def ok_action(self, evt):
        #crvNo = self.curveBox.getSelectedItem()
        #print 'Setting attributes for ', crvNo
        #print self.attrs[crvNo-1]
        self.cpanel.update()
        self.cancel_action(evt)

    def cancel_action(self, evt):
        self.dispose()
Пример #12
0
class EditCurveAttr(JPanel):
    def __init__(self, cattr):
	self.attr = cattr
	self.cbox = JColorChooser(self.attr.color)
	self.sym_panel = EditSymbolAttr(cattr.sym_prop)
	self.thickness_field = JTextField(str(cattr.thickness),2)
	self.draw_symbol_box = JCheckBox("Draw Symbol?",cattr.draw_symbol)
	self.dps_field = JTextField(str(self.attr.data_per_symbol),2)
	self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys())
	self.dash_box.setSelectedItem(self.attr.dash_type)
	self.dash_box.setBorder(BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)"))
	tpanelx = JPanel()
	tpanelx.add(self.thickness_field)
	tpanelx.setBorder(BorderFactory.createTitledBorder("curve thickness (integer)"))
	tpanely = JPanel()
	tpanely.add(self.dps_field)
	tpanely.setBorder(BorderFactory.createTitledBorder("data per symbol(integer)"))
	tpanel = JPanel();tpanel.setLayout(GridLayout(2,2));
	tpanel.add(self.draw_symbol_box); tpanel.add(tpanelx);
	tpanel.add(tpanely); tpanel.add(self.dash_box);
	panel1 = JPanel()
	panel1.setLayout(BorderLayout())
	panel1.add(self.cbox,BorderLayout.CENTER)
	panel1.add(tpanel, BorderLayout.SOUTH)
	panel2 = JPanel()
	panel2.setLayout(BorderLayout())
	panel2.add(self.sym_panel,BorderLayout.CENTER)
	tp1 = JTabbedPane()
	tp1.addTab("Curve Attributes",panel1)
	tp1.addTab("Symbol Attributes",panel2)
	tp1.setSelectedComponent(panel1)
	self.setLayout(BorderLayout())
	self.add(tp1,BorderLayout.CENTER)
    def setAttribute(self,cattr):
	self.attr = cattr
	self.cbox.color = self.attr.color
	self.sym_panel.setAttribute(cattr.sym_prop)
	self.thickness_field.text = str(cattr.thickness)
	self.dps_field.text = str(cattr.data_per_symbol)
	self.draw_symbol_box.setSelected(cattr.draw_symbol)
	self.dash_box.setSelectedItem(cattr.dash_type)
    def update(self):
	self.attr.color = self.cbox.getColor()
	self.attr.thickness = string.atoi(self.thickness_field.text)
	self.attr.data_per_symbol = string.atoi(self.dps_field.text)
	self.attr.draw_symbol = self.draw_symbol_box.isSelected()
	self.attr.dash_type = self.dash_box.getSelectedItem()
	#print 'Updating Self.draw_symbol',self.draw_symbol,self.attr
	self.sym_panel.update()
Пример #13
0
    def initParameterColumn(self, table):
        parameterTypes = JComboBox(sorted(PARAMETER_TYPES.keys()))
        parameterTypes.setSelectedItem('PARAM_BODY')
        parameterColumn = table.getColumnModel().getColumn(0)
        parameterColumn.setCellEditor(DefaultCellEditor(parameterTypes))

        whenTypes = JComboBox(['Before', 'After'])
        whenTypes.setSelectedItem('Before')
        whenColumn = table.getColumnModel().getColumn(2)
        whenColumn.setCellEditor(DefaultCellEditor(whenTypes))

        ruleTypes = JComboBox(sorted(RULES.keys()))
        ruleColumn = table.getColumnModel().getColumn(3)
        ruleColumn.setCellEditor(DefaultCellEditor(ruleTypes))
        return
Пример #14
0
    def initParameterColumn(self, table):
        parameterTypes = JComboBox(sorted(PARAMETER_TYPES.keys()))
        parameterTypes.setSelectedItem('PARAM_BODY')
        parameterColumn = table.getColumnModel().getColumn(0)
        parameterColumn.setCellEditor(DefaultCellEditor(parameterTypes))

        whenTypes = JComboBox(['Before', 'After'])
        whenTypes.setSelectedItem('Before')
        whenColumn = table.getColumnModel().getColumn(2)
        whenColumn.setCellEditor(DefaultCellEditor(whenTypes))

        ruleTypes = JComboBox(sorted(RULES.keys()))
        ruleColumn = table.getColumnModel().getColumn(3)
        ruleColumn.setCellEditor(DefaultCellEditor(ruleTypes))
        return
Пример #15
0
class CurveDialog(JDialog):
    def __init__(self, cattrs):
	#JDialog.__init__(self,"Curve Attribute Editor")
	#("Curve Attribute Editor")
	if cattrs == None or len(cattrs) == 0:
	    raise "No curve attributes specified"
	self.attrs = cattrs
	self.cpanel = EditCurveAttr(cattrs[0])
	pane = self.getContentPane()
	pane.setLayout(BorderLayout())
	x = map(lambda x: x+1,range(len(self.attrs)))
	self.curveBox = JComboBox(x)
	self.curveBox.setBorder(BorderFactory.createTitledBorder("Curve #"))
	self.curveBox.setSelectedItem(0)
	class CListener(ItemListener):
	    def __init__(self,cbox,cpanel,cattrs):
		self.cbox = cbox
		self.cpanel = cpanel
		self.attrs = cattrs
	    def itemStateChanged(self, evt):
		crvNo = self.cbox.getSelectedItem()
		self.cpanel.update()
		self.cpanel.setAttribute(self.attrs[crvNo-1])
	self.curveBox.addItemListener(CListener(self.curveBox, self.cpanel,self.attrs))
	okBtn = JButton("OK",actionPerformed=self.ok_action)
	cancelBtn = JButton("Cancel",actionPerformed=self.cancel_action)
	btnPanel = JPanel()
	btnPanel.setLayout(GridLayout(1,3))
	btnPanel.add(self.curveBox)
	btnPanel.add(okBtn)
	btnPanel.add(cancelBtn)
	pane.add(self.cpanel,BorderLayout.CENTER)
	pane.add(btnPanel, BorderLayout.SOUTH)
	self.setLocation(100,100)
	self.pack()
	self.setVisible(1)
    def ok_action(self,evt):
	#crvNo = self.curveBox.getSelectedItem()
	#print 'Setting attributes for ', crvNo
	#print self.attrs[crvNo-1]
	self.cpanel.update()
	self.cancel_action(evt)
    def cancel_action(self,evt):
	self.dispose()
Пример #16
0
class EditSymbolAttr(JPanel):
    def __init__(self, sattr):
        self.attr = sattr
        self.cbox = JColorChooser(self.attr.color)
        self.sz_field = JTextField(str(self.attr.size))
        szpanel = JPanel()
        szpanel.add(self.sz_field)
        szpanel.setBorder(
            BorderFactory.createTitledBorder("symbol size (integer)"))
        self.filled_box = JCheckBox("Filled ?:", self.attr.filled)
        self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys())
        self.shape_cbox.setSelectedItem(self.attr.shape)
        self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape"))
        panel1 = JPanel()
        panel1.setLayout(BorderLayout())
        panel1.add(szpanel, BorderLayout.NORTH)
        panel2 = JPanel()
        panel2.setLayout(GridLayout(1, 2))
        panel2.add(self.shape_cbox)
        panel2.add(self.filled_box)
        panel1.add(panel2, BorderLayout.SOUTH)
        self.setLayout(BorderLayout())
        self.add(self.cbox, BorderLayout.CENTER)
        self.add(panel1, BorderLayout.SOUTH)

    def setAttribute(self, sattr):
        self.attr = sattr
        self.cbox.color = self.attr.color
        self.sz_field.text = str(self.attr.size)
        self.shape_cbox.setSelectedItem(self.attr.shape)

    def update(self):
        self.attr.color = self.cbox.getColor()
        self.attr.size = string.atoi(self.sz_field.getText())
        self.attr.filled = self.filled_box.isSelected()
        self.attr.shape = self.shape_cbox.getSelectedItem()
        self.attr.sym = self.attr.createSymbol()
Пример #17
0
    def update_table(self):
        """Updates the table with new data"""

        columns = ["Type", "Action", "Name", "Value"]
        data = []
        for param in self._extender.sm.selected_session.params:
            data.append(param.as_table_row())

        data.append([Parameter.type_mapping[Parameter.PARAM_COOKIE], Parameter.ACTION_MODIFY, "", ""])
        data_model = DefaultTableModel(data, columns, tableChanged=self.tableChanged)
        self.modification_table.setModel(data_model)

        # type combobox
        type_combo = JComboBox(self._types)
        type_column = self.modification_table.getColumnModel().getColumn(0)
        type_column.setCellEditor(DefaultCellEditor(type_combo))
        type_column.setMaxWidth(75)

        # action combobox
        action_combo = JComboBox(self._actions)
        action_column = self.modification_table.getColumnModel().getColumn(1)
        action_column.setCellEditor(DefaultCellEditor(action_combo))
        action_column.setMaxWidth(75)
        action_combo.setSelectedItem("replace")
Пример #18
0
class NewAccountGUI:
    def __init__(self, amgui):
        self.amgui = amgui
        self.am = amgui.acctmanager
        self.buildgwinfo()
        self.autologin = JCheckBox("Automatically Log In")
        self.acctname = JTextField()
        self.gwoptions = JPanel(doublebuffered)
        self.gwoptions.border = TitledBorder("Gateway Options")
        self.buildgwoptions("Twisted")
        self.mainframe = JFrame("New Account Window")
        self.buildpane()

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

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

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

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

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

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

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

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

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

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

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

    def cancel(self, ae):
        print "Cancelling new account creation"
        self.mainframe.dispose()
Пример #19
0
    def __init__(self):
        self.setLayout(GridBagLayout())
        self.setBorder(make_title_border("API"))
        self.setAlignmentX(JPanel.LEFT_ALIGNMENT)

        self.status = StatusText(25)
        self.add(JLabel("Status :"), gridx=0)
        self.add(self.status, gridx=1)

        self.version = StatusText(25)
        self.version.set(context.version, bg=Color.GRAY)
        self.add(JLabel("Version :"), gridx=0)
        self.add(self.version, gridx=1)

        settings = context.settings

        txt_url = JTextField(25)
        txt_url.setText(settings.load("apiurl", "https://api.yeswehack.com/"))
        self.add(JLabel("API URL :"), gridx=0)
        self.add(txt_url, gridx=1)

        combo_auth = JComboBox((AuthMethod.anonymous, AuthMethod.email_pass))
        combo_auth.setSelectedItem(
            settings.load("auth_method", AuthMethod.anonymous))
        combo_auth.addActionListener(
            CallbackActionListener(self.auth_method_changed))

        self.add(JLabel("Authentication :"), gridx=0)
        self.add(combo_auth, gridx=1)

        txt_mail = JTextField(25)
        txt_mail.setText(settings.load("email"))
        self.add(JLabel("Email :"), gridx=0)
        self.add(txt_mail, gridx=1)

        txt_pass = JPasswordField(25)
        txt_pass.setText(settings.load("password"))
        self.add(JLabel("Password :"******"remember", True))
        self.add(JLabel("Remember password :"******"Connect")
        btn_connect.addActionListener(CallbackActionListener(self.submit))
        self.add(btn_connect, gridx=1, anchor=EAST)

        self.inputs = {
            "apiurl": txt_url,
            "auth_method": combo_auth,
            "email": txt_mail,
            "password": txt_pass,
            "remember": check_remember,
            "connect": btn_connect,
        }

        self.setMaximumSize(self.getPreferredSize())

        self.auth_method_changed()
        async_call(self.update_status)
Пример #20
0
class ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener):
    """ generated source for class ConfigurableConfigPanel """
    serialVersionUID = 1L
    associatedFile = File()
    associatedFileField = JTextField()
    params = JSONObject()
    savedParams = str()
    loadButton = JButton()
    saveAsButton = JButton()
    saveButton = JButton()
    name = JTextField()
    strategy = JComboBox()
    metagameStrategy = JComboBox()
    stateMachine = JComboBox()
    cacheStateMachine = JCheckBox()
    maxPlys = JSpinner()
    heuristicFocus = JSpinner()
    heuristicMobility = JSpinner()
    heuristicOpponentFocus = JSpinner()
    heuristicOpponentMobility = JSpinner()
    mcDecayRate = JSpinner()
    rightPanel = JPanel()

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

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

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

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

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

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

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

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

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

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

    settingUI = False

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

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

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

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

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

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

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

        def getDescription(self):
            """ generated source for method getDescription """
            return "GGP Players (*.player)"
Пример #21
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

    def registerExtenderCallbacks(self, callbacks):
        # 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("PT Vulnerabilities Manager")
        
        self.config = SafeConfigParser()
        self.createSection('projects')
        self.createSection('general')
        self.config.read('config.ini')
        self.chooser = JFileChooser()
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        
        self.logTable = Table(self)
        self.logTable.getColumnModel().getColumn(0).setMaxWidth(35)
        self.logTable.getColumnModel().getColumn(1).setMinWidth(100)

        self._requestViewer = self._callbacks.createMessageEditor(self, False)
        self._responseViewer = self._callbacks.createMessageEditor(self, False)

        self.initVulnerabilityTab()
        self.initProjSettingsTab()
        self.initTabs()
        self.initCallbacks()

        if self.projPath.getText() != None:
            self.loadVulnerabilities(self.projPath.getText())

        print "Thank you for installing PT Vulnerabilities Manager v1.0 extension"
        print "by Barak Tawily\n\n\n"
        print "Disclaimer:\nThis extension might create folders and files in your hardisk which might be declared as sensitive information, make sure you are creating projects under encrypted partition"
        return

    def initVulnerabilityTab(self):
        #
        ##  init vulnerability tab
        #

        nameLabel = JLabel("Vulnerability Name:")
        nameLabel.setBounds(10, 10, 140, 30)

        self.addButton = JButton("Add",actionPerformed=self.addVuln)
        self.addButton.setBounds(10, 500, 100, 30) 

        rmVulnButton = JButton("Remove",actionPerformed=self.rmVuln)
        rmVulnButton.setBounds(465, 500, 100, 30)

        mitigationLabel = JLabel("Mitigation:")
        mitigationLabel.setBounds(10, 290, 150, 30)
        
        addSSBtn = JButton("Add SS",actionPerformed=self.addSS)
        addSSBtn.setBounds(750, 40, 110, 30) 

        deleteSSBtn = JButton("Remove SS",actionPerformed=self.removeSS)
        deleteSSBtn.setBounds(750, 75, 110, 30) 

        piclistLabel = JLabel("Images list:")
        piclistLabel.setBounds(580, 10, 140, 30)

        self.screenshotsList = DefaultListModel()
        self.ssList = JList(self.screenshotsList)
        self.ssList.setBounds(580, 40, 150, 250)
        self.ssList.addListSelectionListener(ssChangedHandler(self))
        self.ssList.setBorder(BorderFactory.createLineBorder(Color.GRAY))

        previewPicLabel = JLabel("Selected image preview: (click to open in image viewer)")
        previewPicLabel.setBounds(580, 290, 500, 30)


        copyImgMenu = JMenuItem("Copy")
        copyImgMenu.addActionListener(copyImg(self))

        self.imgMenu = JPopupMenu("Popup")
        self.imgMenu.add(copyImgMenu)

        self.firstPic = JLabel()
        self.firstPic.setBorder(BorderFactory.createLineBorder(Color.GRAY))
        self.firstPic.setBounds(580, 320, 550, 400)
        self.firstPic.addMouseListener(imageClicked(self))

        self.vulnName = JTextField("")
        self.vulnName.getDocument().addDocumentListener(vulnTextChanged(self))
        self.vulnName.setBounds(140, 10, 422, 30)

        sevirities = ["Unclassified", "Critical","High","Medium","Low"]
        self.threatLevel = JComboBox(sevirities);
        self.threatLevel.setBounds(140, 45, 140, 30)

        colors = ["Color:", "Green", "Red"]
        self.colorCombo = JComboBox(colors);
        self.colorCombo.setBounds(465, 45, 100, 30)
        self.colorCombo

        severityLabel = JLabel("Threat Level:")
        severityLabel.setBounds(10, 45, 100, 30)

        descriptionLabel = JLabel("Description:")
        descriptionLabel.setBounds(10, 80, 100, 30)

        self.descriptionString = JTextArea("", 5, 30)
        self.descriptionString.setWrapStyleWord(True);
        self.descriptionString.setLineWrap(True)
        self.descriptionString.setBounds(10, 110, 555, 175)
        descriptionStringScroll = JScrollPane(self.descriptionString)
        descriptionStringScroll.setBounds(10, 110, 555, 175)
        descriptionStringScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)


        self.mitigationStr = JTextArea("", 5, 30)
        self.mitigationStr.setWrapStyleWord(True);
        self.mitigationStr.setLineWrap(True)
        self.mitigationStr.setBounds(10, 320, 555, 175)

        mitigationStrScroll = JScrollPane(self.mitigationStr)
        mitigationStrScroll.setBounds(10, 320, 555, 175)
        mitigationStrScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000);
        self.pnl.setLayout(None);
        self.pnl.add(addSSBtn)
        self.pnl.add(piclistLabel)
        self.pnl.add(nameLabel)
        self.pnl.add(deleteSSBtn)
        self.pnl.add(rmVulnButton)
        self.pnl.add(severityLabel)
        self.pnl.add(mitigationLabel)
        self.pnl.add(descriptionLabel)
        self.pnl.add(previewPicLabel)
        self.pnl.add(mitigationStrScroll)
        self.pnl.add(descriptionStringScroll)
        self.pnl.add(self.ssList)
        self.pnl.add(self.firstPic)
        self.pnl.add(self.addButton)
        self.pnl.add(self.vulnName)
        self.pnl.add(self.threatLevel)
        self.pnl.add(self.colorCombo)
        
    def initProjSettingsTab(self):
        # init project settings 
        
        projNameLabel = JLabel("Name:")
        projNameLabel.setBounds(10, 50, 140, 30)

        self.projName = JTextField("")
        self.projName.setBounds(140, 50, 320, 30)
        self.projName.getDocument().addDocumentListener(projTextChanged(self))

        detailsLabel = JLabel("Details:")
        detailsLabel.setBounds(10, 120, 140, 30)

        reportLabel = JLabel("Generate Report:")
        reportLabel.setBounds(10, 375, 140, 30)

        types = ["DOCX","HTML","XLSX"]
        self.reportType = JComboBox(types)
        self.reportType.setBounds(10, 400, 140, 30)

        generateReportButton = JButton("Generate", actionPerformed=self.generateReport)
        generateReportButton.setBounds(160, 400, 90, 30)


        self.projDetails = JTextArea("", 5, 30)
        self.projDetails.setWrapStyleWord(True);
        self.projDetails.setLineWrap(True)

        projDetailsScroll = JScrollPane(self.projDetails)
        projDetailsScroll.setBounds(10, 150, 450, 175)
        projDetailsScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)

        projPathLabel = JLabel("Path:")
        projPathLabel.setBounds(10, 90, 140, 30)

        self.projPath = JTextField("")
        self.projPath.setBounds(140, 90, 320, 30)

        chooseProjPathButton = JButton("Browse...",actionPerformed=self.chooseProjPath)
        chooseProjPathButton.setBounds(470, 90, 100, 30)
        
        importProjButton = JButton("Import",actionPerformed=self.importProj)
        importProjButton.setBounds(470, 10, 100, 30)

        exportProjButton = JButton("Export",actionPerformed=self.exportProj)
        exportProjButton.setBounds(575, 10, 100, 30)

        openProjButton = JButton("Open Directory",actionPerformed=self.openProj)
        openProjButton.setBounds(680, 10, 130, 30)

        currentProjectLabel = JLabel("Current:")
        currentProjectLabel.setBounds(10, 10, 140, 30)

        projects = self.config.options('projects')
        self.currentProject = JComboBox(projects)
        self.currentProject.addActionListener(projectChangeHandler(self))
        self.currentProject.setBounds(140, 10, 140, 30)

        self.autoSave = JCheckBox("Auto Save Mode")
        self.autoSave.setEnabled(False)  # implement this feature
        self.autoSave.setBounds(300, 10, 140, 30)
        self.autoSave.setToolTipText("Will save any changed value while focus is out")

        addProjButton = JButton("Add / Update",actionPerformed=self.addProj)
        addProjButton.setBounds(10, 330, 150, 30)

        removeProjButton = JButton("Remove Current",actionPerformed=self.rmProj)
        removeProjButton.setBounds(315, 330, 146, 30)

        generalOptions = self.config.options('general')
        if 'default project' in generalOptions:
            defaultProj = self.config.get('general','default project')
            self.currentProject.getModel().setSelectedItem(defaultProj)
            self.projPath.setText(self.config.get('projects',self.currentProject.getSelectedItem()))

        self.clearProjTab = True
        self.projectSettings = JPanel()
        self.projectSettings.setBounds(0, 0, 1000, 1000)
        self.projectSettings.setLayout(None)
        self.projectSettings.add(reportLabel)
        self.projectSettings.add(detailsLabel)
        self.projectSettings.add(projPathLabel)
        self.projectSettings.add(addProjButton)
        self.projectSettings.add(openProjButton)
        self.projectSettings.add(projNameLabel)
        self.projectSettings.add(projDetailsScroll)
        self.projectSettings.add(importProjButton)
        self.projectSettings.add(exportProjButton)
        self.projectSettings.add(removeProjButton)
        self.projectSettings.add(generateReportButton)
        self.projectSettings.add(chooseProjPathButton)
        self.projectSettings.add(currentProjectLabel)
        self.projectSettings.add(self.projPath)
        self.projectSettings.add(self.autoSave)
        self.projectSettings.add(self.projName)
        self.projectSettings.add(self.reportType)
        self.projectSettings.add(self.currentProject)

    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        colorsMenu = JMenu("Paint")
        redMenu = JMenuItem("Red")
        noneMenu = JMenuItem("None")
        greenMenu = JMenuItem("Green")
        redMenu.addActionListener(paintChange(self, "Red"))
        noneMenu.addActionListener(paintChange(self, None))
        greenMenu.addActionListener(paintChange(self, "Green"))
        colorsMenu.add(redMenu)
        colorsMenu.add(noneMenu)
        colorsMenu.add(greenMenu)
        
        
        self.menu = JPopupMenu("Popup")
        self.menu.add(colorsMenu)

        self.tabs = JTabbedPane()
        
        self.tabs.addTab("Request", self._requestViewer.getComponent())
        self.tabs.addTab("Response", self._responseViewer.getComponent())

        self.tabs.addTab("Vulnerability", self.pnl)

        self.tabs.addTab("Project Settings", self.projectSettings)
        
        self.tabs.setSelectedIndex(2)
        self._splitpane.setRightComponent(self.tabs)

    def initCallbacks(self):
        #
        ##  init callbacks
        #

        # customize our UI components
        self._callbacks.customizeUiComponent(self._splitpane)
        self._callbacks.customizeUiComponent(self.logTable)
        self._callbacks.customizeUiComponent(self.scrollPane)
        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.registerContextMenuFactory(self)
        # add the custom tab to Burp's UI
        self._callbacks.addSuiteTab(self)


    def loadVulnerabilities(self, projPath):
        self.clearList(None)
        selected = False
        for root, dirs, files in os.walk(projPath): # make it go only for dirs
            for dirName in dirs:
                xmlPath = projPath+"/"+dirName+"/vulnerability.xml"
                # xmlPath = xmlPath.replace("/","//")
                document = self.getXMLDoc(xmlPath)
                nodeList = document.getDocumentElement().getChildNodes()
                vulnName = nodeList.item(0).getTextContent()
                severity = nodeList.item(1).getTextContent()
                description = nodeList.item(2).getTextContent()
                mitigation = nodeList.item(3).getTextContent()
                color = nodeList.item(4).getTextContent()
                test = vulnerability(vulnName,severity,description,mitigation,color)
                self._lock.acquire()
                row = self._log.size()
                self._log.add(test)
                self.fireTableRowsInserted(row, row)
                self._lock.release()
                if vulnName == self.vulnName.getText():
                    self.logTable.setRowSelectionInterval(row,row)
                    selected = True
        if selected == False and self._log.size() > 0:
            self.logTable.setRowSelectionInterval(0, 0)
            self.loadVulnerability(self._log.get(0))
        
    def createSection(self, sectioName):
        self.config.read('config.ini')
        if not (sectioName in self.config.sections()):
            self.config.add_section(sectioName)
            cfgfile = open("config.ini",'w')
            self.config.write(cfgfile)
            cfgfile.close()

    def saveCfg(self):
        f = open('config.ini', 'w')
        self.config.write(f)
        f.close()

    def getXMLDoc(self, xmlPath):
        try:
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath)
            return document
        except:
            self._extender.popup("XML file not found")
            return

    def saveXMLDoc(self, doc, xmlPath):
        transformerFactory = TransformerFactory.newInstance()
        transformer = transformerFactory.newTransformer()
        source = DOMSource(doc)
        result = StreamResult(File(xmlPath))
        transformer.transform(source, result)

    def generateReport(self,event):
        if self.reportType.getSelectedItem() == "HTML":
            path = self.reportToHTML()
        if self.reportType.getSelectedItem() == "XLSX":
            path = self.reportToXLS()
        if self.reportType.getSelectedItem() == "DOCX":
            path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml')
        n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION)
        if n == JOptionPane.YES_OPTION:
            os.system('"' + path + '"') # Bug! stucking burp until the file get closed

    def exportProj(self,event):
        self.chooser.setDialogTitle("Save project")
        Ffilter = FileNameExtensionFilter("Zip files", ["zip"])
        self.chooser.setFileFilter(Ffilter)
        returnVal = self.chooser.showSaveDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            dst = str(self.chooser.getSelectedFile())
            shutil.make_archive(dst,"zip",self.getCurrentProjPath())
            self.popup("Project export successfuly")

    def importProj(self,event):
        self.chooser.setDialogTitle("Select project zip to directory")
        Ffilter = FileNameExtensionFilter("Zip files", ["zip"])
        self.chooser.setFileFilter(Ffilter)
        returnVal = self.chooser.showOpenDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            zipPath = str(self.chooser.getSelectedFile())
            self.chooser.setDialogTitle("Select project directory")
            self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            returnVal = self.chooser.showOpenDialog(None)
            if returnVal == JFileChooser.APPROVE_OPTION:
                projPath = str(self.chooser.getSelectedFile()) + "/PTManager"
                with zipfile.ZipFile(zipPath, "r") as z:
                    z.extractall(projPath)

                xmlPath = projPath + "/project.xml"
                document = self.getXMLDoc(xmlPath)
                nodeList = document.getDocumentElement().getChildNodes()
                projName = nodeList.item(0).getTextContent()
                nodeList.item(1).setTextContent(projPath)
                self.saveXMLDoc(document, xmlPath)
                self.config.set('projects', projName, projPath)
                self.saveCfg()
                self.reloadProjects()
                self.currentProject.getModel().setSelectedItem(projName)
                self.clearVulnerabilityTab() 

    def reportToXLS(self):
        if not xlsxwriterImported:
            self.popup("xlsxwriter library is not imported")
            return
        workbook = xlsxwriter.Workbook(self.getCurrentProjPath() + '/PT Manager Report.xlsx')
        worksheet = workbook.add_worksheet()
        bold = workbook.add_format({'bold': True})
        worksheet.write(0, 0, "Vulnerability Name", bold)
        worksheet.write(0, 1, "Threat Level", bold)
        worksheet.write(0, 2, "Description", bold)
        worksheet.write(0, 3, "Mitigation", bold)
        row = 1
        for i in range(0,self._log.size()):
            worksheet.write(row, 0, self._log.get(i).getName())
            worksheet.write(row, 1, self._log.get(i).getSeverity())
            worksheet.write(row, 2, self._log.get(i).getDescription())
            worksheet.write(row, 3, self._log.get(i).getMitigation())
            row = row + 1
            # add requests and images as well
        workbook.close()
        return self.getCurrentProjPath() + '/PT Manager Report.xlsx'
        
    def reportToHTML(self):
        htmlContent = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="he" dir="ltr">
    <head>
        <title>PT Manager Report</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <style>
        body {
        background-repeat: no-repeat;
        background-attachment: fixed;
        font-family: Arial,Tahoma,sens-serif;
        font-size: 13px;
        margin: auto;
        }

        #warpcenter {
            width: 900px;
            margin: 0px auto;
        }

        table {
            border: 2px dashed #000000;
        }

        td {
            border-top: 2px dashed #000000;
            padding: 10px;
        }

        img {
                border: 0px;
        }
</style>
<script language="javascript">
    function divHideShow(divToHideOrShow) 
    {
        var div = document.getElementById(divToHideOrShow);

        if (div.style.display == "block") 
        {
            div.style.display = "none";
        }
        else 
        {
            div.style.display = "block";
        }

        
    }         
</script>
    </head>

    <body>
        <div id="warpcenter">

<h1> PT Manager Report </h1>
<h2> Project: %s</h1>
    """ % (self.projName.getText())

        for i in range(0,self._log.size()):
            name = self._log.get(i).getName()
            request = "None"
            response = "None"
            path = self.getVulnReqResPath("request",name)
            if os.path.exists(path):
                request = self.newlineToBR(self.getFileContent(path))
                
            path = self.getVulnReqResPath("response",name)
            if os.path.exists(path):
                response = self.newlineToBR(self.getFileContent(path))
            images = ""
            for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(name)):
                if fileName.endswith(".jpg"):
                    images += "%s<br><img src=\"%s\"><br><br>" % (fileName, self.projPath.getText()+"/"+self.clearStr(name) + "/" + fileName)
            description = self.newlineToBR(self._log.get(i).getDescription())
            mitigation = self.newlineToBR(self._log.get(i).getMitigation())
            htmlContent +=  self.convertVulntoTable(i,name,self._log.get(i).getSeverity(), description,mitigation, request, response, images)
        htmlContent += "</div></body></html>"
        f = open(self.getCurrentProjPath() + '/PT Manager Report.html', 'w')
        f.writelines(htmlContent)
        f.close()
        return self.getCurrentProjPath() + '/PT Manager Report.html'

    def newlineToBR(self,string):
        return "<br />".join(string.split("\n"))

    def getFileContent(self,path):
        f = open(path, "rb")
        content = f.read()
        f.close()
        return content

    def convertVulntoTable(self, number, name, severity, description, mitigation, request = "None", response = "None", images = "None"):
        return """<div style="width: 100%%;height: 30px;text-align: center;background-color:#E0E0E0;font-size: 17px;font-weight: bold;color: #000;padding-top: 10px;">%s <a href="javascript:divHideShow('Table_%s');" style="color:#191970">(OPEN / CLOSE)</a></div>
        <div id="Table_%s" style="display: none;">
            <table width="100%%" cellspacing="0" cellpadding="0" style="margin: 0px auto;text-align: left;border-top: 0px;">
                <tr>
                    <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Threat Level: </span> 
                        <span style="color:#8b8989">%s</span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Description</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_03');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_03" style="display: none;margin-top: 25px;">
                        %s
                        </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Mitigration</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_04');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_04" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>

                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Request</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_05');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_05" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>


                                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Response</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_06');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_06" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>

                                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Images</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_07');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_07" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                    </td>
                </tr>
            </table>
        </div><br><br>""" % (name,number,number,severity,number,number,description,number,number,mitigation,number,number,request,number,number,response,number,number,images)

    def clearVulnerabilityTab(self, rmVuln=True):
        if rmVuln:
            self.vulnName.setText("")
        self.descriptionString.setText("")
        self.mitigationStr.setText("")
        self.colorCombo.setSelectedIndex(0)
        self.threatLevel.setSelectedIndex(0)
        self.screenshotsList.clear()
        self.addButton.setText("Add")
        self.firstPic.setIcon(None)

    def saveRequestResponse(self, type, requestResponse, vulnName):
        path = self.getVulnReqResPath(type,vulnName)
        f = open(path, 'wb')
        f.write(requestResponse)
        f.close()

    def openProj(self, event):
        os.system('explorer ' + self.projPath.getText())

    def getVulnReqResPath(self, requestOrResponse, vulnName):
        return self.getCurrentProjPath() + "/" + self.clearStr(vulnName) + "/"+requestOrResponse+"_" + self.clearStr(vulnName)

    def htmlEscape(self,data):
        return data.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')

    def generateReportFromDocxTemplate(self, zipname, newZipName, filename):      
        newZipName = self.getCurrentProjPath() + "/" + newZipName
        with zipfile.ZipFile(zipname, 'r') as zin:
            with zipfile.ZipFile(newZipName, 'w') as zout:
                zout.comment = zin.comment
                for item in zin.infolist():
                    if item.filename != filename:
                        zout.writestr(item, zin.read(item.filename))
                    else:
                        xml_content = zin.read(item.filename)
                        result = re.findall("(.*)<w:body>(?:.*)<\/w:body>(.*)",xml_content)[0]
                        newXML = result[0]
                        templateBody = re.findall("<w:body>(.*)<\/w:body>", xml_content)[0]
                        newBody = ""

                        for i in range(0,self._log.size()):
                            tmp = templateBody
                            tmp = tmp.replace("$vulnerability", self.htmlEscape(self._log.get(i).getName()))
                            tmp = tmp.replace("$severity", self.htmlEscape(self._log.get(i).getSeverity()))
                            tmp = tmp.replace("$description", self.htmlEscape(self._log.get(i).getDescription()))
                            tmp = tmp.replace("$mitigation", self.htmlEscape(self._log.get(i).getMitigation()))
                            newBody = newBody + tmp
                         
                        newXML = newXML + newBody
                        newXML = newXML + result[1]

        with zipfile.ZipFile(newZipName, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            zf.writestr(filename, newXML)
        return newZipName


    def chooseProjPath(self, event):
        self.chooser.setDialogTitle("Select target directory")
        self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        returnVal = self.chooser.showOpenDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            projPath = str(self.chooser.getSelectedFile()) + "/PTManager"
            os.makedirs(projPath)
            self.projPath.setText(projPath)

    def reloadProjects(self):
        self.currentProject.setModel(DefaultComboBoxModel(self.config.options('projects')))

    def rmProj(self, event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            self._requestViewer.setMessage("None", False)
            self._responseViewer.setMessage("None", False)
            shutil.rmtree(self.projPath.getText())
            self.config.remove_option('projects',self.currentProject.getSelectedItem())
            self.reloadProjects()
            self.currentProject.setSelectedIndex(0)
            self.loadVulnerabilities(self.projPath.getText())

    def popup(self,msg):
        JOptionPane.showMessageDialog(None,msg)

    def addProj(self, event):
        projPath = self.projPath.getText()
        if projPath == None or projPath == "":
            self.popup("Please select path")
            return
        self.config.set('projects', self.projName.getText(), projPath)
        self.saveCfg()
        xml = ET.Element('project')
        name = ET.SubElement(xml, "name")
        path = ET.SubElement(xml, "path")
        details = ET.SubElement(xml, "details")
        autoSaveMode = ET.SubElement(xml, "autoSaveMode")

        name.text = self.projName.getText()
        path.text = projPath
        details.text = self.projDetails.getText()
        autoSaveMode.text = str(self.autoSave.isSelected())
        tree = ET.ElementTree(xml)
        try:
            tree.write(self.getCurrentProjPath()+'/project.xml')
        except:
            self.popup("Invalid path")
            return

        self.reloadProjects()
        self.clearVulnerabilityTab()
        self.clearList(None)
        self.currentProject.getModel().setSelectedItem(self.projName.getText())

    def resize(self, image, width, height):
        bi = BufferedImage(width, height, BufferedImage.TRANSLUCENT)
        g2d = bi.createGraphics()
        g2d.addRenderingHints(RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY))
        g2d.drawImage(image, 0, 0, width, height, None)
        g2d.dispose()
        return bi;

    def clearStr(self, var):
        return var.replace(" " , "_").replace("\\" , "").replace("/" , "").replace(":" , "").replace("*" , "").replace("?" , "").replace("\"" , "").replace("<" , "").replace(">" , "").replace("|" , "").replace("(" , "").replace(")" , "")

    def popUpAreYouSure(self):
        dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION)
        if dialogResult == 0:
            return 0
        return 1

    def removeSS(self,event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            os.remove(self.getCurrentVulnPath() + "/" + self.ssList.getSelectedValue())
            self.ssList.getModel().remove(self.ssList.getSelectedIndex())
            self.firstPic.setIcon(ImageIcon(None))
            # check if there is images and select the first one
            # bug in linux

    def addSS(self,event):
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
        try:
            image = clipboard.getData(DataFlavor.imageFlavor)
        except:
            self.popup("Clipboard not contains image")
            return
        vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())
        if not os.path.exists(vulnPath):
            os.makedirs(vulnPath)
        name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg"
        fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name
        file = File(fileName)
        bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB);
        g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None);
        ImageIO.write(bufferedImage, "jpg", file)
        self.addVuln(self)
        self.ssList.setSelectedValue(name,True)

    def rmVuln(self, event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            self._requestViewer.setMessage("None", False)
            self._responseViewer.setMessage("None", False)
            shutil.rmtree(self.getCurrentVulnPath())
            self.clearVulnerabilityTab()
            self.loadVulnerabilities(self.getCurrentProjPath())

    def addVuln(self, event):
        if self.colorCombo.getSelectedItem() == "Color:":
            colorTxt = None
        else:
            colorTxt = self.colorCombo.getSelectedItem()
        self._lock.acquire()
        row = self._log.size()
        vulnObject = vulnerability(self.vulnName.getText(),self.threatLevel.getSelectedItem(),self.descriptionString.getText(),self.mitigationStr.getText() ,colorTxt)
        self._log.add(vulnObject) 
        self.fireTableRowsInserted(row, row)
        self._lock.release()

        vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())
        if not os.path.exists(vulnPath):
            os.makedirs(vulnPath)

        xml = ET.Element('vulnerability')
        name = ET.SubElement(xml, "name")
        severity = ET.SubElement(xml, "severity")
        description = ET.SubElement(xml, "description")
        mitigation = ET.SubElement(xml, "mitigation")
        color = ET.SubElement(xml, "color")
        name.text = self.vulnName.getText()
        severity.text = self.threatLevel.getSelectedItem()
        description.text = self.descriptionString.getText()
        mitigation.text = self.mitigationStr.getText()
        color.text = colorTxt
        tree = ET.ElementTree(xml)
        tree.write(vulnPath+'/vulnerability.xml')

        self.loadVulnerabilities(self.getCurrentProjPath())
        self.loadVulnerability(vulnObject)

    def vulnNameChanged(self):
            if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "":
                self.addButton.setText("Update")
            elif self.addButton.getText() != "Add":
                options = ["Create a new vulnerability", "Change current vulnerability name"]
                n = JOptionPane.showOptionDialog(None,
                    "Would you like to?",
                    "Vulnerability Name",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    None,
                    options,
                    options[0]);

                if n == 0:
                    self.clearVulnerabilityTab(False)
                    self.addButton.setText("Add")
                else:
                    newName = JOptionPane.showInputDialog(
                    None,
                    "Enter new name:",
                    "Vulnerability Name",
                    JOptionPane.PLAIN_MESSAGE,
                    None,
                    None,
                    self.vulnName.getText())
                    row = self.logTable.getSelectedRow()
                    old = self.logTable.getValueAt(row,1)                   
                    self.changeVulnName(newName,old)
                
    def changeVulnName(self,new,old):
        newpath = self.getCurrentProjPath() + "/" + new
        oldpath = self.getCurrentProjPath() + "/" + old
        os.rename(oldpath,newpath)
        self.changeCurrentVuln(new,0, newpath + "/vulnerability.xml")

    def getCurrentVulnPath(self):
        return self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())

    def getCurrentProjPath(self):
        return self.projPath.getText()

    def loadSS(self, imgPath):
        image = ImageIO.read(File(imgPath))
        if image.getWidth() <= 550 and image.getHeight() <= 400:
            self.firstPic.setIcon(ImageIcon(image))
            self.firstPic.setSize(image.getWidth(),image.getHeight())
        else:
            self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400)))
            self.firstPic.setSize(550,400)

    def clearProjectTab(self):
        self.projPath.setText("")
        self.projDetails.setText("")

    def clearList(self, event):
        self._lock.acquire()
        self._log = ArrayList()
        row = self._log.size()
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages();
        if responses > 0:
            ret = LinkedList()
            requestMenuItem = JMenuItem("Send to PT Manager");
            requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request"))
            ret.add(requestMenuItem);
            return(ret);
        return null;
    #
    # implement ITab
    #
    def getTabCaption(self):
        return "PT Manager"
    
    def getUiComponent(self):
        return self._splitpane

        #
    # 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 "#"
        if columnIndex == 1:
            return "Vulnerability Name"
        if columnIndex == 2:
            return "Threat Level"
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        vulnObject = self._log.get(rowIndex)
        if columnIndex == 0:
            return rowIndex+1
        if columnIndex == 1:
            return vulnObject.getName()
        if columnIndex == 2:
            return vulnObject.getSeverity()
        if columnIndex == 3:
            return vulnObject.getMitigation()
        if columnIndex == 4:
            return vulnObject.getColor()

        return ""

    def changeCurrentVuln(self,value,fieldNumber, xmlPath = "def"):
        if xmlPath == "def":
            xmlPath = self.getCurrentVulnPath() + "/vulnerability.xml"
        document = self.getXMLDoc(xmlPath)
        nodeList = document.getDocumentElement().getChildNodes()
        nodeList.item(fieldNumber).setTextContent(value)
        self.saveXMLDoc(document, xmlPath)
        self.loadVulnerabilities(self.getCurrentProjPath())

    def loadVulnerability(self, vulnObject):
        self.addButton.setText("Update")
        self.vulnName.setText(vulnObject.getName())
        self.threatLevel.setSelectedItem(vulnObject.getSeverity())
        self.descriptionString.setText(vulnObject.getDescription())
        self.mitigationStr.setText(vulnObject.getMitigation())

        if vulnObject.getColor() == "" or vulnObject.getColor() == None:
            self.colorCombo.setSelectedItem("Color:")
        else:
            self.colorCombo.setSelectedItem(vulnObject.getColor())
        self.screenshotsList.clear()

        for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())):
            if fileName.endswith(".jpg"):
                self.screenshotsList.addElement(fileName)
                imgPath = self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())+'/'+fileName
                # imgPath = imgPath.replace("/","//")
                self.loadSS(imgPath)

        if (self.screenshotsList.getSize() == 0):
            self.firstPic.setIcon(None)
        else:
            self.ssList.setSelectedIndex(0)

        path = self.getVulnReqResPath("request",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._requestViewer.setMessage(f, False)
        else:
            self._requestViewer.setMessage("None", False)
        
        path = self.getVulnReqResPath("response",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._responseViewer.setMessage(f, False)
        else:
            self._responseViewer.setMessage("None", False)
Пример #22
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                "tools",
                                                                "data",
                                                                "Favourites",
                                                                "icons",
                                                                "tool_16.png"])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                   "tools",
                                                                   "data",
                                                                   "Favourites",
                                                                   "icons",
                                                                   "black_tool_16.png"])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                 "images",
                                                                 "icons",
                                                                 "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(ChecksTableClickListener(app,
            self.checkPopup,
            self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(errorInfoBtnIcon,
                                    actionPerformed=app.on_errorInfoBtn_clicked,
                                    enabled=0)
        notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(notErrorIcon,
                                   actionPerformed=app.on_falsePositiveBtn_clicked,
                                   enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(correctedIcon,
                                    actionPerformed=app.on_correctedBtn_clicked,
                                    enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"),
                               None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = ["",
                   self.app.strings.getString("Check"),
                   self.app.strings.getString("Errors")]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {"white": (255, 255, 255),
                  "black": (0, 0, 0),
                  "green": (100, 200, 0),
                  "red": (200, 0, 0)}
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"),
                                       None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                         self.app.strings.getString("to_do"),
                         self.app.selectedChecks[0].toDo,
                         len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                        errorInfo,
                        self.app.strings.getString("to_do"),
                        self.app.selectedChecks[0].toDo,
                        len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)
Пример #23
0
class NewAccountGUI:
    def __init__(self, amgui):
        self.amgui = amgui
        self.am = amgui.acctmanager
        self.buildgwinfo()
        self.autologin = JCheckBox("Automatically Log In")
        self.acctname = JTextField()
        self.gwoptions = JPanel(doublebuffered)
        self.gwoptions.border = TitledBorder("Gateway Options")
        self.buildgwoptions("Twisted")
        self.mainframe = JFrame("New Account Window")
        self.buildpane()

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

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

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

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

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

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

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

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

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

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

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

    def cancel(self, ae):
        print "Cancelling new account creation"
        self.mainframe.dispose()
Пример #24
0
class NewAtfView(JDialog):
    '''
    Prompt user to choose some options to create a template for a new ATF
    file.
    '''
    def __init__(self, controller, projects, languages, protocols):
        self.modalityType = Dialog.ModalityType.APPLICATION_MODAL
        self.controller = controller
        self.projects = projects
        self.languages = languages
        self.protocols = protocols
        self.cancelled = False
        self.springLayout = SpringLayout()
        self.pane = self.getContentPane()

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("New ATF template")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def build(self):
        '''
        Puts all the window components together in the JFrame
        '''
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        ampersand_panel = self.build_ampersand_row()
        project_panel = self.build_projects_row()
        language_panel = self.build_language_row()
        buttons_panel = self.build_buttons_row()

        # Add panels to main JFrame
        self.add(ampersand_panel)
        self.add(project_panel)
        self.add(language_panel)
        self.add(buttons_panel)

    def build_ampersand_row(self):
        '''
        Builds the &-line row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        ampersand_label = JLabel("CDLI's ID: ")
        self.left_field = JTextField('&')
        equals_label = JLabel('=')
        self.right_field = JTextField()
        tooltip_text = ("<html><body>This is the ID and text's designation "
                        "according to<br/>the CDLI catalog. If your text is "
                        "not yet in the<br/>catalog, please email "
                        "[email protected] to get<br/>an ID and designation."
                        )
        help_label = self.build_help_label(tooltip_text)
        panel.add(ampersand_label)
        panel.add(self.left_field)
        panel.add(equals_label)
        panel.add(self.right_field)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             ampersand_label,
                             20,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             ampersand_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.left_field,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.left_field,
                             20,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             equals_label,
                             5,
                             SpringLayout.EAST,
                             self.left_field)
        layout.putConstraint(SpringLayout.NORTH,
                             equals_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.right_field,
                             5,
                             SpringLayout.EAST,
                             equals_label)
        layout.putConstraint(SpringLayout.NORTH,
                             self.right_field,
                             20,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.right_field)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_projects_row(self):
        '''
        Builds the projects row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        project_label = JLabel('Project: ')
        self.right_combo = JComboBox()
        self.right_combo.setEditable(True)

        def create_project_list():
            '''
            Prepares list of projects and subprojects ordered with the default
            one first.
            '''
            default_project = self.projects['default'][0].split('/')[0]
            if '/' in self.projects['default']:
                default_subproject = self.projects['default'].split('/')[1]
            else:
                default_subproject = ''
            projects = [default_project]
            subprojects = [default_subproject]
            # User created projects might not be in default dictionary
            for project in self.projects.keys():
                if (project != default_project and project != 'default'):
                    projects.append(project)
                # Default project might not have subproject
            if default_project in self.projects.keys():
                if default_subproject:
                    for subproject in self.projects[default_project]:
                        if (subproject != default_subproject):
                            subprojects.append(subproject)
            return projects, subprojects

        self.left_combo = JComboBox(create_project_list()[0])
        # Make left combo keep size no matter how long project names are
        self.left_combo.setPreferredSize(Dimension(125, 30))
        self.left_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.left_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.left_combo.setSize(self.left_combo.getPreferredSize())

        self.right_combo = JComboBox(create_project_list()[1])
        # Prevent right combo to change sizes dynamically
        self.right_combo.setPreferredSize(Dimension(100, 30))
        self.right_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.right_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.right_combo.setSize(self.left_combo.getPreferredSize())

        action_listener = ComboActionListener(self.right_combo,
                                              self.projects)
        self.left_combo.addActionListener(action_listener)
        self.left_combo.setEditable(True)
        self.right_combo.setEditable(True)

        slash_label = JLabel('/')

        tooltip_text = ("<html><body>Choose project from list or insert a new "
                        "one.<br/>You can leave the right-hand field blank."
                        "</body><html>")
        help_label = self.build_help_label(tooltip_text)
        panel.add(project_label)
        panel.add(self.left_combo)
        panel.add(slash_label)
        panel.add(self.right_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             project_label,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             project_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.left_combo,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.left_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             slash_label,
                             5,
                             SpringLayout.EAST,
                             self.left_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             slash_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.right_combo,
                             5,
                             SpringLayout.EAST,
                             slash_label)
        layout.putConstraint(SpringLayout.NORTH,
                             self.right_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.right_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_language_row(self):
        '''
        Builds the language row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Get language list from settings.yaml, removing the default one from
        # the list
        languages = self.languages.keys()
        languages.remove('default')
        # Create necessary components and add them to panel.
        language_label = JLabel('Language: ')
        self.language_combo = JComboBox(languages)
        # Set selected language to default
        self.language_combo.setSelectedItem(self.languages['default'])
        tooltip_text = "Choose a language from the dropdown menu."
        help_label = self.build_help_label(tooltip_text)
        panel.add(language_label)
        panel.add(self.language_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             language_label,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             language_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.language_combo,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.language_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.language_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_buttons_row(self):
        '''
        Add OK/Cancel/Blank buttons.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        create_button = JButton('Create template',
                                actionPerformed=self.create_template)
        leave_button = JButton('Leave blank', actionPerformed=self.blank)
        cancel_button = JButton('Cancel', actionPerformed=self.cancel)
        panel.add(create_button)
        panel.add(leave_button)
        panel.add(cancel_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             create_button,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             create_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             leave_button,
                             5,
                             SpringLayout.EAST,
                             create_button)
        layout.putConstraint(SpringLayout.NORTH,
                             leave_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             cancel_button,
                             5,
                             SpringLayout.EAST,
                             leave_button)
        layout.putConstraint(SpringLayout.NORTH,
                             cancel_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             cancel_button)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             cancel_button)
        # Add this to NewAtf JFrame
        return panel

    def build_help_label(self, tooltip_text):
        icon = ImageIcon(find_image_resource('smallhelp'))
        label = JLabel()
        label.setIcon(icon)
        label.setToolTipText(tooltip_text)
        return label

    def cancel(self, event):
        self.cancelled = True
        self.dispose()

    def blank(self, event):
        self.controller.show_template()
        self.dispose()

    def create_template(self, event):
        '''
        Put together user selected elements of the template following ATF
        file format.
        '''
        # &-line
        # E.g. &X001001 = JCS 48, 089
        and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'),
                                    self.right_field.getText().encode('utf-8'))

        # Project line
        # E.g. #project: cams/gkab
        # E.g. #project: rimanum
        project_line = "#project: {}".format(
                            self.left_combo.getSelectedItem().encode('utf-8'))
        if self.right_combo.getSelectedItem():
            project_line = "{}/{}".format(
                            project_line,
                            self.right_combo.getSelectedItem().encode('utf-8'))

        # Language line
        # E.g. #atf: lang akk-x-stdbab
        language = self.language_combo.getSelectedItem()
        language_code = self.languages[language]

        # Protocol line/s
        # E.g. #atf: use unicode
        protocols = ''
        for protocol in self.protocols:
            protocols += '#atf: use {}\n'.format(protocol)

        # Put together all lines to create the template and show in ATF area
        self.controller.template = ('{}\n'
                                    '{}\n'
                                    '#atf: lang {}\n'
                                    '{}\n'.format(and_line, project_line,
                                                  language_code, protocols)
                                    )
        self.controller.show_template()
        self.dispose()
Пример #25
0
class NewAtfView(JDialog):
    '''
    Prompt user to choose some options to create a template for a new ATF
    file.
    '''
    def __init__(self, controller, projects, languages, protocols):
        self.modalityType = Dialog.ModalityType.APPLICATION_MODAL
        self.controller = controller
        self.projects = projects
        self.languages = languages
        self.protocols = protocols
        self.cancelled = False
        self.springLayout = SpringLayout()
        self.pane = self.getContentPane()

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("New ATF template")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def build(self):
        '''
        Puts all the window components together in the JFrame
        '''
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        ampersand_panel = self.build_ampersand_row()
        project_panel = self.build_projects_row()
        language_panel = self.build_language_row()
        buttons_panel = self.build_buttons_row()

        # Add panels to main JFrame
        self.add(ampersand_panel)
        self.add(project_panel)
        self.add(language_panel)
        self.add(buttons_panel)

    def build_ampersand_row(self):
        '''
        Builds the &-line row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        ampersand_label = JLabel("CDLI's ID: ")
        self.left_field = JTextField('&')
        equals_label = JLabel('=')
        self.right_field = JTextField()
        tooltip_text = ("<html><body>This is the ID and text's designation "
                        "according to<br/>the CDLI catalog. If your text is "
                        "not yet in the<br/>catalog, please email "
                        "[email protected] to get<br/>an ID and designation.")
        help_label = self.build_help_label(tooltip_text)
        panel.add(ampersand_label)
        panel.add(self.left_field)
        panel.add(equals_label)
        panel.add(self.right_field)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, ampersand_label, 20,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.left_field, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.left_field, 20,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, equals_label, 5,
                             SpringLayout.EAST, self.left_field)
        layout.putConstraint(SpringLayout.NORTH, equals_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.right_field, 5,
                             SpringLayout.EAST, equals_label)
        layout.putConstraint(SpringLayout.NORTH, self.right_field, 20,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.right_field)
        layout.putConstraint(SpringLayout.NORTH, help_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_projects_row(self):
        '''
        Builds the projects row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        project_label = JLabel('Project: ')
        self.right_combo = JComboBox()
        self.right_combo.setEditable(True)

        def create_project_list():
            '''
            Prepares list of projects and subprojects ordered with the default
            one first.
            '''
            default_project = self.projects['default'][0].split('/')[0]
            if '/' in self.projects['default']:
                default_subproject = self.projects['default'].split('/')[1]
            else:
                default_subproject = ''
            projects = [default_project]
            subprojects = [default_subproject]
            # User created projects might not be in default dictionary
            for project in self.projects.keys():
                if (project != default_project and project != 'default'):
                    projects.append(project)
                # Default project might not have subproject
            if default_project in self.projects.keys():
                if default_subproject:
                    for subproject in self.projects[default_project]:
                        if (subproject != default_subproject):
                            subprojects.append(subproject)
            return projects, subprojects

        self.left_combo = JComboBox(create_project_list()[0])
        # Make left combo keep size no matter how long project names are
        self.left_combo.setPreferredSize(Dimension(125, 30))
        self.left_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.left_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.left_combo.setSize(self.left_combo.getPreferredSize())

        self.right_combo = JComboBox(create_project_list()[1])
        # Prevent right combo to change sizes dynamically
        self.right_combo.setPreferredSize(Dimension(100, 30))
        self.right_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.right_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.right_combo.setSize(self.left_combo.getPreferredSize())

        action_listener = ComboActionListener(self.right_combo, self.projects)
        self.left_combo.addActionListener(action_listener)
        self.left_combo.setEditable(True)
        self.right_combo.setEditable(True)

        slash_label = JLabel('/')

        tooltip_text = ("<html><body>Choose project from list or insert a new "
                        "one.<br/>You can leave the right-hand field blank."
                        "</body><html>")
        help_label = self.build_help_label(tooltip_text)
        panel.add(project_label)
        panel.add(self.left_combo)
        panel.add(slash_label)
        panel.add(self.right_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, project_label, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, project_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.left_combo, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, slash_label, 5,
                             SpringLayout.EAST, self.left_combo)
        layout.putConstraint(SpringLayout.NORTH, slash_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.right_combo, 5,
                             SpringLayout.EAST, slash_label)
        layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.right_combo)
        layout.putConstraint(SpringLayout.NORTH, help_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_language_row(self):
        '''
        Builds the language row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Get language list from settings.yaml, removing the default one from
        # the list
        languages = self.languages.keys()
        languages.remove('default')
        # Create necessary components and add them to panel.
        language_label = JLabel('Language: ')
        self.language_combo = JComboBox(languages)
        # Set selected language to default
        self.language_combo.setSelectedItem(self.languages['default'])
        tooltip_text = "Choose a language from the dropdown menu."
        help_label = self.build_help_label(tooltip_text)
        panel.add(language_label)
        panel.add(self.language_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, language_label, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, language_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.language_combo, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.language_combo)
        layout.putConstraint(SpringLayout.NORTH, help_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_buttons_row(self):
        '''
        Add OK/Cancel/Blank buttons.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        create_button = JButton('Create template',
                                actionPerformed=self.create_template)
        leave_button = JButton('Leave blank', actionPerformed=self.blank)
        cancel_button = JButton('Cancel', actionPerformed=self.cancel)
        panel.add(create_button)
        panel.add(leave_button)
        panel.add(cancel_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, create_button, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, create_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, leave_button, 5,
                             SpringLayout.EAST, create_button)
        layout.putConstraint(SpringLayout.NORTH, leave_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, cancel_button, 5,
                             SpringLayout.EAST, leave_button)
        layout.putConstraint(SpringLayout.NORTH, cancel_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             cancel_button)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             cancel_button)
        # Add this to NewAtf JFrame
        return panel

    def build_help_label(self, tooltip_text):
        icon = ImageIcon(find_image_resource('smallhelp'))
        label = JLabel()
        label.setIcon(icon)
        label.setToolTipText(tooltip_text)
        return label

    def cancel(self, event):
        self.cancelled = True
        self.dispose()

    def blank(self, event):
        self.controller.show_template()
        self.dispose()

    def create_template(self, event):
        '''
        Put together user selected elements of the template following ATF
        file format.
        '''
        # &-line
        # E.g. &X001001 = JCS 48, 089
        and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'),
                                    self.right_field.getText().encode('utf-8'))

        # Project line
        # E.g. #project: cams/gkab
        # E.g. #project: rimanum
        project_line = "#project: {}".format(
            self.left_combo.getSelectedItem().encode('utf-8'))
        if self.right_combo.getSelectedItem():
            project_line = "{}/{}".format(
                project_line,
                self.right_combo.getSelectedItem().encode('utf-8'))

        # Language line
        # E.g. #atf: lang akk-x-stdbab
        language = self.language_combo.getSelectedItem()
        language_code = self.languages[language]

        # Protocol line/s
        # E.g. #atf: use unicode
        protocols = ''
        for protocol in self.protocols:
            protocols += '#atf: use {}\n'.format(protocol)

        # Put together all lines to create the template and show in ATF area
        self.controller.template = ('{}\n'
                                    '{}\n'
                                    '#atf: lang {}\n'
                                    '{}\n'.format(and_line, project_line,
                                                  language_code, protocols))
        self.controller.show_template()
        self.dispose()
Пример #26
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

        ### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(
            app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(
            app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(
            self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "tool_16.png"
                ])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(
            self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "black_tool_16.png"
                ])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(
            ImageIcon(
                File.separator.join(
                    [self.app.SCRIPTDIR, "images", "icons", "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(
            ChecksTableClickListener(app, self.checkPopup, self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(
            app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(
            app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

        ### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(
            errorInfoBtnIcon,
            actionPerformed=app.on_errorInfoBtn_clicked,
            enabled=0)
        notErrorIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(
            notErrorIcon,
            actionPerformed=app.on_falsePositiveBtn_clicked,
            enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(
            correctedIcon,
            actionPerformed=app.on_correctedBtn_clicked,
            enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(
            app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(
            app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(
            app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(
            app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"), None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = [
            "",
            self.app.strings.getString("Check"),
            self.app.strings.getString("Errors")
        ]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(
                self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {
            "white": (255, 255, 255),
            "black": (0, 0, 0),
            "green": (100, 200, 0),
            "red": (200, 0, 0)
        }
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(
            self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"), None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                self.app.strings.getString("to_do"),
                self.app.selectedChecks[0].toDo,
                len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                errorInfo, self.app.strings.getString("to_do"),
                self.app.selectedChecks[0].toDo,
                len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)