class TextFieldPanel(JPanel, FocusListener):
    __metaclass__ = Singleton

    def __init__(self):
        super(TextFieldPanel, self).__init__()
        self._text_field = None

    def focusGained(self, event):
        pass

    def focusLost(self, event):
        Application.get_instance().execute(
            SetDomainDictValueCommand(
                self._get_domain_dict_type(), self._get_domain_dict_key(),
                InfrastructureHelpers.split(self._text_field.getText())))

    def display(self, values):
        self._prepare_components(values)

    def _prepare_components(self, values):
        self._text_field = JTextField()
        self._text_field.setColumns(30)
        self._text_field.setEditable(True)
        self._text_field.setText(
            InfrastructureHelpers.join(values[self._get_domain_dict_key()]))
        self._text_field.addFocusListener(self)
        self.add(self._text_field)
Ejemplo n.º 2
0
def textfield(text = "", actionListener = None):
    txt = JTextField(text, 15)
    class Focuser(FocusListener):
        def focusGained(self,e):
            pass
        def focusLost(self,e):
            if actionListener: actionListener(e)
    txt.addFocusListener(Focuser())
#    if actionListener: txt.addActionListener(actionListener)
    return txt
Ejemplo n.º 3
0
def textfield(text="", actionListener=None):
    txt = JTextField(text, 15)

    class Focuser(FocusListener):
        def focusGained(self, e):
            pass

        def focusLost(self, e):
            if actionListener: actionListener(e)

    txt.addFocusListener(Focuser())
    #    if actionListener: txt.addActionListener(actionListener)
    return txt
Ejemplo n.º 4
0
class _HintTextField(FocusListener, KeyAdapter):
    """
    HintTextField is a class responsible for showing an hint while the textfield is empty
    """
    def __init__(self, hint=None, action=None):
        if not hint: hint = 'hint'
        if not action: action = nop_evt
        self.this = JTextField(hint)
        self._hint = hint
        self._showing_hint = True
        self._enter_listener = None
        self.this.addFocusListener(self)
        self.this.addKeyListener(self)
        self.set_enter_evt_listener(action)

    def set_enter_evt_listener(self, enter_listener):
        """
        Add an evt listener to HintTextField

        :param enter_listener: lambda event listener
        :return:
        """
        self._enter_listener = enter_listener

    def keyPressed(self, e):
        """
        KeyAdapter override

        :param e: event containing the key pressed
        :return: None
        """
        if self._enter_listener and e.getKeyCode() == KeyEvent.VK_ENTER:
            self._enter_listener(e)

    def focusGained(self, e):
        """
        FocusListener override

        :param e: unused
        :return: None
        """
        if self.getText() == "":
            self.this.setText("")
            self._showing_hint = False

    def focusLost(self, e):
        """
        FocusListener override

        :param e: unused
        :return: None
        """
        if self.getText() == "":
            self.this.setText(self._hint)
            self._showing_hint = True

    def getText(self):
        """
        :return: the current text or "" if no text is wrote inside the textfield
        """
        if self._showing_hint:
            return ""
        else:
            return self.this.getText()

    def setText(self, txt):
        """
        Set Text

        :param txt: a string
        :return: None
        """
        self.this.setText(txt)
        self._showing_hint = False

    def reset(self):
        """
        Reset the HintBox
        :return: None
        """
        self.this.setText(self._hint)
        self._showing_hint = True
