table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
table.setAutoCreateRowSorter(True) # to sort the view only, not the data in the underlying TableModel
jsp = JScrollPane(table)
jsp.setPreferredSize(Dimension(200, 500))
c.anchor = GridBagConstraints.NORTHWEST
c.fill = GridBagConstraints.BOTH # resize with the frame
gb.setConstraints(jsp, c)
all.add(jsp)
c.gridx = 1
c.weightx = 1.0 # take any additionally available horizontal space
c.weighty = 1.0
textarea = JTextArea()
textarea.setLineWrap(True)
textarea.setWrapStyleWord(True) # wrap text by cutting at whitespace
textarea.setEditable(False) # avoid changing the text, as any changes wouldn't be persisted to disk
font = textarea.getFont().deriveFont(20.0)
textarea.setFont(font)
textarea.setPreferredSize(Dimension(500, 500))
gb.setConstraints(textarea, c)
all.add(textarea)
frame = JFrame("CSV")
frame.getContentPane().add(all)
frame.pack()
frame.setVisible(True)

# React to a row being selected by showing the corresponding Motivation entry
# in the textarea to the right, so that it's more readable
class TableSelectionListener(ListSelectionListener):
  def valueChanged(self, event):
    if event.getValueIsAdjusting():
      return
Пример #2
0
class HandRecoWriter(JFrame):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        #Create classifiers
        #Character classifier
        path_to_this_dir = File(str(inspect.getfile( inspect.currentframe() ))).getParent()
        character_classifier_file = open(File(path_to_this_dir,"character_classifier.dat").getPath(),'r')
        self.character_classifier = CharacterClassifier(from_string_string=character_classifier_file.read())
        character_classifier_file.close()
        #Word classifier
        word_classifier_file = open(File(path_to_this_dir,"word_classifier.dat").getPath(),'r')
        self.word_classifier= WordClassifier(from_string_string=word_classifier_file.read())
        word_classifier_file.close()
        #Set up window
        self.setTitle("HandReco Writer")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setLayout(BorderLayout())
        #Set up menu
        menu_bar = JMenuBar()
        info_menu = JMenu("Info")
        def instructions(event):
            instr = '''
            The program can just recognise capital English characters.
            See Info -> Available Words... for available word corrections.
            
            Good Luck with the writing!'''
            JOptionPane.showMessageDialog(self, instr, 
                          "Instructions", 
                          JOptionPane.INFORMATION_MESSAGE)
        instructions_menu_item = JMenuItem("Instructions...",actionPerformed=instructions)
        info_menu.add(instructions_menu_item)
        def word_corrections(event):
            words_string = ""
            for word in self.word_classifier.words:
                words_string = words_string + word.upper() + "\n"
            text = "The words that can be corrected are:\n\n" +words_string
            dialog = JOptionPane(text, 
                                 JOptionPane.INFORMATION_MESSAGE)
            dialog_wrapper = JDialog(self,"Available Words",False)
            dialog_wrapper.setContentPane(dialog)
            dialog_wrapper.pack()
            dialog_wrapper.setVisible(True)
        word_corrections_menu_item = JMenuItem("Available Words...",actionPerformed=word_corrections)
        info_menu.add(word_corrections_menu_item)
        menu_bar.add(info_menu)
        self.setJMenuBar(menu_bar)
        #Input panel
        input_panel = JPanel()
        input_panel.setLayout(BoxLayout(input_panel, BoxLayout.X_AXIS))
        input_panel.setBorder(BorderFactory.createTitledBorder("Input"))
        self.paint_area = PaintArea(100,100)
        input_panel.add(self.paint_area)
        input_options_panel = JPanel()
        input_options_panel.setLayout(BoxLayout(input_options_panel, BoxLayout.Y_AXIS))
        #Write Char
        write_char_panel = JPanel(BorderLayout())
        def write_char(event):
            char = self.character_classifier.classify_image(self.paint_area.image())
            self.text_area.setText(self.text_area.getText() + char)
            self.paint_area.clear()
        write_char_panel.add(JButton("Write Char", actionPerformed=write_char), BorderLayout.NORTH)
        input_options_panel.add(write_char_panel)
        #Space and Correct
        space_and_correct_panel = JPanel(BorderLayout())
        def space_and_correct(event):
            text = self.text_area.getText()
            words = text.split(" ")
            string = words[-1]
            try:
                word = self.word_classifier.classify(string.lower())
                words[-1] = word.upper()
            except:
                JOptionPane.showMessageDialog(self, "Have you entered a character which is not in the alphabet?", 
                              "Could not Correct", 
                              JOptionPane.ERROR_MESSAGE)
                self.text_area.setText(text + " ")
                return
            newText = ""
            for w in words:
                newText = newText + w + " "
            self.text_area.setText(newText)
        space_and_correct_panel.add(JButton("Space and Correct", actionPerformed=space_and_correct), BorderLayout.NORTH)
        input_options_panel.add(space_and_correct_panel)
        #Space
        space_panel = JPanel(BorderLayout())
        def space(event):
            self.text_area.setText(self.text_area.getText() + " ")
        space_panel.add(JButton("Space", actionPerformed=space), BorderLayout.NORTH)
        input_options_panel.add(space_panel)
        #Clear Input Area
        clear_input_area_panel = JPanel(BorderLayout())
        def clear(event):
            self.paint_area.clear()
        clear_input_area_panel.add(JButton("Clear Input Area", actionPerformed=clear), BorderLayout.NORTH)
        input_options_panel.add(clear_input_area_panel)
        input_panel.add(input_options_panel)
        self.add(input_panel, BorderLayout.NORTH)
        text_area_panel = JPanel()
        text_area_panel.setLayout(BorderLayout())
        text_area_panel.setBorder(BorderFactory.createTitledBorder("Text"))
        self.text_area = JTextArea()
        self.text_area.setLineWrap(True)
        #Increase font size
        font = self.text_area.getFont() 
        self.text_area.setFont(Font(font.getName(), Font.BOLD, 24))
        
        text_area_panel.add(JScrollPane(self.text_area), BorderLayout.CENTER)
        self.add(text_area_panel, BorderLayout.CENTER)
        self.pack()
        self.setSize(Dimension(300,300))
        self.setVisible(True)