Ejemplo n.º 5
0
class ConsolePanel(Panel):
    def __init__(self):

        self.console = None
        self.outText = None
        self.inText = None
        self.outTextScroller = None
        self.nestedInputPanel = None
        self.directoryText = None
        Panel.__init__(self, "insets 0 0 0 0")

    def sendCommand(self, command):
        print str(self)
        oldText = self.inText.getText()
        self.inText.setText(command)

        self.inText.getActionListeners()[0].actionPerformed(None)
        self.inText.setText(oldText)

    def setDirectoryText(self, dirText):
        self.directoryText.setText(dirText)
        self.nestedInputPanel.revalidate()

    def write_out(self, text):
        if not self.outText:
            return
        self.outText.setText(self.outText.getText() + text)

    def initUI(self):

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

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

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

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

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

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

        #self.outText.repaint()

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

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

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

        self.inText.addFocusListener(InFocusAdapter())

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

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

        dirTex = self.directoryText

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

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

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

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

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

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

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

        self.inText.addActionListener(
            InputTextActionListener(self, self.inText, self.outText,
                                    self.console))
        self.inText.addKeyListener(
            InputKeyActionListener(self, self.inText, self.outText,
                                   self.console))

    def addUI(self):

        self.add(self.outTextScroller, "cell 0 0, push, grow")
        self.add(self.nestedInputPanel, "cell 0 1, pushx, growx")
        self.nestedInputPanel.add(self.directoryText, "cell 0 0")
        self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")
Ejemplo n.º 6
0
class BeautifierOptionsPanel(JScrollPane):
    def __init__(self, extender):
        super(BeautifierOptionsPanel, self).__init__()
        self._extender = extender

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

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

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

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

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

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

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

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

        innerContainer.add(messageTabOptionPanel, gbc)

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

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

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

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

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

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

        self.setDefaultOptionDisplay()

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

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

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

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

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

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

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

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

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

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

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

        def focusGained(self, e):
            pass

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

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

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

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

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

        def focusGained(self, e):
            pass

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

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

        def focusGained(self, e):
            pass

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

	def __init__(self):
		
		self.console = None
		self.outText = None
		self.inText = None
		self.outTextScroller = None
		self.nestedInputPanel = None
		self.directoryText = None
		Panel.__init__(self, "insets 0 0 0 0")

	def sendCommand(self, command):
		print str(self)
		oldText = self.inText.getText()
		self.inText.setText(command)

		self.inText.getActionListeners()[0].actionPerformed(None)
		self.inText.setText(oldText)

	def setDirectoryText(self, dirText):
		self.directoryText.setText(dirText)
		self.nestedInputPanel.revalidate()

	def write_out(self,text):
		if not self.outText:
			return
		self.outText.setText(self.outText.getText() + text)

	def initUI(self):

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

		#create the output text panel
		self.outText = JTextArea()
		self.outText.setEditable(False)
		self.outText.setFont(font)
		self.outText.setWrapStyleWord(True)
		self.outText.setLineWrap(True)
		#self.outText.setLineWrap(True)
		#self.outText.setWrapStyleWord(True)
		class NoGhostScroller(JScrollPane):
			def paintComponent(self, g):
				
				g.setColor(self.getBackground())
				g.fillRect(0, 0, self.getWidth(), self.getHeight())
				#super(NoGhostScroller, self).paintComponent(g)

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

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

		#self.outText.repaint()

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

		#create the input text box
		self.inText = JTextField()
		self.inText.setFocusTraversalKeysEnabled(False)
		self.inText.setFont(font)
		self.inText.setBackground(Color(0, 20, 0))
		self.inText.setForeground(Color.WHITE)
		self.inText.getCaret().setVisible(True)
		self.inText.getCaret().setBlinkRate(500)
		self.inText.setCaretColor(Color(200,255,200))
		
		class InFocusAdapter(FocusAdapter):
			def focusLost(adap, e):
				self.inText.setVisible(True)
		self.inText.addFocusListener(InFocusAdapter())

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

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


		dirTex = self.directoryText;

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

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

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

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

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

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

		self.inText.addActionListener(InputTextActionListener(self,self.inText,self.outText,self.console))
		self.inText.addKeyListener(InputKeyActionListener(self,self.inText,self.outText,self.console))




	def addUI(self):
		
		self.add(self.outTextScroller, "cell 0 0, push, grow")
		self.add(self.nestedInputPanel, "cell 0 1, pushx, growx")
		self.nestedInputPanel.add(self.directoryText, "cell 0 0")
		self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")