Пример #3
0
    class ConsoleController:
        def __init__(self, parent):
            self._parent = parent
            self._sessions = self._parent.sessions()
            self._request = None #TODO I'll need a request in order to connect to something
            self._position = None #TODO I'll need a position, something to change in the header to insert the command
            self._pwd = None
            self._commandHistory = []
            self._historyIndex = 0
            self._tabComplete = []

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            # input
            self._consolePwd = JTextField()
            self._consolePwd.setEditable(False)
            self._consolePwd.setText("Not initialized")
            self._consoleInput = JTextField()
            #Remove 'tab' low-level tab-function of jumping to other component, so I can use it
            self._consoleInput.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET)
            self._consoleInput.addActionListener(self.EnterPress())
            self._consoleInput.addKeyListener(self.KeyPress())
            self._inputPanel = JPanel(BorderLayout())
            self._inputPanel.add(self._consolePwd, BorderLayout.WEST)
            self._inputPanel.add(self._consoleInput, BorderLayout.CENTER)
            # output
            self._consoleOutput = JTextArea()
            self._consoleOutput.setEditable(False)
            self._consoleOutput.setForeground(Color.WHITE)
            self._consoleOutput.setBackground(Color.BLACK)
            self._consoleOutput.setFont(self._consoleOutput.getFont().deriveFont(12.0))

            self._scrollPaneConsoleOutput = JScrollPane(self._consoleOutput)

            # Add to main panel and return the main panel
            self._mainPanel.add(self._scrollPaneConsoleOutput, BorderLayout.CENTER)
            self._mainPanel.add(self._inputPanel, BorderLayout.SOUTH)
            return self._mainPanel

        def sendCommand(self, requestId, cmd, directTo):
            Utils.out("ConsoleController > sendCommand > 'cmd'")
            Utils.out(cmd)
            if cmd == 'clear':
                self.resetOutput()
                self._commandHistory.append(cmd)
                self.resetHistoryIndex()
                self.clearCmd()
                return
            cmdModified = cmd
            requestHttpMethod = self._parent.getRequestHttpService(requestId)
            #If I use virtual persistence and there's already a pwd set
            if Utils.shellController._virtualPersistence and self.pwd():
                #Then always prepend 'cd <pwd>' to any command executed. In reality we
                # always enter in the same directory, but because this shell keeps track
                # of where the user thinks he is, and always goes to that directory first
                # the illusion of a persistence is created
                cmdVirtual = "cd " + self.pwd()
                cmdModified = cmdVirtual + "; " + cmd
            requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified)
            Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start()
            self._commandHistory.append(cmd)
            self.resetHistoryIndex()
            self.clearCmd()

            if Utils.shellController._virtualPersistence:
                if cmd.startswith('cd '):
                    Utils.out("ConsoleController > sendCommand: detected 'cd '")
                    #ask for pwd
                    cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start()
                if Utils.shellController._tabCompletion:
                    #ask 'ls -1a' for tab-completion
                    # The first command, pwd is set here, but cmdVirtual ain't. But this
                    # also means we are at the entry directory anyway, so we can just ask ls
                    # and get the correct tab completion anyway
                    try:
                        cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX)
                    except:
                        cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
            else:
                if Utils.shellController._tabCompletion:
                    cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()

            #either way execute the requested command

        def startSession(self):
            #TODO when starting a session I want to test for a number of things:
            # if I can reform the request to a post request and still have it work
            # if base 64 is available
            # if bash is available
            self.setPwd(None)
            if Utils.shellController._virtualPersistence and Utils.shellController._outputIsolator:
                Utils.out("startSession > virtualPersistence enabled > Requesting pwd")
                self.sendCommand(self._parent.currentRequestId(), Commands.pwd(Commands.OS_LINUX), 'pwd')

        def appendOutput(self, text, printCommand=True):
            try:
                if printCommand:
                    self.printCommand(self._commandHistory[-1])
            except:
                pass

            self._consoleOutput.append("\n" + text)
            #auto scroll down if needed
            self._consoleOutput.setCaretPosition(self._consoleOutput.getDocument().getLength())

        def resetOutput(self):
            Utils.setConsole('')

        def printCommand(self, cmd):
            self._consoleOutput.append("\n" + self._pwd + "# " + cmd)

        def printCurrentCommand(self):
            self.printCommand(self.cmd())

        def setPwd(self, pwd):
            self._pwd = pwd
            if pwd is None:
                self._consolePwd.setText('')
            else:
                self._consolePwd.setText(pwd)
            Utils.consoleController._mainPanel.revalidate()

        def pwd(self):
            return self._pwd

        def cmdHistoryCount(self):
            return len(self._commandHistory) #TODO - 1

        def setCmd(self, cmd):
            self._consoleInput.setText(cmd)

        def cmd (self):
            return self._consoleInput.getText()

        def clearCmd(self):
            self._consoleInput.setText('')

        def resetHistoryIndex(self):
            self._historyIndex = self.cmdHistoryCount()

        def previousCommand(self):
            if self._historyIndex > 0:
                self._historyIndex -= 1
                self.setCmd(self._commandHistory[self._historyIndex])

        def nextCommand(self):
            if self._historyIndex < self.cmdHistoryCount():
                self._historyIndex += 1
                self.setCmd(self._commandHistory[self._historyIndex])
            else:
                self.clearCmd()
                self.resetHistoryIndex()

        def setTabComplete(self, text):
            self._tabComplete = text.splitlines()

        def findTabComplete(self, beginCharacters=''):
            suggestions = []
            if beginCharacters:
                for suggestion in self._tabComplete:
                    Utils.debug("suggestion", suggestion)
                    Utils.debug("text", beginCharacters)
                    if suggestion[0:len(beginCharacters)] == beginCharacters:
                        suggestions.append(suggestion)
            else:
                suggestions = self._tabComplete
            return suggestions

        def tabComplete(self):
            currentCommand = self.cmd()
            Utils.debug("currentCommand", currentCommand)
            if currentCommand:
                commandArray = currentCommand.split(' ')
                lastword = commandArray.pop()
                Utils.debug("lastword", lastword)
                suggestions = self.findTabComplete(lastword)
                if suggestions:
                    if len(suggestions) > 1:
                        self.printCurrentCommand()
                        for suggestion in suggestions:
                            self.appendOutput(suggestion, False)
                    if len(suggestions) == 1:
                        self.setCmd(' '.join(commandArray) + ' ' + suggestions.pop())
            else:
                suggestions = self.findTabComplete()
                if len(suggestions) > 1:
                    self.printCurrentCommand()
                    for suggestion in suggestions:
                        self.appendOutput(suggestion, False)

        class EnterPress(ActionListener): #TODO remove: AbstractAction
            def actionPerformed(self, e):
                Utils.consoleController.sendCommand(Utils.shellController.currentRequestId(), Utils.consoleInput.getText(), 'console')

            def keyPressed(self, e):
                Utils.out("key pressed")

        class KeyPress(KeyListener):
            def keyTyped(self, e):
                pass

            def keyReleased(self, e):
                if e.getKeyCode() == e.VK_DOWN:
                    Utils.consoleController.nextCommand()
                    Utils.out("released down")
                if e.getKeyCode() == e.VK_UP:
                    Utils.consoleController.previousCommand()
                    Utils.out("released up")

                if e.getKeyCode() == e.VK_TAB:
                    Utils.out("pressed tab")
                    Utils.consoleController.tabComplete()

            def keyPressed(self, e):
                pass
Пример #4
0
# Middle-right textarea showing the text of a note associated with the selected table row image
c.gridx = 1
c.gridy = 1
c.weighty = 1.0
c.gridwidth = 3
c.fill = GridBagConstraints.BOTH
textarea = JTextArea()
textarea.setBorder(
    BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(Color.BLACK),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)))
textarea.setLineWrap(True)
textarea.setWrapStyleWord(True)  # wrap text by cutting lines at whitespace
textarea.setEditable(False)
font = textarea.getFont().deriveFont(18.0)
textarea.setFont(font)
textarea.setPreferredSize(Dimension(500, 500))
gb.setConstraints(textarea, c)
all.add(textarea)

# Bottom text label showing the status of the note: whether it's being edited, or saved.
c.gridx = 1
c.gridy = 2
c.gridwidth = 1
c.weightx = 0.5
c.weighty = 0.0
note_status = JLabel("")
gb.setConstraints(note_status, c)
all.add(note_status)
Пример #5
0
class HandRecoWriter(JFrame):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        #Create classifiers
        #Character classifier
        path_to_this_dir = File(str(inspect.getfile(
            inspect.currentframe()))).getParent()
        character_classifier_file = open(
            File(path_to_this_dir,
                 "character_classifier_11_segments_4_6_cf.dat").getPath(), 'r')
        self.character_classifier = CharacterClassifier(
            from_string_string=character_classifier_file.read())
        character_classifier_file.close()
        #Word classifier
        word_classifier_file = open(
            File(path_to_this_dir, "word_classifier.dat").getPath(), 'r')
        self.word_classifier = WordClassifier(
            from_string_string=word_classifier_file.read())
        word_classifier_file.close()
        #Set up window
        self.setTitle("HandReco Writer")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setLayout(BorderLayout())
        #Set up menu
        menu_bar = JMenuBar()
        info_menu = JMenu("Info")

        def instructions(event):
            instr = '''
            The program can just recognise capital English characters.
            See Info -> Available Words... for available word corrections.
            
            Good Luck with the writing!'''
            JOptionPane.showMessageDialog(self, instr, "Instructions",
                                          JOptionPane.INFORMATION_MESSAGE)

        instructions_menu_item = JMenuItem("Instructions...",
                                           actionPerformed=instructions)
        info_menu.add(instructions_menu_item)

        def word_corrections(event):
            words_string = ""
            for word in self.word_classifier.words:
                words_string = words_string + word.upper() + "\n"
            text = "The words that can be corrected are:\n\n" + words_string
            dialog = JOptionPane(text, JOptionPane.INFORMATION_MESSAGE)
            dialog_wrapper = JDialog(self, "Available Words", False)
            dialog_wrapper.setContentPane(dialog)
            dialog_wrapper.pack()
            dialog_wrapper.setVisible(True)

        word_corrections_menu_item = JMenuItem(
            "Available Words...", actionPerformed=word_corrections)
        info_menu.add(word_corrections_menu_item)
        menu_bar.add(info_menu)
        self.setJMenuBar(menu_bar)
        #Input panel
        input_panel = JPanel()
        input_panel.setLayout(BoxLayout(input_panel, BoxLayout.X_AXIS))
        input_panel.setBorder(BorderFactory.createTitledBorder("Input"))
        self.paint_area = PaintArea(100, 100)
        input_panel.add(self.paint_area)
        input_options_panel = JPanel()
        input_options_panel.setLayout(
            BoxLayout(input_options_panel, BoxLayout.Y_AXIS))
        #Write Char
        write_char_panel = JPanel(BorderLayout())

        def write_char(event):
            char = self.character_classifier.classify_image(
                self.paint_area.image())
            self.text_area.setText(self.text_area.getText() + char)
            self.paint_area.clear()

        write_char_panel.add(JButton("Write Char", actionPerformed=write_char),
                             BorderLayout.NORTH)
        input_options_panel.add(write_char_panel)
        #Space and Correct
        space_and_correct_panel = JPanel(BorderLayout())

        def space_and_correct(event):
            text = self.text_area.getText()
            words = text.split(" ")
            string = words[-1]
            try:
                word = self.word_classifier.classify(string.lower())
                words[-1] = word.upper()
            except:
                JOptionPane.showMessageDialog(
                    self,
                    "Have you entered a character which is not in the alphabet?",
                    "Could not Correct", JOptionPane.ERROR_MESSAGE)
                self.text_area.setText(text + " ")
                return
            newText = ""
            for w in words:
                newText = newText + w + " "
            self.text_area.setText(newText)

        space_and_correct_panel.add(
            JButton("Space and Correct", actionPerformed=space_and_correct),
            BorderLayout.NORTH)
        input_options_panel.add(space_and_correct_panel)
        #Space
        space_panel = JPanel(BorderLayout())

        def space(event):
            self.text_area.setText(self.text_area.getText() + " ")

        space_panel.add(JButton("Space", actionPerformed=space),
                        BorderLayout.NORTH)
        input_options_panel.add(space_panel)
        #Clear Input Area
        clear_input_area_panel = JPanel(BorderLayout())

        def clear(event):
            self.paint_area.clear()

        clear_input_area_panel.add(
            JButton("Clear Input Area", actionPerformed=clear),
            BorderLayout.NORTH)
        input_options_panel.add(clear_input_area_panel)
        input_panel.add(input_options_panel)
        self.add(input_panel, BorderLayout.NORTH)
        text_area_panel = JPanel()
        text_area_panel.setLayout(BorderLayout())
        text_area_panel.setBorder(BorderFactory.createTitledBorder("Text"))
        self.text_area = JTextArea()
        self.text_area.setLineWrap(True)
        #Increase font size
        font = self.text_area.getFont()
        self.text_area.setFont(Font(font.getName(), Font.BOLD, 24))

        text_area_panel.add(JScrollPane(self.text_area), BorderLayout.CENTER)
        self.add(text_area_panel, BorderLayout.CENTER)
        self.pack()
        self.setSize(Dimension(300, 300))
        self.setVisible(True)