Exemplo n.º 1
0
 def init(self):
     self.getContext().addPropertyChangeListener(
         self)  #ThrottleFrame change
     self.addressPanel = self.getContext().getCurrentThrottleFrame(
     ).getAddressPanel()
     self.addressPanel.addAddressListener(
         self)  # change of throttle in Current frame
     self.throttle = self.getContext().getCurrentThrottleFrame(
     ).getAddressPanel().getThrottle()  # the throttle
     self.speedAction = SpeedAction()  #Speed increase thread
     self.speedAction.setThrottle(self.throttle)
     self.speedTimer = Timer(
         valueSpeedTimerRepeat, self.speedAction
     )  # Very important to use swing Timer object (see Swing and multithreading doc)
     self.speedTimer.setRepeats(True)
     self.label = JButton(
         ImageIcon(self.getFolder() + "/WiimoteThrottle2.png",
                   "WiiMote"))  #label
     self.label.addMouseListener(
         self.getMouseListeners()
         [0])  # In order to get the popupmenu on the button too
     self.add(self.label)
     self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis()
     self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis()
     self.advFunctions = AdvFunctions()
     self.lastTimeEStop = Calendar.getInstance().getTimeInMillis()
     self.wiiDevice = None
     self.sync = thread.allocate_lock()  # A lock protecting bellow self.evt
     self.evt = None
     java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true")
     # Required for Bluecove + WiiRemoteJ
     WiiRemoteJ.findRemotes(self, 1)  # Search for 1 Wiimote, and call back
Exemplo n.º 2
0
 def init(self):
     self.getContext().addPropertyChangeListener(self) #ThrottleFrame change
     self.getContext().getCurrentThrottleFrame().getAddressPanel().addAddressListener(self) # change of throttle in Current frame
     self.addressPanel = self.getContext().getCurrentThrottleFrame().getAddressPanel()
     self.throttle = self.addressPanel.getThrottle() # the throttle
     self.roster = self.addressPanel.getRosterEntry() # roster entry if any
     self.speedAction =  SpeedAction()  #Speed increase thread
     self.speedAction.setThrottle( self.throttle )
     self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc)
     self.speedTimer.setRepeats(True)
     self.label = JButton(ImageIcon(self.getFolder() + "/USBControl.png","USBThrottle")) #label
     self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too
     self.add(self.label)
     self.model = jmri.jmrix.jinput.TreeModel.instance() # USB
     self.desiredController = None
     self.ctrlMenuItem = []
     self.USBDriver = None
     self.driver = None
     mi = JCheckBoxMenuItem ("None")
     self.getPopUpMenu().add( mi )
     mi.addItemListener( ControllerItemListener(None, self) )
     self.ctrlMenuItem.append(mi)
     for ctrl in self.model.controllers(): 
         mi = JCheckBoxMenuItem (ctrl.getName())
         self.getPopUpMenu().add( mi )
         mi.addItemListener( ControllerItemListener(ctrl, self) )
         self.ctrlMenuItem.append(mi)
     if ( len(self.ctrlMenuItem) == 0 ):
         print "No matching USB device found"
     else:
         self.ctrlMenuItem[0].setSelected(True)  # by default connect to the first one
     self.model.addPropertyChangeListener(self)
     self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis()
     self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis()
Exemplo n.º 3
0
 def __init__(self, timeInterval, function, parameters=[], repeat=True):
    """Specify time interval (in milliseconds), which function to call when the time interval has passed
       and the parameters to pass this function, and whether to repeat (True) or do it only once."""
       
    self.timeListener = TimerListener(function, parameters)    # define the timer event listener and provide function and parameters to be called 
    
    JTimer.__init__(self, int(timeInterval), self.timeListener)
    self.setRepeats( repeat )      # should we do this once or forever? 
Exemplo n.º 4
0
class Example(JFrame, ActionListener):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()
        
# Paint all of the objects in screenObjects
    def mypaint(self, g):
        for object in screenObjects:
            object._draw(g) #Now calls a _draw method on each object, instead of just having a bunch of lambdas in screenObjects.
            
# Add an external event on a mouse click
    def myclick(self, x, y):
        externalEvents['LeftMouseButton'] = SP2(x, y)   #SP2 inherited from pythonfrp StaticNumerics.py 
    
    def mykey(self, k):
        externalEvents['KeyTyped']=string(k)
#        print("Key Pressed: " + string(k))

    def my_move(self, x, y):
        mouse_pos[0]= SP2(x,y)

    def initUI(self):
        self.addKeyListener(KA(lambda k: self.mykey(k)))
        self.xp=0
        self.yp=0
        self.canvas=Canvas(lambda g:self.mypaint(g), lambda x, y: self.myclick(x, y), lambda x, y: self.my_move(x, y))
        self.canvas.setBackground(Color(200, 200, 200))
        self.getContentPane().add(self.canvas)
        self.setTitle("Test")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(500, 500)
        self.setLocationRelativeTo(None)
        self.setBackground(Color(255, 255, 255))
        self.setVisible(True)
        self.timer=Timer(50, self)
        self.timer.start()

# This is the heartbeat handling code - this is attached to a timer in the frame      

    def actionPerformed(self, e):
        currentTime=System.currentTimeMillis()
        rSide = random.randrange(0,4)
        if ((currentTime-startTime[0]) % 5 == 0):
            if (rSide == 0):
                (circle(p2(random.randrange(50,450),-30+localTime*100), 10))
            elif (rSide == 1):
                (circle(p2(500-localTime*100, random.randrange(50,450)), 10))
            elif (rSide == 2):
                (circle(p2(random.randrange(50,450),500-localTime*100), 10))
            else:
                (circle(p2(-30+localTime*100,random.randrange(50,450)), 10))
        del screenObjects[:]
#        print(currentTime-startTime[0])
#        print('Objects: ' + str(Globals.worldObjects))
        heartbeat((currentTime - startTime[0]) / 1000.0, externalEvents)
        externalEvents.clear()
        self.repaint()
    class WindowClose(ActionListener):
        def __init__(self):
            from javax.swing import Timer
            self.timer = Timer(5000, self)
            self.timer.start()

        def actionPerformed(self, e):
            self.timer.stop()
            mframe.dispose()
Exemplo n.º 6
0
    def __init__(self, timeInterval, function, parameters=[], repeat=True):
        """Specify time interval (in milliseconds), which function to call when the time interval has passed
         and the parameters to pass this function, and whether to repeat (True) or do it only once."""

        self.timeListener = TimerListener(
            function, parameters
        )  # define the timer event listener and provide function and parameters to be called

        JTimer.__init__(self, int(timeInterval), self.timeListener)
        self.setRepeats(repeat)  # should we do this once or forever?
Exemplo n.º 7
0
   def __init__(self, timeInterval, function, parameters=[], repeat=True):
      """Specify time interval (in milliseconds), which function to call when the time interval has passed
         and the parameters to pass this function, and whether to repeat (True) or do it only once."""

      self.timeListener = TimerListener(function, parameters)    # define the timer event listener and provide function and parameters to be called

      JSwing_Timer.__init__(self, int(timeInterval), self.timeListener)
      self.setRepeats( repeat )      # should we do this once or forever?

      # remember that this timer has been created and is active (so that it can be stopped/terminated by JEM, if desired)
      __ActiveTimers__.append(self)
Exemplo n.º 8
0
 def __init__(self, timeInterval, function, parameters=[], repeat=True):
    """Specify time interval (in milliseconds), which function to call when the time interval has passed
       and the parameters to pass this function, and whether to repeat (True) or do it only once."""
       
    self.timeListener = TimerListener(function, parameters)    # define the timer event listener and provide function and parameters to be called 
    
    JTimer.__init__(self, int(timeInterval), self.timeListener)
    self.setRepeats( repeat )      # should we do this once or forever? 
    
    # remember that this timer has been created and is active (so that it can be stopped/terminated by JEM, if desired)
    __ActiveTimers__.append(self)
Exemplo n.º 9
0
    def __init__(self, extender):
        self._syncTimer = Timer(1000, None)
        self._syncTimer.setRepeats(True)
        self._syncTimer.actionPerformed = self._sendCommandSync
        self._syncTimer.stop()

        self.commandListenPort = 8089;

        self._startTimer = Timer(1000, None)
        self._startTimer.setInitialDelay(1500)
        self._startTimer.setRepeats(False)
        self._startTimer.actionPerformed = self._sendCommandStart
        self._startTimer.stop()

        self._extender = extender
Exemplo n.º 10
0
class Example(JFrame, ActionListener):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

# Paint all of the objects in screenObjects

    def mypaint(self, g):
        for object in screenObjects:
            object(g)

# Add an external event on a mouse click

    def myclick(self, x, y):
        externalEvents['LeftMouseButton'] = SP2(
            x, y)  #SP2 inherited from pythonfrp StaticNumerics.py

    def mykey(self, k):
        externalEvents['KeyTyped'] = string(k)

    def initUI(self):
        self.addKeyListener(KA(lambda k: k))
        self.xp = 0
        self.yp = 0
        self.canvas = Canvas(lambda g: self.mypaint(g),
                             lambda x, y: self.myclick(x, y))
        self.canvas.setBackground(Color(200, 200, 100))
        self.getContentPane().add(self.canvas)
        self.setTitle("Ball")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(300, 300)
        self.setLocationRelativeTo(None)
        self.setBackground(Color(255, 255, 255))
        self.setVisible(True)
        self.timer = Timer(50, self)
        self.timer.start()

# This is the heartbeat handling code - this is attached to a timer in the frame

    def actionPerformed(self, e):
        currentTime = System.currentTimeMillis()
        del screenObjects[:]
#        print(currentTime-startTime[0])
#        print('Objects: ' + str(Globals.worldObjects))

    heartbeat((currentTime - startTime[0]) / 1000.0, externalEvents)
    externalEvents.clear()
    self.repaint()
Exemplo n.º 11
0
    def __init__(self, view, name, func, args=(), filter=None, label=None):
        core.DataViewComponent.__init__(self, label)
        self.view = view
        self.name = name
        self.func = func
        self.indices = None
        self.data = self.view.watcher.watch(name, func, args=args)
        self.margin = 10

        self.autozoom = True
        self.last_maxy = None
        self.popup_zoom = JCheckBoxMenuItem('auto-zoom', self.autozoom, stateChanged=self.toggle_autozoom)
        self.popup.add(self.popup_zoom)

        self.autohide = True
        self.show_axes_labels = True
        self.popup_hide = JCheckBoxMenuItem('auto-hide axis labels', True, actionPerformed=self.toggle_autohide)
        self.popup.add(self.popup_hide)

        self.axes_label_init_clr = 0.3
        self.axes_label_clr_val = self.axes_label_init_clr
        self.axes_label_clr_step = (1 - self.axes_label_init_clr) / 10

        self.axes_label_hide_dly = 1000
        self.axes_label_hide_tmr = Timer(self.axes_label_hide_dly / 10, None, actionPerformed=self.fade_axes_labels)

        self.filter = filter
        self.setSize(200, 200)
Exemplo n.º 12
0
 def initUI(self):
     self.addKeyListener(KA(lambda k: k))
     self.xp = 0
     self.yp = 0
     self.canvas = Canvas(lambda g: self.mypaint(g),
                          lambda x, y: self.myclick(x, y))
     self.canvas.setBackground(Color(200, 200, 100))
     self.getContentPane().add(self.canvas)
     self.setTitle("Ball")
     self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     self.setSize(300, 300)
     self.setLocationRelativeTo(None)
     self.setBackground(Color(255, 255, 255))
     self.setVisible(True)
     self.timer = Timer(50, self)
     self.timer.start()
Exemplo n.º 13
0
 def init(self):
     self.getContext().addPropertyChangeListener(self) #ThrottleFrame change
     self.getContext().getCurrentThrottleFrame().getAddressPanel().addAddressListener(self) # change of throttle in Current frame
     self.addressPanel = self.getContext().getCurrentThrottleFrame().getAddressPanel()
     self.throttle = self.addressPanel.getThrottle() # the throttle
     self.roster = self.addressPanel.getRosterEntry() # roster entry if any
     self.speedAction =  SpeedAction()  #Speed increase thread
     self.speedAction.setThrottle( self.throttle )
     self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc)
     self.speedTimer.setRepeats(True)
     self.label = JButton(ImageIcon(self.getFolder() + "/USBControl.png","USBThrottle")) #label
     self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too
     self.add(self.label)
     self.model = jmri.jmrix.jinput.TreeModel.instance() # USB
     self.desiredController = None
     self.ctrlMenuItem = []
     self.USBDriver = None
     self.driver = None
     mi = JCheckBoxMenuItem ("None")
     self.getPopUpMenu().add( mi )
     mi.addItemListener( ControllerItemListener(None, self) )
     self.ctrlMenuItem.append(mi)
     for ctrl in self.model.controllers(): 
         mi = JCheckBoxMenuItem (ctrl.getName())
         self.getPopUpMenu().add( mi )
         mi.addItemListener( ControllerItemListener(ctrl, self) )
         self.ctrlMenuItem.append(mi)
     if ( len(self.ctrlMenuItem) == 0 ):
         print "No matching USB device found"
     else:
         self.ctrlMenuItem[0].setSelected(True)  # by default connect to the first one
     self.model.addPropertyChangeListener(self)
     self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis()
     self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis()
Exemplo n.º 14
0
class LifeGame(object):
    def __init__(self, numRows, numCols):
        self.numRows = numRows
        self.numCols = numCols
        self.timer = Timer(250, None, actionPerformed=self._step)
        self.gridMutator = GridMutator()

    def startGui(self):
        frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self.gridPanel = JPanel(GridLayout(self.numRows, self.numCols))
        self.cellButtons = self._doForAllCells(self._createCellButton)
        self.grid = self._doForAllCells(lambda r, c: False)
        frame.add(self.gridPanel)
        buttonPanel = JPanel(FlowLayout())
        stepButton = JButton("Step", actionPerformed=self._step)
        runButton = JToggleButton("Run", actionPerformed=self._run)
        buttonPanel.add(stepButton)
        buttonPanel.add(runButton)
        frame.add(buttonPanel, SOUTH)
        frame.pack()
        frame.locationRelativeTo = None
        frame.visible = True

    def _step(self, event):
        self.grid = self.gridMutator.generateNext(
            self._doForAllCells(lambda r, c: self.cellButtons[r][c].selected))
        self._doForAllCells(self._selectCellButtonFromGrid)

    def _run(self, event):
        if self.timer.running:
            self.timer.stop()
        else:
            self.timer.start()

    def _createCellButton(self, r, c):
        button = JToggleButton()
        s = button.preferredSize
        button.preferredSize = (s.height, s.height)  # Make square
        self.gridPanel.add(button)
        return button

    def _doForAllCells(self, fn):
        return [[fn(r, c) for c in range(self.numCols)]
                for r in range(self.numRows)]

    def _selectCellButtonFromGrid(self, r, c):
        self.cellButtons[r][c].selected = self.grid[r][c]
Exemplo n.º 15
0
    def initGame(self):

        self.left = False
        self.right = True
        self.up = False
        self.down = False
        self.inGame = True
        self.dots = 3

        for i in range(self.dots):
            x[i] = 50 - i * 10
            y[i] = 50

        self.locateApple()

        self.timer = Timer(DELAY, self)
        self.timer.start()
Exemplo n.º 16
0
    def __init__(self, view, name, func, label=None):
        core.DataViewComponent.__init__(self, label)
        self.view = view
        self.name = name
        self.func = func
        self.label_height = 18
        self.resize_border = 2

        self.popup_hide_limit = JCheckBoxMenuItem('auto-hide limits', True, actionPerformed=self.toggle_autohide)
        self.popup.add(self.popup_hide_limit)
        self.show_limits = False
        self.auto_hide_limits = True
        self.limits_font = Font("Dialog", Font.PLAIN, 10)
        self.limit_width = 0
        self.limit_hide_delay = 1000
        self.limit_color_def = 0.3
        self.limit_color_val = self.limit_color_def
        self.limit_color_step = (1 - self.limit_color_def) / 10
        self.limit_hide_timer = Timer(self.limit_hide_delay / 10, None, actionPerformed=self.hide_limits)
        self.limit_hide_timer.setRepeats(False)

        self.popup.add(JPopupMenu.Separator())
        self.popup.add(JMenuItem('zero', actionPerformed=self.zero))
        self.popup.add(JMenuItem('set value', actionPerformed=self.set_value))

        self.filename = None
        self.popup.add(JMenuItem('set from file...', actionPerformed=self.set_from_file))

        self.popup.add(JPopupMenu.Separator())
        self.popup.add(JMenuItem('increase range', actionPerformed=self.increase_range))
        self.popup.add(JMenuItem('decrease range', actionPerformed=self.decrease_range))
        self.scale_factor = 0.01
        self.range = 1.0

        self.data = self.view.watcher.watch(name, func)

        values = self.data.get_first()
        self.sliders = []
        self.labels = []
        for i, v in enumerate(values):
            vv = int(v * 100 / self.range)
            if vv > 100:
                vv = 100
            if vv < -100:
                vv = -100
            slider = JSlider(JSlider.VERTICAL, -100, 100, vv, stateChanged=lambda event, index=i: self.slider_moved(index))
            slider.background = Color.white
            self.add(slider)
            self.sliders.append(slider)
            label = JLabel('0.00')
            self.add(label)
            self.labels.append(label)
            slider.addMouseListener(self)

        self.setSize(len(values) * 40 + 40, 200)
        self.addComponentListener(self)
        self.componentResized(None)
Exemplo n.º 17
0
 def __init__(self, delay):
     self.frame = JFrame("SVT Monitor", \
                         windowClosing = lambda event: sys.exit(0))
     self.grid = GridLayout(2, 4)
     self.pane = self.frame.contentPane
     self.pane.layout = self.grid
     self.buttonList = map(lambda x: JButton("b0svt0" + `x`), \
                                  [0,7,6,5,1,2,3,4]) # Left to right,
     # top to bottom
     for button in self.buttonList:
         button.actionCommand = button.text
         button.addActionListener(self)
         self.pane.add(button)
     self.crateMonitorList = []
     self.frame.pack()
     self.frame.visible = 1
     self.timer = Timer(delay, self)
     self.timer.start()
Exemplo n.º 18
0
class LifeGame(object):
    def __init__(self, numRows, numCols):
        self.numRows = numRows
        self.numCols = numCols
        self.timer = Timer(250, None, actionPerformed=self._step)

    def startGui(self):
        frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        (R, C) = (self.numRows, self.numCols)
        gridPanel = JPanel(GridLayout(R, C))
        self.checkBoxes = [[JCheckBox() for c in range(C)] for r in range(R)]
        self.grid = [[False for c in range(C)] for r in range(R)]
        for r in range(R):
            for c in range(C):
                gridPanel.add(self.checkBoxes[r][c])
        frame.add(gridPanel)
        buttonPanel = JPanel(FlowLayout())
        stepButton = JButton("Step", actionPerformed=self._step)
        runButton = JToggleButton("Run", actionPerformed=self._run)
        buttonPanel.add(stepButton)
        buttonPanel.add(runButton)
        frame.add(buttonPanel, SOUTH)
        frame.pack()
        frame.locationRelativeTo = None
        frame.visible = True

    def _getGridFromCheckBoxes(self):
        return [[self.checkBoxes[r][c].selected for c in range(self.numCols)]
                for r in range(self.numRows)]

    def _step(self, event):
        self.grid = GridMutator().generateNext(self._getGridFromCheckBoxes())
        self._selectCheckBoxesFromGrid()

    def _run(self, event):
        if self.timer.running:
            self.timer.stop()
        else:
            self.timer.start()

    def _selectCheckBoxesFromGrid(self):
        for r in range(self.numRows):
            for c in range(self.numCols):
                self.checkBoxes[r][c].selected = self.grid[r][c]
Exemplo n.º 19
0
class LifeGame(object):
    def __init__(self, numRows, numCols):
        self.numRows = numRows
        self.numCols = numCols
        self.timer = Timer(250, None, actionPerformed=self._step)

    def startGui(self):
        frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        (R, C) = (self.numRows, self.numCols)
        gridPanel = JPanel(GridLayout(R, C))
        self.checkBoxes = [[JCheckBox() for c in range(C)] for r in range(R)]
        self.grid = [[False for c in range(C)] for r in range(R)]
        for r in range(R):
            for c in range(C):
                gridPanel.add(self.checkBoxes[r][c])
        frame.add(gridPanel)
        buttonPanel = JPanel(FlowLayout())
        stepButton = JButton("Step", actionPerformed=self._step)
        runButton = JToggleButton("Run", actionPerformed=self._run)
        buttonPanel.add(stepButton)
        buttonPanel.add(runButton)
        frame.add(buttonPanel, SOUTH)
        frame.pack()
        frame.locationRelativeTo = None
        frame.visible = True

    def _getGridFromCheckBoxes(self):
        return [[self.checkBoxes[r][c].selected for c in range(self.numCols)]
            for r in range(self.numRows)]

    def _step(self, event):
        self.grid = GridMutator().generateNext(self._getGridFromCheckBoxes())
        self._selectCheckBoxesFromGrid()

    def _run(self, event):
        if self.timer.running:
            self.timer.stop()
        else:
            self.timer.start()

    def _selectCheckBoxesFromGrid(self):
        for r in range(self.numRows):
            for c in range(self.numCols):
                self.checkBoxes[r][c].selected = self.grid[r][c]
Exemplo n.º 20
0
class svtMonitor(ActionListener):
    def __init__(self, delay):
        self.frame = JFrame("SVT Monitor", \
                            windowClosing = lambda event: sys.exit(0))
        self.grid = GridLayout(2, 4)
        self.pane = self.frame.contentPane
        self.pane.layout = self.grid
        self.buttonList = map(lambda x: JButton("b0svt0" + `x`), \
                                     [0,7,6,5,1,2,3,4]) # Left to right,
        # top to bottom
        for button in self.buttonList:
            button.actionCommand = button.text
            button.addActionListener(self)
            self.pane.add(button)
        self.crateMonitorList = []
        self.frame.pack()
        self.frame.visible = 1
        self.timer = Timer(delay, self)
        self.timer.start()

    def actionPerformed(self, event):
        crate = event.getActionCommand()
        if crate == None:  # it's the timer
            self.update()
        else:  # the user pushed a button
            if __debug__:
                print "%s pushed" % crate
            crateList = map(lambda x, self=self: x.crate,
                            self.crateMonitorList)
            if not crate in crateList:  # Do not open the same crate more than once
                if __debug__:
                    print "%s opening" % crate
                self.crateMonitorList.append(
                    crateMonitor(event.getActionCommand(), mainWindow=self))

    def delete(self, crate):
        crate.close()
        self.crateMonitorList.remove(crate)

    def update(self):
        if __debug__:
            print "big update"
        for crate in self.crateMonitorList:
            crate.update()
Exemplo n.º 21
0
Arquivo: time.py Projeto: jggatc/pyj2d
class _EventTimer(ActionListener):
    timers = {}

    def __init__(self, eventid):
        self.event = pyj2d.event.Event(eventid)
        self.timer = Timer(0, self)

    def set_timer(self, time):
        if self.timer.isRunning():
            self.timer.stop()
        if time:
            self.timer.setInitialDelay(time)
            self.timer.setDelay(time)
            self.timer.start()

    def actionPerformed(self, evt):
        pyj2d.event.post(self.event)
Exemplo n.º 22
0
class Example(JFrame, ActionListener):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

# Paint all of the objects in screenObjects
    def mypaint(self, g):
        for object in screenObjects:
            object(g)
            
# Add an external event on a mouse click
    def myclick(self, x, y):
        externalEvents['LeftMouseButton'] = SP2(x, y)   #SP2 inherited from pythonfrp StaticNumerics.py
    def mykey(self, k):
        externalEvents['KeyTyped'] = string(k)

    def initUI(self):
        self.addKeyListener(KA(lambda k: k))
        self.xp = 0
        self.yp = 0
        self.canvas = Canvas(lambda g:self.mypaint(g), lambda x, y: self.myclick(x, y))
        self.canvas.setBackground(Color(200, 200, 100))
        self.getContentPane().add(self.canvas)
        self.setTitle("Ball")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(300, 300)
        self.setLocationRelativeTo(None)
        self.setBackground(Color(255, 255, 255))
        self.setVisible(True)
        self.timer = Timer(50, self)
        self.timer.start()

# This is the heartbeat handling code - this is attached to a timer in the frame      
    def actionPerformed(self, e):
        currentTime = System.currentTimeMillis()
        del screenObjects[:]
#        print(currentTime-startTime[0])
#        print('Objects: ' + str(Globals.worldObjects))
    heartbeat((currentTime - startTime[0]) / 1000.0, externalEvents)
    externalEvents.clear()
    self.repaint()
Exemplo n.º 23
0
        def init(self, aName, aDevice, aAllowedStates, aLogFile, aParent):
            from javax.swing import Timer
            #print ('TrackDevice.init ' + aName )
            self.DeviceName = aName
            self.Device = aDevice
            self.DeviceValue = self.Device.getValue()
            self.AllowedStates = aAllowedStates
            self.parent = aParent
            self.LogFile = aLogFile

            self.timeoutListener = self.TimeoutReceiver()
            self.timeoutListener.setCallBack(self.receiveTimeoutHandler)
            self.receiveTimer = Timer(1, self.timeoutListener)
            self.receiveTimer.stop()
            self.receiveTimer.setRepeats(False)

            self.sendTimeoutListener = self.TimeoutReceiver()
            self.sendTimeoutListener.setCallBack(self.sendTimeoutHandler)
            self.sendTimer = Timer(1, self.sendTimeoutListener)
            self.sendTimer.stop()
            self.sendTimer.setRepeats(False)

            self.pauseTimeoutListener = self.TimeoutReceiver()
            self.pauseTimeoutListener.setCallBack(self.pauseTimeoutHandler)
            self.pauseTimer = Timer(1, self.pauseTimeoutListener)
            self.pauseTimer.stop()
            self.pauseTimer.setRepeats(False)

            self.relayClicks = jmri.jmrit.Sound(
                "resources/sounds/Code-receive.wav")
            #self.relayClicks = jmri.jmrit.Sound(jmri.util.FileUtil.getExternalFilename("preference:resources/sounds/EnhancedCTCRelay.wav"))
            self.relaySend = jmri.jmrit.Sound("resources/sounds/Code-send.wav")

            return
        def init(self, aName, aDevice, aAllowedStates, aLogFile, aParent):
            from javax.swing import Timer
            self.DeviceName = aName
            self.Device = aDevice
            self.DeviceNumber = self.DeviceName[2:self.DeviceName.find(":")]
            self.AllowedStates = aAllowedStates
            self.parent = aParent
            self.DeviceValue = self.AllowedStates[0]
            self.LogFile = aLogFile

            self.timeoutListener = self.TimeoutReceiver()
            self.timeoutListener.setCallBack(self.receiveTimeoutHandler)

            self.receiveTimer = Timer(100, self.timeoutListener)
            self.receiveTimer.setInitialDelay(10)

            self.receiveTimer.stop()
            self.receiveTimer.setRepeats(False)

            self.sendTimeoutListener = self.TimeoutReceiver2()
            self.sendTimeoutListener.setCallBack(self.sendTimeoutHandler)

            self.sendTimer = Timer(100, self.timeoutListener)
            self.sendTimer.setInitialDelay(10)
            self.sendTimer.stop()
            self.sendTimer.setRepeats(False)

            self.pauseTimeoutListener = self.TimeoutReceiver()
            self.pauseTimeoutListener.setCallBack(self.pauseTimeoutHandler)

            self.pauseTimer = Timer(100, self.pauseTimeoutListener)
            self.pauseTimer.setInitialDelay(10)

            self.pauseTimer.stop()
            self.pauseTimer.setRepeats(False)

            self.finalTimeoutListener = self.TimeoutReceiver()
            self.finalTimeoutListener.setCallBack(self.finalTimeoutHandler)
            self.finalTimer = Timer(100, self.finalTimeoutListener)
            self.finalTimer.setInitialDelay(10)
            self.finalTimer.stop()
            self.finalTimer.setRepeats(False)

            #            self.relayClicks = jmri.jmrit.Sound(jmri.util.FileUtil.getExternalFilename("preference:resources/sounds/EnhancedCTCRelayTrimmed.wav"))
            self.relayClicks = jmri.jmrit.Sound(
                "resources/sounds/Code-receive.wav")
            self.relaySend = jmri.jmrit.Sound("resources/sounds/Code-send.wav")

            return
Exemplo n.º 25
0
    def initUI(self):
        self.addKeyListener(KA(lambda k: self.mykey(k)))
        self.xp = 0
        self.yp = 0
        self.canvas = Canvas(lambda g: self.mypaint(g),
                             lambda x, y: self.myclick(x, y),
                             lambda x, y: self.my_move(x, y))
        self.canvas.setBackground(JavaColor(200, 200, 100))
        self.getContentPane().add(self.canvas)
        self.setTitle("Test")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.xSize = 500
        self.ySize = 500
        self.setSize(self.xSize, self.ySize)
        self.setLocationRelativeTo(None)
        self.setBackground(JavaColor(255, 255, 255))
        self.setVisible(True)

        #self.button = JButton("This is a button")
        #self.add(self.button, BorderLayout.SOUTH)
        #self.button.addActionListener(self)

        self.timer = Timer(50, self)
        self.timer.start()
Exemplo n.º 26
0
 def init(self):
     """ generated source for method init """
     setSize(500, 500)
     addMouseListener(self)
     addMouseMotionListener(self)
     # initialize the biped to a valid state:
     state = [
         0.463, 0.98, 0.898, -0.229, 0.051, 0.276, -0.221, -1.430, -0.217,
         0.086, 0.298, -3.268, -0.601, 3.167, 0.360, 0.697, 0.241, 3.532
     ]
     self.bip7.setState(state)
     delay = 1
     # milliseconds
     taskPerformer = ActionListener()
     self.timer = Timer(delay, taskPerformer)
     self.timer.start()
     self.tempBuffer = BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB)
     initComponents()
     self.con = Controller()
     self.con.addWalkingController()
     self.con.addRunningController()
     self.con.addCrouchWalkController()
     self.addKeyListener(self)
     self.requestFocus()
Exemplo n.º 27
0
 def initUI(self):
     self.addKeyListener(KA(lambda k: k))
     self.xp = 0
     self.yp = 0
     self.canvas = Canvas(lambda g:self.mypaint(g), lambda x, y: self.myclick(x, y))
     self.canvas.setBackground(Color(200, 200, 100))
     self.getContentPane().add(self.canvas)
     self.setTitle("Ball")
     self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     self.setSize(300, 300)
     self.setLocationRelativeTo(None)
     self.setBackground(Color(255, 255, 255))
     self.setVisible(True)
     self.timer = Timer(50, self)
     self.timer.start()
Exemplo n.º 28
0
    def initGame(self):

        self.left = False
        self.right = True
        self.up = False
        self.down = False
        self.inGame = True
        self.dots = 3

        for i in range(self.dots):
            x[i] = 50 - i * 10
            y[i] = 50


        self.locateApple()

        self.timer = Timer(DELAY, self)
        self.timer.start()
Exemplo n.º 29
0
 def init(self):
     self.getContext().addPropertyChangeListener(self) #ThrottleFrame change
     self.addressPanel=self.getContext().getCurrentThrottleFrame().getAddressPanel();
     self.addressPanel.addAddressListener(self) # change of throttle in Current frame
     self.throttle = self.getContext().getCurrentThrottleFrame().getAddressPanel().getThrottle() # the throttle
     self.speedAction =  SpeedAction()  #Speed increase thread
     self.speedAction.setThrottle( self.throttle )
     self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc)
     self.speedTimer.setRepeats(True)
     self.label = JButton(ImageIcon(self.getFolder() + "/WiimoteThrottle.png","WiiMote")) #label
     self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too
     self.add(self.label)
     self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis()
     self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis()
     self.lastTimeEStop = Calendar.getInstance().getTimeInMillis()
     self.wiiDevice = None
     self.sync = thread.allocate_lock() # A lock protecting bellow self.evt
     self.evt = None
     java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true"); # Required for Bluecove + WiiRemoteJ
     WiiRemoteJ.findRemotes(self, 1) # Search for 1 Wiimote, and call back
Exemplo n.º 30
0
 def initUI(self):
     self.addKeyListener(KA(lambda k: self.mykey(k)))
     self.xp=0
     self.yp=0
     self.canvas=Canvas(lambda g:self.mypaint(g), lambda x, y: self.myclick(x, y), lambda x, y: self.my_move(x, y))
     self.canvas.setBackground(JavaColor(200, 200, 100))
     self.getContentPane().add(self.canvas)
     self.setTitle("Test")
     self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     self.xSize = 500
     self.ySize = 500
     self.setSize(self.xSize, self.ySize)
     self.setLocationRelativeTo(None)
     self.setBackground(JavaColor(255, 255, 255))
     self.setVisible(True)
     
     #self.button = JButton("This is a button")
     #self.add(self.button, BorderLayout.SOUTH)
     #self.button.addActionListener(self)
     
     self.timer=Timer(50, self)
     self.timer.start()
Exemplo n.º 31
0
    def highlightTab(self):
        currentPane = self._splitpane
        previousPane = currentPane
        while currentPane and not isinstance(currentPane, JTabbedPane):
            previousPane = currentPane
            currentPane = currentPane.getParent()
        if currentPane:
            index = currentPane.indexOfComponent(previousPane)
            currentPane.setBackgroundAt(index, Color(0xff6633))

            class setColorBackActionListener(ActionListener):
                def actionPerformed(self, e):
                    currentPane.setBackgroundAt(index, Color.BLACK)

            timer = Timer(5000, setColorBackActionListener())
            timer.setRepeats(False)
            timer.start()
Exemplo n.º 32
0
The getMissiles() method returns the list of missiles. It is called from the Board class.
Board.java
package com.zetcode;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Board extends JPanel implements ActionListener {

    private final int ICRAFT_X = 40;
    private final int ICRAFT_Y = 60;
    private final int DELAY = 10;
    private Timer timer;
    private SpaceShip spaceShip;

    public Board() {

        initBoard();
    }

    private void initBoard() {

        addKeyListener(new TAdapter());
        setBackground(Color.BLACK);
        setFocusable(true);

        spaceShip = new SpaceShip(ICRAFT_X, ICRAFT_Y);

        timer = new Timer(DELAY, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        doDrawing(g);

        Toolkit.getDefaultToolkit().sync();
    }

    private void doDrawing(Graphics g) {

        Graphics2D g2d = (Graphics2D) g;
        
        g2d.drawImage(spaceShip.getImage(), spaceShip.getX(),
                spaceShip.getY(), this);

        List<Missile> missiles = spaceShip.getMissiles();

        for (Missile missile : missiles) {
            
            g2d.drawImage(missile.getImage(), missile.getX(),
                    missile.getY(), this);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        updateMissiles();
        updateSpaceShip();

        repaint();
    }

    private void updateMissiles() {

        List<Missile> missiles = spaceShip.getMissiles();

        for (int i = 0; i < missiles.size(); i++) {

            Missile missile = missiles.get(i);

            if (missile.isVisible()) {

                missile.move();
            } else {

                missiles.remove(i);
            }
        }
    }

    private void updateSpaceShip() {

        spaceShip.move();
    }

    private class TAdapter extends KeyAdapter {

        @Override
        public void keyReleased(KeyEvent e) {
            spaceShip.keyReleased(e);
        }

        @Override
        public void keyPressed(KeyEvent e) {
            spaceShip.keyPressed(e);
        }
    }
}
This is the Board class.
private void doDrawing(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;
    
    g2d.drawImage(spaceShip.getImage(), spaceShip.getX(),
            spaceShip.getY(), this);

    List<Missile> missiles = spaceShip.getMissiles();

    for (Missile missile : missiles) {
        
        g2d.drawImage(missile.getImage(), missile.getX(),
                missile.getY(), this);
    }
}
In the doDrawing() method, we draw the craft and all the available missiles.
private void updateMissiles() {

    List<Missile> missiles = spaceShip.getMissiles();

    for (int i = 0; i < missiles.size(); i++) {

        Missile missile = missiles.get(i);

        if (missile.isVisible()) {

            missile.move();
        } else {

            missiles.remove(i);
        }
    }
}
In the updateMissiles() method we parse all missiles from the missiles list. Depending on what the isVisible() method returns, we either move the missile or remove it from the container.
ShootingMissilesEx.java
package com.zetcode;

import java.awt.EventQueue;
import javax.swing.JFrame;

public class ShootingMissilesEx extends JFrame {

    public ShootingMissilesEx() {
        
        initUI();
    }
    
    private void initUI() {
        
        add(new Board());
        
        setSize(400, 300);
        setResizable(false);
        
        setTitle("Shooting missiles");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        
        EventQueue.invokeLater(() -> {
            ShootingMissilesEx ex = new ShootingMissilesEx();
            ex.setVisible(true);
        });
    }
}
Exemplo n.º 33
0
Arquivo: time.py Projeto: jggatc/pyj2d
 def __init__(self, eventid):
     self.event = pyj2d.event.Event(eventid)
     self.timer = Timer(0, self)
Exemplo n.º 34
0
class Simbicon(java, applet, Applet, MouseListener, MouseMotionListener,
               KeyListener):
    """ generated source for class Simbicon """
    bip7 = Bip7()
    gnd = Ground()
    Dt = 0.00005
    DtDisp = 0.0054
    timeEllapsed = 0

    # we'll use this buffered image to reduce flickering
    tempBuffer = BufferedImage()
    timer = Timer()

    # and the controller
    con = Controller()
    Md = float()
    Mdd = float()
    DesVel = 0

    # if this variable is set to true, the simulation will be running, otherwise it won't
    simFlag = False
    simButton = javax.swing.JButton()
    reset = javax.swing.JButton()
    panel = javax.swing.JPanel()
    speedSlider = javax.swing.JSlider()
    label = javax.swing.JLabel()
    shouldPanY = False

    def init(self):
        """ generated source for method init """
        setSize(500, 500)
        addMouseListener(self)
        addMouseMotionListener(self)
        # initialize the biped to a valid state:
        state = [
            0.463, 0.98, 0.898, -0.229, 0.051, 0.276, -0.221, -1.430, -0.217,
            0.086, 0.298, -3.268, -0.601, 3.167, 0.360, 0.697, 0.241, 3.532
        ]
        self.bip7.setState(state)
        delay = 1
        # milliseconds
        taskPerformer = ActionListener()
        self.timer = Timer(delay, taskPerformer)
        self.timer.start()
        self.tempBuffer = BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB)
        initComponents()
        self.con = Controller()
        self.con.addWalkingController()
        self.con.addRunningController()
        self.con.addCrouchWalkController()
        self.addKeyListener(self)
        self.requestFocus()

    def boundRange(self, value, min, max):
        """ generated source for method boundRange """
        if value < min:
            value = min
        if value > max:
            value = max
        return value

    # ////////////////////////////////////////////////////////
    #   PROC: wPDtorq()
    #   DOES: computes requires torque to move a joint wrt world frame
    # ////////////////////////////////////////////////////////
    def wPDtorq(self, torq, joint, dposn, kp, kd, world):
        """ generated source for method wPDtorq """
        joint_posn = self.bip7.State[4 + joint * 2]
        joint_vel = self.bip7.State[4 + joint * 2 + 1]
        if world:
            #  control wrt world frame? (virtual)
            joint_posn += self.bip7.State[4]
            #  add body tilt
            joint_vel += self.bip7.State[5]
            #  add body angular velocity
        torq[joint] = kp * (dposn - joint_posn) - kd * joint_vel

    # ////////////////////////////////////////////////////////
    #  PROC:  jointLimit()
    #  DOES:  enforces joint limits
    # ////////////////////////////////////////////////////////
    def jointLimit(self, torq, joint):
        """ generated source for method jointLimit """
        kpL = 800
        kdL = 80
        minAngle = self.con.jointLimit[0][joint]
        maxAngle = self.con.jointLimit[1][joint]
        currAngle = self.bip7.State[4 + joint * 2]
        currOmega = self.bip7.State[4 + joint * 2 + 1]
        if currAngle < minAngle:
            torq = kpL * (minAngle - currAngle) - kdL * currOmega
        elif currAngle > maxAngle:
            torq = kpL * (maxAngle - currAngle) - kdL * currOmega
        return torq

    def bip7WalkFsm(self, torq):
        """ generated source for method bip7WalkFsm """
        torsoIndex = 0
        rhipIndex = 1
        rkneeIndex = 2
        lhipIndex = 3
        lkneeIndex = 4
        rankleIndex = 5
        lankleIndex = 6
        worldFrame = [False, True, False, True, False, False, False]
        self.con.stateTime += self.Dt
        s = self.con.state[self.con.fsmState]
        computeMdMdd()
        n = 0
        while n < 7:
            target = self.boundRange(target, self.con.targetLimit[0][n],
                                     self.con.targetLimit[1][n])
            self.wPDtorq(torq, n, target, self.con.kp[n], self.con.kd[n],
                         worldFrame[n])
            n += 1
        self.con.advance(self.bip7)

    def bip7Control(self, torq):
        """ generated source for method bip7Control """
        body = 0
        stanceHip = int()
        swingHip = int()
        fallAngle = 60
        n = 0
        while n < 7:
            torq[n] = 0
            n += 1
        if not self.bip7.lostControl:
            self.bip7WalkFsm(torq)
        if self.con.state[self.con.fsmState].leftStance:
            stanceHip = 3
            swingHip = 1
        else:
            stanceHip = 1
            swingHip = 3
        if not self.con.state[self.con.fsmState].poseStance:
            torq[stanceHip] = -torq[body] - torq[swingHip]
        torq[0] = 0
        n = 1
        while n < 7:
            torq[n] = self.boundRange(torq[n], self.con.torqLimit[0][n],
                                      self.con.torqLimit[1][n])
            self.jointLimit(torq[n], n)
            n += 1

    def computeMdMdd(self):
        """ generated source for method computeMdMdd """
        stanceFootX = self.bip7.getStanceFootXPos(self.con)
        self.Mdd = self.bip7.State[1] - self.DesVel
        self.Md = self.bip7.State[0] - stanceFootX

    def initComponents(self):
        """ generated source for method initComponents """
        self.simButton = javax.swing.JButton()
        self.reset = javax.swing.JButton()
        self.panel = javax.swing.JPanel()
        self.label = javax.swing.JLabel()
        self.label.setText("Speed: ")
        self.speedSlider = javax.swing.JSlider()
        self.speedSlider.setMaximum(100)
        self.speedSlider.setMinimum(0)
        self.speedSlider.setToolTipText(
            "Adjust the speed of the simulation by adjusting this slider.")
        setLayout(BorderLayout())
        self.panel.setLayout(FlowLayout())
        add(self.panel, BorderLayout.NORTH)
        self.panel.add(self.label)
        self.panel.add(self.speedSlider)
        self.panel.add(self.simButton)
        self.panel.add(self.reset)
        self.speedSlider.addMouseListener(java.awt.event.MouseAdapter())
        self.simButton.setText("  Start  ")
        self.reset.setText("Reset")
        self.simButton.addActionListener(java.awt.event.ActionListener())
        self.reset.addActionListener(java.awt.event.ActionListener())

    def resetSimulation(self):
        """ generated source for method resetSimulation """
        self.bip7.resetBiped()
        self.con.stateTime = 0
        self.con.fsmState = 0
        self.con.currentGroupNumber = 0
        self.con.desiredGroupNumber = 0
        repaint()

    def runLoop(self):
        """ generated source for method runLoop """
        if self.simFlag == False:
            return
        self.timer.stop()
        i = 0
        while i < 200:
            self.bip7.computeGroundForces(self.gnd)
            self.bip7Control(self.bip7.t)
            self.bip7.runSimulationStep(self.Dt)
            self.timeEllapsed += self.Dt
            if self.timeEllapsed > self.DtDisp:
                self.update(self.getGraphics())
                self.timeEllapsed = 0
            i += 1
        self.timer.start()

    def update(self, g):
        """ generated source for method update """
        if g == None:
            return
        g2 = self.tempBuffer.getGraphics()
        g2.setColor(Color(255, 255, 255))
        g2.fillRect(0, 0, getSize().width - 1, getSize().height - 1)
        m = Matrix3x3.getTranslationMatrix(0, -300)
        m = m.multiplyBy(Matrix3x3.getScalingMatrix(float(100)))
        panX = self.bip7.State[0]
        panY = self.bip7.State[2]
        if self.shouldPanY == False:
            panY = 0
        m = m.multiplyBy(
            Matrix3x3.getTranslationMatrix(-panX + 1.5, -panY + 0.5))
        self.bip7.drawBiped(g2, m)
        self.gnd.draw(g2, m)
        g.drawImage(self.tempBuffer, 0, self.panel.getHeight(), self)
        self.panel.repaint()

    def paint(self, g):
        """ generated source for method paint """
        self.update(g)
        self.panel.repaint()

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

    def keyPressed(self, e):
        """ generated source for method keyPressed """
        if e.getKeyCode() == e.VK_LEFT:
            self.bip7.PushTime = 0.2
            self.bip7.PushForce = -60
        if e.getKeyCode() == e.VK_RIGHT:
            self.bip7.PushTime = 0.2
            self.bip7.PushForce = 60
        if e.getKeyChar() == 'r' or e.getKeyChar() == 'R':
            self.con.desiredGroupNumber = 1
        if e.getKeyChar() == 'w' or e.getKeyChar() == 'W':
            self.con.desiredGroupNumber = 0
        if e.getKeyChar() == 'c' or e.getKeyChar() == 'C':
            self.con.desiredGroupNumber = 2
        if e.getKeyChar() == '1':
            self.gnd.getFlatGround()
            self.resetSimulation()
        if e.getKeyChar() == '2':
            self.gnd.getComplexTerrain()
            self.resetSimulation()

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

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

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

    def mousePressed(self, e):
        """ generated source for method mousePressed """
        self.requestFocus()

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

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

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

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

    def destroy(self):
        """ generated source for method destroy """
        removeMouseListener(self)
        removeMouseMotionListener(self)

    def getAppletInfo(self):
        """ generated source for method getAppletInfo """
        return "Title: Simbicon\n" + "Author: Stelian Coros, Michiel van de Panne."
Exemplo n.º 35
0
class USBThrottle(Jynstrument, PropertyChangeListener, AddressListener):
    #Property listener part: USB value
    def propertyChange(self, event):
        # Customize bellow for throttles calls:
        if (event.propertyName == "Value"):  # USB
            if (event.oldValue.getController() == self.desiredController):
                component = event.oldValue.getComponent().toString()
                value = event.newValue
                # Uncomment bellow line to see component name and its value
                # print "Component",component,"value changed to",value
                try:
                    # Change current ThrottleFrame
                    if ((component == self.driver.componentNextThrottleFrame)
                            and
                        (value == self.driver.valueNextThrottleFrame)):  #NEXT
                        self.getContext().nextThrottleFrame()
                    if ((component
                         == self.driver.componentPreviousThrottleFrame) and
                        (value == self.driver.valuePreviousThrottleFrame)
                        ):  #PREVIOUS
                        self.getContext().previousThrottleFrame()
                    if ((component
                         == self.driver.componentNextRunningThrottleFrame) and
                        (value == self.driver.valueNextRunningThrottleFrame)
                        ):  #NEXT RUNNING
                        self.getContext().nextRunningThrottleFrame()
                    if ((component
                         == self.driver.componentPreviousRunningThrottleFrame)
                            and
                        (value == self.driver.valuePreviousRunningThrottleFrame
                         )):  #PREVIOUS RUNNING
                        self.getContext().previousRunningThrottleFrame()
                except AttributeError:
                    pass

                if (self.throttle == None):
                    try:
                        # Browse through roster
                        if ((component
                             == self.driver.componentNextRosterBrowse) and
                            (value == self.driver.valueNextRoster)):  #NEXT
                            selectedIndex = self.addressPanel.getRosterSelectedIndex(
                            )
                            self.addressPanel.setVisible(True)
                            self.addressPanel.setIcon(False)
                            self.addressPanel.setRosterSelectedIndex(
                                selectedIndex + 1)
                        if ((component
                             == self.driver.componentPreviousRosterBrowse) and
                            (value
                             == self.driver.valuePreviousRoster)):  #PREVIOUS
                            selectedIndex = self.addressPanel.getRosterSelectedIndex(
                            )
                            self.addressPanel.setVisible(True)
                            self.addressPanel.setIcon(False)
                            self.addressPanel.setRosterSelectedIndex(
                                selectedIndex - 1)
                    except AttributeError:
                        pass
                    try:
                        # Request a throttle
                        if ((component == self.driver.componentRosterSelect)
                                and (value == self.driver.valueRosterSelect)):
                            self.addressPanel.selectRosterEntry()
                    except AttributeError:
                        pass

                # From there; current throttle control, hence require a throttle
                if (self.throttle != None):
                    # Release current throttle
                    try:
                        if ((component == self.driver.componentThrottleRelease)
                                and
                            (value == self.driver.valueThrottleRelease)):
                            self.addressPanel.dispatchAddress()
                    except AttributeError:
                        pass

                    try:
                        # Speed - dynamic controler (joystick going back to neutral position)
                        if ((component == self.driver.componentSpeedIncrease)
                                or
                            (component == self.driver.componentSpeedDecrease)
                                or (component == self.driver.componentSpeed)):
                            if ((component
                                 == self.driver.componentSpeedIncrease) and
                                (value == self.driver.valueSpeedIncrease)):
                                self.speedAction.setSpeedIncrement(0.03)
                            if ((component
                                 == self.driver.componentSpeedDecrease) and
                                (value == self.driver.valueSpeedDecrease)):
                                self.speedAction.setSpeedIncrement(-0.03)
                            if (component == self.driver.componentSpeed):
                                try:
                                    self.vsd = valueSpeedDivider * self.driver.componentSpeedMultiplier
                                except AttributeError:
                                    self.vsd = valueSpeedDivider
                                self.speedAction.setSpeedIncrement(value /
                                                                   self.vsd)
                            if (abs(value) > self.driver.valueSpeedTrigger):
                                self.speedTimer.start()
                            else:
                                self.speedTimer.stop()
                    except AttributeError:
                        self.speedTimer.stop(
                        )  # just in case, stop it, really should never get there

                    try:
                        # Speed v2 - static controler (lever on RailDriver or AAR105)
                        if (component == self.driver.componentSpeedSet):
                            # negative is lever front, positive is lever back
                            # limit range to only positive side of lever
                            if (value < self.driver.valueSpeedSetMinValue):
                                value = self.driver.valueSpeedSetMinValue
                            if (value > self.driver.valueSpeedSetMaxValue):
                                value = self.driver.valueSpeedSetMaxValue
                            # convert fraction of input to speed step
                            self.throttle.setSpeedSetting(
                                (value - self.driver.valueSpeedSetMinValue) /
                                (self.driver.valueSpeedSetMaxValue -
                                 self.driver.valueSpeedSetMinValue))
                            print "Slider Speed:", self.controlPanel.getDisplaySlider(
                            )
                    except AttributeError:
                        pass
                    # Direction
                    try:
                        if ((component
                             == self.driver.componentDirectionForward) and
                            (value == self.driver.valueDirectionForward)):
                            self.throttle.setIsForward(True)
                        if ((component
                             == self.driver.componentDirectionBackward) and
                            (value == self.driver.valueDirectionBackward)):
                            self.throttle.setIsForward(False)
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentDirectionSwitch)
                                and
                            (value == self.driver.valueDirectionSwitch)):
                            self.throttle.setIsForward(
                                not self.throttle.getIsForward())
                    except AttributeError:
                        pass

                    # Speed presets
                    try:  # STOP
                        if ((component == self.driver.componentStopSpeed)
                                and (value == self.driver.valueStopSpeed)):
                            if (Calendar.getInstance().getTimeInMillis() -
                                    self.lastTimeStopButton < delay4doubleTap):
                                self.throttle.setSpeedSetting(
                                    EStopSpeed)  # EStop on double tap
                            else:
                                self.throttle.setSpeedSetting(speedStopSpeed)
                            self.lastTimeStopButton = Calendar.getInstance(
                            ).getTimeInMillis()
                    except AttributeError:
                        pass
                    try:  # EStop
                        if ((component == self.driver.componentEStopSpeed)
                                and (value == self.driver.valueEStopSpeed)):
                            self.throttle.setSpeedSetting(EStopSpeed)
                    except AttributeError:
                        pass
                    try:  # EStop
                        if ((component == self.driver.componentEStopSpeedBis)
                                and (value == self.driver.valueEStopSpeedBis)):
                            self.throttle.setSpeedSetting(EStopSpeed)
                    except AttributeError:
                        pass
                    try:  # SLOW
                        if ((component == self.driver.componentSlowSpeed)
                                and (value == self.driver.valueSlowSpeed)):
                            self.throttle.setSpeedSetting(speedSlowSpeed)
                    except AttributeError:
                        pass
                    try:  # CRUISE
                        if ((component == self.driver.componentCruiseSpeed)
                                and (value == self.driver.valueCruiseSpeed)):
                            if (Calendar.getInstance().getTimeInMillis() -
                                    self.lastTimeCruiseButton <
                                    delay4doubleTap):  # EStop on double tap
                                self.throttle.setSpeedSetting(
                                    speedMaxSpeed)  # Max speed on double tap
                            else:
                                self.throttle.setSpeedSetting(speedCruiseSpeed)
                            self.lastTimeCruiseButton = Calendar.getInstance(
                            ).getTimeInMillis()
                    except AttributeError:
                        pass
                    try:  # MAX
                        if ((component == self.driver.componentMaxSpeed)
                                and (value == self.driver.valueMaxSpeed)):
                            self.throttle.setSpeedSetting(speedMaxSpeed)
                    except AttributeError:
                        pass

                    # Functions
                    try:
                        if ((component == self.driver.componentF0)
                                and (value == self.driver.valueF0)):
                            self.throttle.setF0(not self.throttle.getF0())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(0))
                                and (component == self.driver.componentF0)
                                and (value == self.driver.valueF0Off)):
                            self.throttle.setF0(not self.throttle.getF0())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF1)
                                and (value == self.driver.valueF1)):
                            self.throttle.setF1(not self.throttle.getF1())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(1))
                                and (component == self.driver.componentF1)
                                and (value == self.driver.valueF1Off)):
                            self.throttle.setF1(not self.throttle.getF1())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF2)
                                and (value == self.driver.valueF2)):
                            self.throttle.setF2(not self.throttle.getF2())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(2))
                                and (component == self.driver.componentF2)
                                and (value == self.driver.valueF2Off)):
                            self.throttle.setF2(not self.throttle.getF2())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF3)
                                and (value == self.driver.valueF3)):
                            self.throttle.setF3(not self.throttle.getF3())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(3))
                                and (component == self.driver.componentF3)
                                and (value == self.driver.valueF3Off)):
                            self.throttle.setF3(not self.throttle.getF3())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF4)
                                and (value == self.driver.valueF4)):
                            self.throttle.setF4(not self.throttle.getF4())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(4))
                                and (component == self.driver.componentF4)
                                and (value == self.driver.valueF4Off)):
                            self.throttle.setF4(not self.throttle.getF4())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF5)
                                and (value == self.driver.valueF5)):
                            self.throttle.setF5(not self.throttle.getF5())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(5))
                                and (component == self.driver.componentF5)
                                and (value == self.driver.valueF5Off)):
                            self.throttle.setF5(not self.throttle.getF5())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF6)
                                and (value == self.driver.valueF6)):
                            self.throttle.setF6(not self.throttle.getF6())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(6))
                                and (component == self.driver.componentF6)
                                and (value == self.driver.valueF6Off)):
                            self.throttle.setF6(not self.throttle.getF6())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF7)
                                and (value == self.driver.valueF7)):
                            self.throttle.setF7(not self.throttle.getF7())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(7))
                                and (component == self.driver.componentF7)
                                and (value == self.driver.valueF7Off)):
                            self.throttle.setF7(not self.throttle.getF7())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF8)
                                and (value == self.driver.valueF8)):
                            self.throttle.setF8(not self.throttle.getF8())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(8))
                                and (component == self.driver.componentF8)
                                and (value == self.driver.valueF8Off)):
                            self.throttle.setF8(not self.throttle.getF8())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF9)
                                and (value == self.driver.valueF9)):
                            self.throttle.setF9(not self.throttle.getF9())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(9))
                                and (component == self.driver.componentF9)
                                and (value == self.driver.valueF9Off)):
                            self.throttle.setF9(not self.throttle.getF9())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF10)
                                and (value == self.driver.valueF10)):
                            self.throttle.setF10(not self.throttle.getF10())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(10))
                                and (component == self.driver.componentF10)
                                and (value == self.driver.valueF10Off)):
                            self.throttle.setF10(not self.throttle.getF10())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF11)
                                and (value == self.driver.valueF11)):
                            self.throttle.setF11(not self.throttle.getF11())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(11))
                                and (component == self.driver.componentF11)
                                and (value == self.driver.valueF11Off)):
                            self.throttle.setF11(not self.throttle.getF11())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF12)
                                and (value == self.driver.valueF12)):
                            self.throttle.setF12(not self.throttle.getF12())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(12))
                                and (component == self.driver.componentF12)
                                and (value == self.driver.valueF12Off)):
                            self.throttle.setF12(not self.throttle.getF12())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF13)
                                and (value == self.driver.valueF13)):
                            self.throttle.setF13(not self.throttle.getF13())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(13))
                                and (component == self.driver.componentF13)
                                and (value == self.driver.valueF13Off)):
                            self.throttle.setF13(not self.throttle.getF13())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF14)
                                and (value == self.driver.valueF14)):
                            self.throttle.setF14(not self.throttle.getF14())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(14))
                                and (component == self.driver.componentF14)
                                and (value == self.driver.valueF14Off)):
                            self.throttle.setF14(not self.throttle.getF14())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF15)
                                and (value == self.driver.valueF15)):
                            self.throttle.setF15(not self.throttle.getF15())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(15))
                                and (component == self.driver.componentF15)
                                and (value == self.driver.valueF15Off)):
                            self.throttle.setF15(not self.throttle.getF15())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF16)
                                and (value == self.driver.valueF16)):
                            self.throttle.setF16(not self.throttle.getF16())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(16))
                                and (component == self.driver.componentF16)
                                and (value == self.driver.valueF16Off)):
                            self.throttle.setF16(not self.throttle.getF16())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF17)
                                and (value == self.driver.valueF17)):
                            self.throttle.setF17(not self.throttle.getF17())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(17))
                                and (component == self.driver.componentF17)
                                and (value == self.driver.valueF17Off)):
                            self.throttle.setF17(not self.throttle.getF17())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF18)
                                and (value == self.driver.valueF18)):
                            self.throttle.setF18(not self.throttle.getF18())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(18))
                                and (component == self.driver.componentF18)
                                and (value == self.driver.valueF18Off)):
                            self.throttle.setF18(not self.throttle.getF18())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF19)
                                and (value == self.driver.valueF19)):
                            self.throttle.setF19(not self.throttle.getF19())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(19))
                                and (component == self.driver.componentF19)
                                and (value == self.driver.valueF19Off)):
                            self.throttle.setF19(not self.throttle.getF19())
                    except AttributeError:
                        pass

                    try:
                        if ((component == self.driver.componentF20)
                                and (value == self.driver.valueF20)):
                            self.throttle.setF20(not self.throttle.getF20())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(20))
                                and (component == self.driver.componentF20)
                                and (value == self.driver.valueF20Off)):
                            self.throttle.setF20(not self.throttle.getF20())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF21)
                                and (value == self.driver.valueF21)):
                            self.throttle.setF21(not self.throttle.getF21())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(21))
                                and (component == self.driver.componentF21)
                                and (value == self.driver.valueF21Off)):
                            self.throttle.setF21(not self.throttle.getF21())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF22)
                                and (value == self.driver.valueF22)):
                            self.throttle.setF22(not self.throttle.getF22())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(22))
                                and (component == self.driver.componentF22)
                                and (value == self.driver.valueF22Off)):
                            self.throttle.setF22(not self.throttle.getF22())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF23)
                                and (value == self.driver.valueF23)):
                            self.throttle.setF23(not self.throttle.getF23())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(23))
                                and (component == self.driver.componentF23)
                                and (value == self.driver.valueF23Off)):
                            self.throttle.setF23(not self.throttle.getF23())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF24)
                                and (value == self.driver.valueF24)):
                            self.throttle.setF24(not self.throttle.getF24())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(24))
                                and (component == self.driver.componentF24)
                                and (value == self.driver.valueF24Off)):
                            self.throttle.setF24(not self.throttle.getF24())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF25)
                                and (value == self.driver.valueF25)):
                            self.throttle.setF25(not self.throttle.getF25())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(25))
                                and (component == self.driver.componentF25)
                                and (value == self.driver.valueF25Off)):
                            self.throttle.setF25(not self.throttle.getF25())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF26)
                                and (value == self.driver.valueF26)):
                            self.throttle.setF26(not self.throttle.getF26())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(26))
                                and (component == self.driver.componentF26)
                                and (value == self.driver.valueF26Off)):
                            self.throttle.setF26(not self.throttle.getF26())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF27)
                                and (value == self.driver.valueF27)):
                            self.throttle.setF27(not self.throttle.getF27())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(27))
                                and (component == self.driver.componentF27)
                                and (value == self.driver.valueF27Off)):
                            self.throttle.setF27(not self.throttle.getF27())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF28)
                                and (value == self.driver.valueF28)):
                            self.throttle.setF28(not self.throttle.getF28())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(28))
                                and (component == self.driver.componentF28)
                                and (value == self.driver.valueF28Off)):
                            self.throttle.setF28(not self.throttle.getF28())
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF29)
                                and (value == self.driver.valueF29)):
                            self.throttle.setF29(not self.throttle.getF29())
                        if ((self.roster != None)
                                and (not self.roster.getFunctionLockable(29))
                                and (component == self.driver.componentF29)
                                and (value == self.driver.valueF29Off)):
                            self.throttle.setF29(not self.throttle.getF29())
                    except AttributeError:
                        pass

        # Nothing to customize bellow this point
        if (event.propertyName == "ThrottleFrame"
            ):  # Current throttle frame changed
            self.speedTimer.stop()
            event.oldValue.getAddressPanel().removeAddressListener(self)
            self.addressPanel = event.newValue.getAddressPanel()
            self.throttle = self.addressPanel.getThrottle()
            self.roster = self.addressPanel.getRosterEntry()
            self.speedAction.setThrottle(self.throttle)
            event.newValue.getAddressPanel().addAddressListener(self)

#Jynstrument main and mandatory methods

    def getExpectedContextClassName(self):
        return "jmri.jmrit.throttle.ThrottleWindow"

    def init(self):
        self.getContext().addPropertyChangeListener(
            self)  #ThrottleFrame change
        self.getContext().getCurrentThrottleFrame().getAddressPanel(
        ).addAddressListener(self)  # change of throttle in Current frame
        self.addressPanel = self.getContext().getCurrentThrottleFrame(
        ).getAddressPanel()
        self.throttle = self.addressPanel.getThrottle()  # the throttle
        self.roster = self.addressPanel.getRosterEntry()  # roster entry if any
        self.speedAction = SpeedAction()  #Speed increase thread
        self.speedAction.setThrottle(self.throttle)
        self.speedTimer = Timer(
            valueSpeedTimerRepeat, self.speedAction
        )  # Very important to use swing Timer object (see Swing and multithreading doc)
        self.speedTimer.setRepeats(True)
        self.label = JButton(
            ImageIcon(self.getFolder() + "/USBControl.png",
                      "USBThrottle"))  #label
        self.label.addMouseListener(
            self.getMouseListeners()
            [0])  # In order to get the popupmenu on the button too
        self.add(self.label)
        self.model = jmri.jmrix.jinput.TreeModel.instance()  # USB
        self.desiredController = None
        self.ctrlMenuItem = []
        self.USBDriver = None
        self.driver = None
        mi = JCheckBoxMenuItem("None")
        self.getPopUpMenu().add(mi)
        mi.addItemListener(ControllerItemListener(None, self))
        self.ctrlMenuItem.append(mi)
        for ctrl in self.model.controllers():
            mi = JCheckBoxMenuItem(ctrl.getName())
            self.getPopUpMenu().add(mi)
            mi.addItemListener(ControllerItemListener(ctrl, self))
            self.ctrlMenuItem.append(mi)
        if (len(self.ctrlMenuItem) == 0):
            print "No matching USB device found"
        else:
            self.ctrlMenuItem[0].setSelected(
                True)  # by default connect to the first one
        self.model.addPropertyChangeListener(self)
        self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis()
        self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis()

# On quit clean up resources

    def quit(self):
        self.speedTimer.stop()
        for mi in self.ctrlMenuItem:
            self.getPopUpMenu().remove(mi)
        self.ctrlMenuItem = None
        self.speedAction = None
        self.speedTimer = None
        self.throttle = None
        self.addressPanel = None
        self.driver = None
        self.USBDriver = None
        self.getContext().removePropertyChangeListener(self)
        self.model.removePropertyChangeListener(self)
        self.getContext().getCurrentThrottleFrame().getAddressPanel(
        ).removeAddressListener(self)

# Menu entry changed for Current controller and update driver

    def setSelectedController(self, ctrl, item):
        for mi in self.ctrlMenuItem:
            if (mi != item):  # Force deselection of other ones
                mi.setSelected(False)
        self.desiredController = ctrl
        if (ctrl != None):
            sys.path.append(self.getFolder())  # Load a driver
            try:
                del self.driver
                del self.USBDriver
                dd = ctrl.getName()
                dd = dd.replace(" ", "")
                dd = dd.replace(".", "")
                dd = dd.replace("(", "")
                dd = dd.replace(")", "")
                dd = dd.replace("{", "")
                dd = dd.replace("}", "")
                dd = dd.replace("[", "")
                dd = dd.replace("]", "")
                self.USBDriver = __import__(dd)
            except ImportError:  # On error load a default one
                print "Driver \"" + dd + "\" not found in \"" + self.getFolder(
                ) + "\", loading default one"
                self.USBDriver = __import__("Default")
            reload(self.USBDriver)
            sys.path.remove(self.getFolder())
            self.driver = self.USBDriver.USBDriver()

    def setXml(self, elt):
        if (elt.getChildren("USBThrottle") == None):
            return
        ctrl = elt.getChildren("USBThrottle")[0].getAttributeValue(
            "DesiredController")
        if (ctrl == None):
            return
        for mi in self.ctrlMenuItem:
            if (mi.getText() == ctrl):
                mi.setSelected(True)
                break

    def getXml(self):
        elt = Element("USBThrottle")
        for mi in self.ctrlMenuItem:
            if (mi.isSelected()):
                elt.setAttribute("DesiredController", mi.getText())
                break
        return elt

#AddressListener part: to listen for address changes in address panel (release, acquired)

    def notifyAddressChosen(self, address):
        pass

    def notifyAddressThrottleFound(self, throttle):
        self.speedTimer.stop()
        self.throttle = throttle
        self.speedAction.setThrottle(self.throttle)

    def notifyAddressReleased(self, address):
        self.speedTimer.stop()
        self.throttle = None
        self.speedAction.setThrottle(self.throttle)

    def notifyConsistAddressChosen(self, address, isLong):
        self.notifyAddressChosen(address)

    def notifyConsistAddressThrottleFound(self, throttle):
        self.notifyAddressThrottleFound(throttle)

    def notifyConsistAddressReleased(self, address, isLong):
        self.notifyAddressReleased(address)
Exemplo n.º 36
0
class WiimoteThrottle2(Jynstrument, PropertyChangeListener, AddressListener,
                       WiiDeviceDiscoveryListener, WiiRemoteListener,
                       Runnable):
    #Jynstrument main and mandatory methods
    def getExpectedContextClassName(self):
        return "jmri.jmrit.throttle.ThrottleWindow"

    def init(self):
        self.getContext().addPropertyChangeListener(
            self)  #ThrottleFrame change
        self.addressPanel = self.getContext().getCurrentThrottleFrame(
        ).getAddressPanel()
        self.addressPanel.addAddressListener(
            self)  # change of throttle in Current frame
        self.throttle = self.getContext().getCurrentThrottleFrame(
        ).getAddressPanel().getThrottle()  # the throttle
        self.speedAction = SpeedAction()  #Speed increase thread
        self.speedAction.setThrottle(self.throttle)
        self.speedTimer = Timer(
            valueSpeedTimerRepeat, self.speedAction
        )  # Very important to use swing Timer object (see Swing and multithreading doc)
        self.speedTimer.setRepeats(True)
        self.label = JButton(
            ImageIcon(self.getFolder() + "/WiimoteThrottle2.png",
                      "WiiMote"))  #label
        self.label.addMouseListener(
            self.getMouseListeners()
            [0])  # In order to get the popupmenu on the button too
        self.add(self.label)
        self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis()
        self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis()
        self.advFunctions = AdvFunctions()
        self.lastTimeEStop = Calendar.getInstance().getTimeInMillis()
        self.wiiDevice = None
        self.sync = thread.allocate_lock()  # A lock protecting bellow self.evt
        self.evt = None
        java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true")
        # Required for Bluecove + WiiRemoteJ
        WiiRemoteJ.findRemotes(self, 1)  # Search for 1 Wiimote, and call back

    def quit(self):
        self.speedTimer.stop()
        WiiRemoteJ.stopFind()
        if ((self.wiiDevice != None) and (self.wiiDevice.isConnected())):
            self.wiiDevice.removeWiiRemoteListener(self)
            self.wiiDevice.disconnect()
        self.wiiDevice = None
        self.speedAction = None
        self.speedTimer = None
        self.throttle = None
        self.advFunctions = None
        self.getContext().removePropertyChangeListener(self)
        self.addressPanel.removeAddressListener(self)
        self.addressPanel = None

    #Wiimote discoverer events

    def findFinished(self, nb):
        print "Search finished, found ", nb, " wiimotes"

    def wiiDeviceDiscovered(self, evt):
        print "Found a Wiimote, number: ", evt.getNumber()
        self.wiiDevice = evt.getWiiDevice()
        ledLights = [False, False, False, False]
        ledLights[evt.getNumber() % 4] = True
        self.wiiDevice.setLEDLights(ledLights)
        self.wiiDevice.addWiiRemoteListener(self)

    #Wiimote events
    def buttonInputReceived(self, evt):
        #        print("Wiimote Button event: ", evt)
        self.sync.acquire()
        self.evt = evt
        self.sync.release()
        SwingUtilities.invokeLater(
            self
        )  # Delegate processing to Swing thread (when we are here, we're in the WiiRemoteJ driver thread)

    def run(self):
        self.sync.acquire()
        evt = self.evt
        self.sync.release()
        if (self.speedTimer != None):
            self.speedTimer.stop()  # In any case
        # ThrottleFrames
        if (evt.wasReleased(WRButtonEvent.RIGHT)):  # NEXT
            self.getContext().nextThrottleFrame()
        if (evt.wasReleased(WRButtonEvent.LEFT)):  # PREVIOUS
            self.getContext().previousThrottleFrame()
        if (evt.wasReleased(WRButtonEvent.UP)):  # NEXT RUNNING
            self.getContext().nextRunningThrottleFrame()
        if (evt.wasReleased(WRButtonEvent.DOWN)):  # PREVIOUS RUNNING
            self.getContext().previousRunningThrottleFrame()
        # No throttle assigned to current frame, browse through roster
        if (self.throttle == None):
            if (evt.wasReleased(
                    WRButtonEvent.HOME)):  # Assign selected roster entry
                self.addressPanel.selectRosterEntry()
                return
            if (evt.wasReleased(WRButtonEvent.PLUS)):  # Next roster entry
                selectedIndex = self.addressPanel.getRosterSelectedIndex()
                self.addressPanel.setIcon(False)
                self.addressPanel.setVisible(True)
                self.addressPanel.setRosterSelectedIndex(selectedIndex + 1)
                return
            if (evt.wasReleased(WRButtonEvent.MINUS)):  # Previous roster entry
                selectedIndex = self.addressPanel.getRosterSelectedIndex()
                self.addressPanel.setIcon(False)
                self.addressPanel.setVisible(True)
                self.addressPanel.setRosterSelectedIndex(selectedIndex - 1)
                return
        # Throttle assigned to current frame, control it
        if (self.throttle != None):
            # Speed control
            if (evt.isPressed(WRButtonEvent.B)):  # SPEED - increment
                self.speedAction.setSpeedIncrement(valueSpeedIncrement)
                self.speedTimer.start()
            if (evt.isPressed(WRButtonEvent.A)):  # SPEED - decrement
                self.speedAction.setSpeedIncrement(-valueSpeedIncrement)
                self.speedTimer.start()
            # EStop
            if (evt.isPressed(WRButtonEvent.PLUS
                              | WRButtonEvent.MINUS)):  # estop = + & -
                self.throttle.setSpeedSetting(speedEStopSpeed)
                self.lastTimeEStop = Calendar.getInstance().getTimeInMillis(
                )  # To cancel next inputs
                self.wiiDevice.vibrateFor(750)
            # Directions
            if (evt.wasReleased(WRButtonEvent.PLUS)):  # FORWARD
                self.throttle.setIsForward(True)
            if (evt.wasReleased(WRButtonEvent.MINUS)):  # BACKWARD
                self.throttle.setIsForward(False)
            # Home : F0
            if (evt.wasReleased(WRButtonEvent.HOME)):  # LIGHTS
                if not ((self.addressPanel.getRosterEntry() != None) and
                        (self.advFunctions.call(
                            self.addressPanel.getRosterEntry(), "0", False,
                            self.throttle) != None)):
                    self.throttle.setF0(not self.throttle.getF0())
            # Wiimote 1 & 2 buttons
            if (evt.isPressed(WRButtonEvent.ONE)):
                if not ((self.addressPanel.getRosterEntry() != None) and
                        (self.advFunctions.call(
                            self.addressPanel.getRosterEntry(), "1", True,
                            self.throttle) != None)):
                    pass  # default F1 not momentary (switch only on Release, do nothing here)
            if (evt.wasReleased(WRButtonEvent.ONE)):
                if not ((self.addressPanel.getRosterEntry() != None) and
                        (self.advFunctions.call(
                            self.addressPanel.getRosterEntry(), "1", False,
                            self.throttle) != None)):
                    self.throttle.setF1(
                        not self.throttle.getF1())  # default F1 not momentary
            if (evt.isPressed(WRButtonEvent.TWO)):
                if not ((self.addressPanel.getRosterEntry() != None) and
                        (self.advFunctions.call(
                            self.addressPanel.getRosterEntry(), "2", True,
                            self.throttle) != None)):
                    self.throttle.setF2(True)  # default F2 momentary
            if (evt.wasReleased(WRButtonEvent.TWO)):
                if not ((self.addressPanel.getRosterEntry() != None) and
                        (self.advFunctions.call(
                            self.addressPanel.getRosterEntry(), "2", False,
                            self.throttle) != None)):
                    self.throttle.setF2(False)

    def disconnected(self):
        self.wiiDevice = None
        print("Lost wiimote")

    def accelerationInputReceived(self, evt):
        pass

    def combinedInputReceived(self, evt):
        pass

    def extensionConnected(self, extension):
        pass

    def extensionDisconnected(self, extension):
        pass

    def extensionInputReceived(self, evt):
        pass

    def extensionPartiallyInserted(self):
        pass

    def extensionUnknown(self):
        pass

    def IRInputReceived(self, evt):
        pass

    def statusReported(self, evt):
        print("Wiimote status reported: ", evt)

#Property listener part

    def propertyChange(self, event):
        self.speedTimer.stop()
        if (event.propertyName == "ThrottleFrame"
            ):  # Current throttle frame changed
            event.oldValue.getAddressPanel().removeAddressListener(self)
            self.addressPanel = event.newValue.getAddressPanel()
            self.throttle = self.addressPanel.getThrottle()
            self.speedAction.setThrottle(self.throttle)
            self.addressPanel.addAddressListener(self)

#AddressListener part: to listen for address changes in address panel (release, acquired)

    def notifyAddressChosen(self, address):
        pass

    def notifyAddressThrottleFound(self, throttle):
        self.speedTimer.stop()
        self.throttle = throttle
        self.speedAction.setThrottle(self.throttle)

    def notifyAddressReleased(self, address):
        self.speedTimer.stop()
        self.throttle = None
        self.speedAction.setThrottle(self.throttle)

    def notifyConsistAddressChosen(self, address, isLong):
        self.notifyAddressChosen(address)

    def notifyConsistAddressThrottleFound(self, throttle):
        self.notifyAddressThrottleFound(throttle)

    def notifyConsistAddressReleased(self, address, isLong):
        self.notifyAddressReleased(address)
Exemplo n.º 37
0
class WiimoteThrottle(Jynstrument, PropertyChangeListener, AddressListener, WiiDeviceDiscoveryListener, WiiRemoteListener, Runnable):
    #Wiimote discoverer events
    def findFinished(self, nb):
        print "Search finished, found ",nb ," wiimotes"

    def wiiDeviceDiscovered(self, evt):
        print "Found a Wiimote, number: ", evt.getNumber()
        self.wiiDevice = evt.getWiiDevice()
        ledLights = [False, False, False, False]
        ledLights[evt.getNumber()%4] = True
        self.wiiDevice.setLEDLights(ledLights)
        self.wiiDevice.addWiiRemoteListener(self)

    #Wiimote events        
    def buttonInputReceived(self, evt):
#        print("Wiimote Button event: ", evt)
        self.sync.acquire()
        self.evt = evt
        self.sync.release()
        SwingUtilities.invokeLater(self) # Delegate processing to Swing thread (when we are here, we're in the WiiRemoteJ driver thread)

    def run(self):
        self.sync.acquire()
        evt = self.evt
        self.sync.release()
        if (self.speedTimer != None):
            self.speedTimer.stop() # In any case
        # ThrottleFrames
        if ( evt.wasReleased(WRButtonEvent.RIGHT) ): # NEXT
             self.getContext().nextThrottleFrame()
        if ( evt.wasReleased(WRButtonEvent.LEFT) ):  # PREVIOUS
            self.getContext().previousThrottleFrame()
        if ( evt.wasReleased(WRButtonEvent.UP) ): # NEXT RUNNING
             self.getContext().nextRunningThrottleFrame()
        if ( evt.wasReleased(WRButtonEvent.DOWN) ):  # PREVIOUS RUNNING
            self.getContext().previousRunningThrottleFrame()  
        # No throttle assigned to current frame, browse through roster      
        if (self.throttle == None):
            if ( evt.wasReleased(WRButtonEvent.HOME) ):  # Assign selected roster entry
                self.addressPanel.selectRosterEntry()
                return
            if ( evt.wasReleased(WRButtonEvent.PLUS) ):  # Next roster entry
                selectedIndex = self.addressPanel.getRosterSelectedIndex()
                self.addressPanel.setIcon(False)
                self.addressPanel.setVisible(True)
                self.addressPanel.setRosterSelectedIndex(selectedIndex + 1)
                return
            if ( evt.wasReleased(WRButtonEvent.MINUS) ):  # Previous roster entry
                selectedIndex = self.addressPanel.getRosterSelectedIndex()
                self.addressPanel.setIcon(False)
                self.addressPanel.setVisible(True)
                self.addressPanel.setRosterSelectedIndex(selectedIndex - 1)
                return
        # Throttle assigned to current frame, control it  
        if (self.throttle != None):
            if ( evt.wasReleased(WRButtonEvent.HOME) ):  # LIGHTS
                self.throttle.setF0( not self.throttle.getF0() )
                return
            if ( evt.wasReleased(WRButtonEvent.PLUS) ):  # FORWARD
                self.throttle.setIsForward(True)
                return
            if ( evt.wasReleased(WRButtonEvent.MINUS) ):  # BACKWARD
                self.throttle.setIsForward(False)
                return
            # Speed control
            if ( evt.isPressed(WRButtonEvent.B) ): # SPEED - increment
                self.speedAction.setSpeedIncrement( valueSpeedIncrement )
                self.speedTimer.start()
                return
            if ( evt.isPressed(WRButtonEvent.A) ): # SPEED - decrement
                self.speedAction.setSpeedIncrement( -valueSpeedIncrement )
                self.speedTimer.start()
                return
            # EStop
            if ( evt.isPressed( WRButtonEvent.ONE | WRButtonEvent.TWO ) ): # estop = button1 + button2
                self.throttle.setSpeedSetting( speedEStopSpeed )
                self.lastTimeEStop = Calendar.getInstance().getTimeInMillis() # To cancel next inputs
                self.wiiDevice.vibrateFor(750)
                return
            # Speed presets
            if (Calendar.getInstance().getTimeInMillis() - self.lastTimeEStop > delay4double): # Delay for nothing after EStop
                if (( evt.wasReleased(WRButtonEvent.TWO) ) and           #STOP = button2 x2 or (button2 and CurrentSpeed = slow speed)
                    ( (Calendar.getInstance().getTimeInMillis() - self.lastTimeButton2 < delay4double) or ( self.throttle.getSpeedSetting() == speedSlowSpeed ))):  
                    self.throttle.setSpeedSetting( speedStopSpeed )
                    return
                if ( evt.wasReleased(WRButtonEvent.TWO) ):               # SLOW SPEED = button2
                    self.throttle.setSpeedSetting( speedSlowSpeed )
                    self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis()
                    return
                if (( evt.wasReleased(WRButtonEvent.ONE) ) and           # MAX SPEED = button1x2 or (button1 and CurrentSpeed = cruise speed)
                    ( (Calendar.getInstance().getTimeInMillis() - self.lastTimeButton1 < delay4double) or ( self.throttle.getSpeedSetting() == speedCruiseSpeed ))): 
                    self.throttle.setSpeedSetting( speedMaxSpeed )
                    return
                if ( evt.wasReleased( WRButtonEvent.ONE) ):              # CRUISE SPEED = button1
                    self.throttle.setSpeedSetting( speedCruiseSpeed )
                    self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis()
                    return

    def disconnected(self):
        self.wiiDevice = None
        print("Lost wiimote")
        
    def accelerationInputReceived(self, evt):
        pass
    def combinedInputReceived(self, evt):
        pass
    def	extensionConnected(self, extension):
        pass          
    def	extensionDisconnected(self, extension):
        pass          
    def extensionInputReceived(self, evt):
        pass
    def	extensionPartiallyInserted(self):
        pass
    def extensionUnknown(self):
        pass
    def IRInputReceived(self, evt):
        pass
    def statusReported(self, evt):
        print("Wiimote status reported: ", evt)

#Property listener part
    def propertyChange(self, event):
        self.speedTimer.stop()                     
        if (event.propertyName == "ThrottleFrame") :  # Current throttle frame changed
            event.oldValue.getAddressPanel().removeAddressListener(self)
            self.addressPanel = event.newValue.getAddressPanel()
            self.throttle = self.addressPanel.getThrottle()
            self.speedAction.setThrottle( self.throttle )
            self.addressPanel.addAddressListener(self)

#Jynstrument main and mandatory methods
    def getExpectedContextClassName(self):
        return "jmri.jmrit.throttle.ThrottleWindow"
    
    def init(self):
        self.getContext().addPropertyChangeListener(self) #ThrottleFrame change
        self.addressPanel=self.getContext().getCurrentThrottleFrame().getAddressPanel();
        self.addressPanel.addAddressListener(self) # change of throttle in Current frame
        self.throttle = self.getContext().getCurrentThrottleFrame().getAddressPanel().getThrottle() # the throttle
        self.speedAction =  SpeedAction()  #Speed increase thread
        self.speedAction.setThrottle( self.throttle )
        self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc)
        self.speedTimer.setRepeats(True)
        self.label = JButton(ImageIcon(self.getFolder() + "/WiimoteThrottle.png","WiiMote")) #label
        self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too
        self.add(self.label)
        self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis()
        self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis()
        self.lastTimeEStop = Calendar.getInstance().getTimeInMillis()
        self.wiiDevice = None
        self.sync = thread.allocate_lock() # A lock protecting bellow self.evt
        self.evt = None
        java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true"); # Required for Bluecove + WiiRemoteJ
        WiiRemoteJ.findRemotes(self, 1) # Search for 1 Wiimote, and call back
       
    def quit(self):
        self.speedTimer.stop() 
        WiiRemoteJ.stopFind()
        if ((self.wiiDevice != None) and (self.wiiDevice.isConnected())):
            self.wiiDevice.removeWiiRemoteListener(self)
            self.wiiDevice.disconnect()
        self.wiiDevice = None
        self.speedAction = None
        self.speedTimer = None
        self.throttle = None
        self.getContext().removePropertyChangeListener(self)
        self.addressPanel.removeAddressListener(self)
        self.addressPanel = None

#AddressListener part: to listen for address changes in address panel (release, acquired)
    def notifyAddressChosen(self, address):
        pass
        
    def notifyAddressThrottleFound(self, throttle):
        self.speedTimer.stop() 
        self.throttle = throttle
        self.speedAction.setThrottle( self.throttle )
            
    def notifyAddressReleased(self, address):
        self.speedTimer.stop()
        self.throttle = None
        self.speedAction.setThrottle( self.throttle )

    def notifyConsistAddressChosen(self, address, isLong):
        self.notifyAddressChosen(address)

    def notifyConsistAddressThrottleFound(self, throttle):
        self.notifyAddressThrottleFound(throttle)

    def notifyConsistAddressReleased(self, address, isLong):
        self.notifyAddressReleased(address)
Exemplo n.º 38
0
class Example(JFrame, ActionListener):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

# Paint all of the objects in screenObjects

    def mypaint(self, g):
        for object in screenObjects:
            object._draw(
                g
            )  #Now calls a _draw method on each object, instead of just having a bunch of lambdas in screenObjects.

# Add an external event on a mouse click

    def myclick(self, x, y):
        externalEvents['LeftMouseButton'] = SP2(
            x, y)  #SP2 inherited from pythonfrp StaticNumerics.py

    def mykey(self, k):
        externalEvents['KeyTyped'] = string(k)
#        print("Key Pressed: " + string(k))

    def my_move(self, x, y):
        mouse_pos[0] = SP2(x, y)

    def initUI(self):
        self.addKeyListener(KA(lambda k: self.mykey(k)))
        self.xp = 0
        self.yp = 0
        self.canvas = Canvas(lambda g: self.mypaint(g),
                             lambda x, y: self.myclick(x, y),
                             lambda x, y: self.my_move(x, y))
        self.canvas.setBackground(Color(200, 200, 200))
        self.getContentPane().add(self.canvas)
        self.setTitle("Test")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(500, 500)
        self.setLocationRelativeTo(None)
        self.setBackground(Color(255, 255, 255))
        self.setVisible(True)
        self.timer = Timer(50, self)
        self.timer.start()


# This is the heartbeat handling code - this is attached to a timer in the frame

    def actionPerformed(self, e):
        currentTime = System.currentTimeMillis()
        rSide = random.randrange(0, 4)
        if ((currentTime - startTime[0]) % 5 == 0):
            if (rSide == 0):
                (circle(p2(random.randrange(50, 450), -30 + localTime * 100),
                        10))
            elif (rSide == 1):
                (circle(p2(500 - localTime * 100, random.randrange(50, 450)),
                        10))
            elif (rSide == 2):
                (circle(p2(random.randrange(50, 450), 500 - localTime * 100),
                        10))
            else:
                (circle(p2(-30 + localTime * 100, random.randrange(50, 450)),
                        10))
        del screenObjects[:]
        #        print(currentTime-startTime[0])
        #        print('Objects: ' + str(Globals.worldObjects))
        heartbeat((currentTime - startTime[0]) / 1000.0, externalEvents)
        externalEvents.clear()
        self.repaint()
Exemplo n.º 39
0
    def	registerExtenderCallbacks(self, callbacks):
        print "PhantomJS RIA Crawler extension"
        print "Nikolay Matyunin @autorak <*****@*****.**>"

        # keep a reference to our callbacks object and helpers object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # extension name
        callbacks.setExtensionName("Phantom RIA Crawler")

        # Create Tab UI components
        self._jPanel = JPanel()
        self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT)
        _titleLabelFont = _titleLabel.font
        _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12);
        _titleLabel.setFont(_titleLabelFont);
        _titleLabel.setForeground(Color(230, 142, 11))

        self._addressTextField = JTextField('')
        self._addressTextField.setColumns(50)
        _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT)
        self._addressTextField.getDocument().addDocumentListener(self)

        self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value
        self._phantomJsPathField.setColumns(50)
        _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT)

        self._startButton = JToggleButton('Start', actionPerformed=self.startToggled)
        self._startButton.setEnabled(False)

        _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT)
        self._requestsMadeInfo = JLabel("", SwingConstants.LEFT)
        _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT)
        self._statesFoundInfo = JLabel("", SwingConstants.LEFT)

        _separator = JSeparator(SwingConstants.HORIZONTAL)

        _configLabel = JLabel("Crawling configuration:")
        self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked)
        self._configFile = ""

        _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT)
        self._listenersCombo = JComboBox()
        self._configTimer = Timer(5000, None)
        self._configTimer.actionPerformed = self._configUpdated
        self._configTimer.stop()
        self._configUpdated(None)

        self._commandClient = CommandClient(self)

        # Layout management
        self._groupLayout = GroupLayout(self._jPanel)
        self._jPanel.setLayout(self._groupLayout)
        self._groupLayout.setAutoCreateGaps(True)
        self._groupLayout.setAutoCreateContainerGaps(True)

        self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_addressTextLabel)
                .addGroup(self._groupLayout.createParallelGroup()
                    .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_requestsMadeLabel)
                        .addComponent(self._requestsMadeInfo))
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_statesFoundLabel)
                        .addComponent(self._statesFoundInfo)))
                .addComponent(self._startButton))
            .addComponent(_separator)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
        )

        self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_addressTextLabel)
                .addComponent(self._addressTextField)
                .addComponent(self._startButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_requestsMadeLabel)
                .addComponent(self._requestsMadeInfo))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_statesFoundLabel)
                .addComponent(self._statesFoundInfo))
            .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo))
        )

        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel);


        # context menu data
        self._contextMenuData = None;
        self._running = False;

        # register callbacks
        callbacks.customizeUiComponent(self._jPanel)
        callbacks.registerContextMenuFactory(self)
        callbacks.addSuiteTab(self)

        return
Exemplo n.º 40
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, DocumentListener, ChangeListener):

    #
    # implement IBurpExtender
    #
    def	registerExtenderCallbacks(self, callbacks):
        print "PhantomJS RIA Crawler extension"
        print "Nikolay Matyunin @autorak <*****@*****.**>"

        # keep a reference to our callbacks object and helpers object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # extension name
        callbacks.setExtensionName("Phantom RIA Crawler")

        # Create Tab UI components
        self._jPanel = JPanel()
        self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT)
        _titleLabelFont = _titleLabel.font
        _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12);
        _titleLabel.setFont(_titleLabelFont);
        _titleLabel.setForeground(Color(230, 142, 11))

        self._addressTextField = JTextField('')
        self._addressTextField.setColumns(50)
        _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT)
        self._addressTextField.getDocument().addDocumentListener(self)

        self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value
        self._phantomJsPathField.setColumns(50)
        _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT)

        self._startButton = JToggleButton('Start', actionPerformed=self.startToggled)
        self._startButton.setEnabled(False)

        _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT)
        self._requestsMadeInfo = JLabel("", SwingConstants.LEFT)
        _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT)
        self._statesFoundInfo = JLabel("", SwingConstants.LEFT)

        _separator = JSeparator(SwingConstants.HORIZONTAL)

        _configLabel = JLabel("Crawling configuration:")
        self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked)
        self._configFile = ""

        _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT)
        self._listenersCombo = JComboBox()
        self._configTimer = Timer(5000, None)
        self._configTimer.actionPerformed = self._configUpdated
        self._configTimer.stop()
        self._configUpdated(None)

        self._commandClient = CommandClient(self)

        # Layout management
        self._groupLayout = GroupLayout(self._jPanel)
        self._jPanel.setLayout(self._groupLayout)
        self._groupLayout.setAutoCreateGaps(True)
        self._groupLayout.setAutoCreateContainerGaps(True)

        self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_addressTextLabel)
                .addGroup(self._groupLayout.createParallelGroup()
                    .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_requestsMadeLabel)
                        .addComponent(self._requestsMadeInfo))
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_statesFoundLabel)
                        .addComponent(self._statesFoundInfo)))
                .addComponent(self._startButton))
            .addComponent(_separator)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
        )

        self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_addressTextLabel)
                .addComponent(self._addressTextField)
                .addComponent(self._startButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_requestsMadeLabel)
                .addComponent(self._requestsMadeInfo))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_statesFoundLabel)
                .addComponent(self._statesFoundInfo))
            .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo))
        )

        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel);


        # context menu data
        self._contextMenuData = None;
        self._running = False;

        # register callbacks
        callbacks.customizeUiComponent(self._jPanel)
        callbacks.registerContextMenuFactory(self)
        callbacks.addSuiteTab(self)

        return

    #
    # implement ITab and Tab ChangeListener
    #
    def getTabCaption(self):
        return "Phantom RIA Crawler"
    def getUiComponent(self):
        return self._jPanel
    def stateChanged(self, ev):
        self._configUpdated()

    def _configUpdated(self, ev):
        config = self._callbacks.saveConfig()

        # update proxy listeners
        index = 0
        listeners = DefaultComboBoxModel()
        while (("proxy.listener" + str(index)) in config):
            listenerItem = config["proxy.listener" + str(index)]
            listenerItems = listenerItem.split(".")
            if (listenerItems[0] == "1"):
                address = ".".join(listenerItems[2][1:].split("|"))
                if (len(address) == 0):
                    address = "127.0.0.1"
                listeners.addElement(address + " : " + listenerItems[1])

            index = index + 1
        self._listenersCombo.setModel(listeners)
        return;

    #
    # implement button actions
    #
    def startToggled(self, ev):
        if (self._startButton.getModel().isSelected()):
            try:
                os.chdir(sys.path[0] + os.sep + "riacrawler" + os.sep + "scripts")
            except Exception as e:
                print >> sys.stderr, "RIA crawler scripts loading error", "I/O error({0}): {1}".format(e.errno, e.strerror)
                self._startButton.setSelected(False)
                return

            phantomJsPath = self._phantomJsPathField.text
            target = self._addressTextField.text

            config = "crawler.config"
            if (self._configFile):
                config = self._configFile

            listenerAddress = self._listenersCombo.getSelectedItem().replace(" ", "")
            p = Popen("{0} --proxy={3} main.js --target={1} --config={2}".format(phantomJsPath, target, config, listenerAddress), shell=True)
            self._running = True
            self._requestsMadeInfo.setText("")
            self._statesFoundInfo.setText("")
            self._commandClient.startCrawling()
        else:
            if (self._running):
                self._commandClient.stopCrawling()
            self._running = False

    def syncCrawlingState(self, result):
        print "RIA crawling state: ", result
        self._requestsMadeInfo.setText(str(result["requests_made"]))
        self._statesFoundInfo.setText(str(result["states_detected"]))
        if (result["running"] == False):
            self._commandClient.stopCrawling()
            self._running = False
            self._startButton.setSelected(False)

    def loadConfigClicked(self, ev):
        openFile = JFileChooser();
        openFile.showOpenDialog(None);
        self._configFile = openFile.getSelectedFile()

    #
    # implement DocumentListener for _addressTextField
    #
    def removeUpdate(self, ev):
        self.updateStartButton()
    def insertUpdate(self, ev):
        self.updateStartButton()
    def updateStartButton(self):
        self._startButton.setEnabled(len(self._addressTextField.text) > 0)


    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, contextMenuInvocation):
        menuItemList = ArrayList()

        context = contextMenuInvocation.getInvocationContext()
        if (context == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST or context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or
            context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY or context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE):

            self._contextMenuData = contextMenuInvocation.getSelectedMessages()
            menuItemList.add(JMenuItem("Send to Phantom RIA Crawler", actionPerformed = self.menuItemClicked))

        return menuItemList


    def menuItemClicked(self, event):
        if (self._running == True):
            self._callbacks.issueAlert("Can't set data to Phantom RIA Crawler: crawling is running already.")
            return;

        dataIsSet = False;
        for message in self._contextMenuData:
            request = self._helpers.analyzeRequest(message)

            url = request.getUrl().toString()
            print url
            if (url):
                dataisSet = True;
                self._addressTextField.setText(url)
    class TrackDevice(java.beans.PropertyChangeListener):
        import java
        import javax.swing
        from javax.swing import Timer

        delayTimer = None
        relayClicks = None

        # TrackDevice.init - Initialize a TrackDevice instance for a particular device
        #
        # aName          : Device name
        # aDevice        : JMRI device instance
        # aAllowedStates : Array of states we want to track, other states are ignored
        #
        def init(self, aName, aDevice, aAllowedStates, aLogFile, aParent):
            from javax.swing import Timer
            self.DeviceName = aName
            self.Device = aDevice
            self.DeviceNumber = self.DeviceName[2:self.DeviceName.find(":")]
            self.AllowedStates = aAllowedStates
            self.parent = aParent
            self.DeviceValue = self.AllowedStates[0]
            self.LogFile = aLogFile

            self.timeoutListener = self.TimeoutReceiver()
            self.timeoutListener.setCallBack(self.receiveTimeoutHandler)

            self.receiveTimer = Timer(100, self.timeoutListener)
            self.receiveTimer.setInitialDelay(10)

            self.receiveTimer.stop()
            self.receiveTimer.setRepeats(False)

            self.sendTimeoutListener = self.TimeoutReceiver2()
            self.sendTimeoutListener.setCallBack(self.sendTimeoutHandler)

            self.sendTimer = Timer(100, self.timeoutListener)
            self.sendTimer.setInitialDelay(10)
            self.sendTimer.stop()
            self.sendTimer.setRepeats(False)

            self.pauseTimeoutListener = self.TimeoutReceiver()
            self.pauseTimeoutListener.setCallBack(self.pauseTimeoutHandler)

            self.pauseTimer = Timer(100, self.pauseTimeoutListener)
            self.pauseTimer.setInitialDelay(10)

            self.pauseTimer.stop()
            self.pauseTimer.setRepeats(False)

            self.finalTimeoutListener = self.TimeoutReceiver()
            self.finalTimeoutListener.setCallBack(self.finalTimeoutHandler)
            self.finalTimer = Timer(100, self.finalTimeoutListener)
            self.finalTimer.setInitialDelay(10)
            self.finalTimer.stop()
            self.finalTimer.setRepeats(False)

            #            self.relayClicks = jmri.jmrit.Sound(jmri.util.FileUtil.getExternalFilename("preference:resources/sounds/EnhancedCTCRelayTrimmed.wav"))
            self.relayClicks = jmri.jmrit.Sound(
                "resources/sounds/Code-receive.wav")
            self.relaySend = jmri.jmrit.Sound("resources/sounds/Code-send.wav")

            return

        # TrackDevice.updateState - Track the device state while reading the old log
        #                           file.  Note the state but don't change the device
        #                           itself and don't log the changes to the new log file
        #                           (yet).
        #
        # aNewState : New device state.
        #
        def updateState(self, aNewState):
            print 'updateState ' + self.DeviceName + " to state = " + aNewState
            for i in range(len(self.AllowedStates)):
                if (aNewState == self.AllowedStates[i]):
                    self.DeviceValue = aNewState
                    self.Device.setValue(aNewState)
                    break

        # TrackDevice.propertyChange - Record state changes as a result of activities
        #                              elsewhere in JMRI
        #
        # aEvent : Event triggering the change (we don't actually look at the event...)
        #
        def propertyChange(self, aEvent):
            newValue = self.Device.getValue()
            print("***** In propertyChange")
            memories.getMemory("IM5:TVC").setValue("1")

            #
            #  Turn on Control Code indicator light
            codeSendSensor = sensors.getSensor("Code Send Indicator")
            codeSendSensor.setState(ACTIVE)

            #
            #  Start relay clicking sound
            self.relaySend.loop()

            #
            #  Start timer to keep code send light on and relays clicking for a while.
            ccdl = 15  #+  java.util.Random().nextInt(1) # Code transmission delay
            self.sendTimer.setDelay(ccdl * 1000)
            #self.sendTimer.start()

            self.parent.waitMsec(ccdl * 1000)

            self.relaySend.stop()
            codeSendSensor.setState(INACTIVE)

            if (newValue == self.DeviceValue):
                return

            for i in range(len(self.AllowedStates)):
                if (newValue == self.AllowedStates[i]):
                    self.DeviceValue = newValue
                    self.LogFile.write(self.DeviceName + " " +
                                       self.DeviceValue + "\n")
                    self.LogFile.flush()
                    break
            return

        # TrackDevice.setInitialDeviceState - After reading all of the old tracking file we
        #                                     now initialize the actual devices to their last
        #                                     known states and log these states into the new
        #                                     log file.
        #
        def setInitialDeviceState(self, logFile, parent):
            #       Uncomment the following print statement to display the list of devices being tracked.
            print "In setInitDeviceState, name = " + self.DeviceName + " value = " + self.DeviceValue
            self.LogFile = logFile
            ###            self.Device.setState(self.DeviceValue)
            self.Device.addPropertyChangeListener(self)
            #logStateChange2(self.DeviceName, self.DeviceState, False)
            logFile.write(self.DeviceName + " " + self.DeviceValue + "\n")

            signalId = "IS:" + self.DeviceNumber
            # Move the switch lever to the correct position
            sensors.getSensor(signalId + ":CB").setState(INACTIVE)
            if (self.DeviceValue == "N"):
                turnouts.provideTurnout("NT" +
                                        self.DeviceNumber).setState(CLOSED)
                self.parent.waitMsec(100)
                sensors.getSensor(signalId + ":NK").setState(ACTIVE)
                sensors.getSensor(signalId + ":L").setState(ACTIVE)
                sensors.getSensor(signalId + ":RK").setState(INACTIVE)

            else:
                turnouts.provideTurnout("NT" +
                                        self.DeviceNumber).setState(THROWN)
                self.parent.waitMsec(100)
                sensors.getSensor(signalId + ":NK").setState(INACTIVE)
                sensors.getSensor(signalId + ":RK").setState(ACTIVE)
                sensors.getSensor(signalId + ":L").setState(INACTIVE)

        class TimeoutReceiver(java.awt.event.ActionListener):
            cb = None

            def actionPerformed(self, event):
                if (self.cb != None):
                    self.cb(event)
                return

            def setCallBack(self, cbf):
                self.cb = cbf
                return

        class TimeoutReceiver2(java.awt.event.ActionListener):
            cb = None

            def actionPerformed(self, event):
                if (self.cb != None):
                    self.cb(event)
                return

            def setCallBack(self, cbf):
                self.cb = cbf
                return

        def sendTimeoutHandler(self, event):
            print "In send timeout handler"
            self.sendTimer.stop()
            self.relaySend.stop()
            sensors.getSensor("IS16:CCK").setState(INACTIVE)

            smdl = 5  #+  java.util.Random().nextInt(2) # Switch motor delay -

            self.pauseTimer.setInitialDelay(smdl * 100)
            self.pauseTimer.start()
            return

        #
        #  Timeout handler between send & receive.
        #  Turn panel indicators off & start indication code relay clicks.
        def pauseTimeoutHandler(self, event):
            self.pauseTimer.stop()

            sensors.getSensor("Code Receive Indicator").setState(ACTIVE)
            self.relayClicks.loop()
            newName = "IS:" + self.DeviceNumber
            sensors.getSensor(newName + ":NK").setState(INACTIVE)
            sensors.getSensor(newName + ":RK").setState(INACTIVE)
            signals.getSignalHead("VH:T" + str(self.DeviceNumber) +
                                  "N").setAppearance(DARK)
            signals.getSignalHead("VH:T" + str(self.DeviceNumber) +
                                  "R").setAppearance(DARK)

            icdl = 5  #+  java.util.Random().nextInt(3) # Indicator code delay

            self.receiveTimer.setInitialDelay(icdl * 100)
            self.receiveTimer.start()
            return

        #
        #  Final timeout handler....turn off Indication Code relay clicks and change indicator lights on panel.
        def receiveTimeoutHandler(self, event):
            # see which phase we think we are in
            self.receiveTimer.stop()

            sensors.getSensor("Code Receive Indicator").setState(INACTIVE)

            #
            #  Throw the turnout.  We should do this in an earlier timeout handler, but with the CTC panel lights hardwired to the tortoise motor,
            #  the lights change too soon.
            if (memories.getMemory("IM1:FB").getValue() == 0):
                if (self.Device.getValue() == "N"):
                    turnouts.provideTurnout("NT" +
                                            self.DeviceNumber).setState(CLOSED)
                else:
                    turnouts.provideTurnout("NT" +
                                            self.DeviceNumber).setState(THROWN)

            self.finalTimer.setInitialDelay(6000)
            self.finalTimer.start()

            return

        #
        #  Final timeout handler....turn off Indication Code relay clicks and change indicator lights on panel.
        def finalTimeoutHandler(self, event):
            # see which phase we think we are in
            self.finalTimer.stop()

            self.relayClicks.stop()
            sensors.getSensor("Code Receive Indicator").setState(INACTIVE)
            memories.getMemory("IM5:TVC").setValue("0")
            memories.getMemory("IM1:FB").setValue(0)
            return
Exemplo n.º 42
0
    def __init__(self, frame, name):
        self.frame = frame
        self.exception = None
        self.name = name
        self.searchTerm = None
        self.searchIndex = -1

        self.searchField = JTextField("")
        self.searchField.addActionListener(SearchListener(self))

        self.newGeneFrom = JTextField("")
        self.newGeneTo = JTextField("")
        self.newGeneButton = JButton("New Gene")
        newGeneActionListener = NewGeneActionListener(self)
        self.newGeneFrom.addActionListener(newGeneActionListener)
        self.newGeneTo.addActionListener(newGeneActionListener)
        self.newGeneButton.addActionListener(newGeneActionListener)

        self.markForRemovalButton = JButton("Mark For Removal")
        self.markForRemovalButton.addActionListener(MarkForRemovalListener(self))
        
        self.inGenes = JList(DefaultListModel())
        self.inGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.inGenes.cellRenderer = ProfelisCellRenderer()
        self.markButtonLabelerTimer = Timer(100, MarkButtonLabeler(self))
        self.markButtonLabelerTimer.start()
        self.loadFile()

        self.outGenes = JList(DefaultListModel())
        self.outGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.outGenes.cellRenderer = ProfelisCellRenderer()
                
        constraints = GridBagConstraints()
        self.layout = GridBagLayout()
        
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes In Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        self.add(JButton(RemoveAction(self)), constraints)
        constraints.gridx, constraints.gridy = 1, 1
        self.add(self.markForRemovalButton, constraints)
        constraints.gridx, constraints.gridy = 2, 1
        self.add(JLabel("Search"), constraints)
        constraints.gridx, constraints.gridy = 3, 1
        constraints.fill = GridBagConstraints.HORIZONTAL
        self.add(self.searchField, constraints)
        constraints.gridx, constraints.gridy = 0, 2
        constraints.gridwidth, constraints.gridheight = 4, 2
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.inGenes), constraints)

        constraints.gridx, constraints.gridy = 4, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes To Add To Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 4, 1
        self.add(self.newGeneButton, constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 5, 1
        self.add(self.newGeneFrom, constraints)
        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 6, 1
        self.add(JLabel("To"), constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 7, 1
        self.add(self.newGeneTo, constraints)

        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 4, 2
        self.add(JButton(AddGenesAction(self)), constraints)
        constraints.gridx, constraints.gridy = 4, 3
        constraints.gridwidth, constraints.gridheight = 4, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.outGenes), constraints)
Exemplo n.º 43
0
class Example(JFrame, ActionListener):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

# Paint all of the objects in screenObjects

    def mypaint(self, g):
        layerArray = [[] for i in range(100)
                      ]  #Creating a 100-item array for us to work with.
        for object in screenObjects:
            layerIndex = int(
                min(object._zLayer, 99)
            )  #This specifies the layer that the object will be headed for...
            layerLoc = 0
            myDepth = object._get("zDepth")
            for compObject in layerArray[
                    layerIndex]:  #but first, we need to find the right place in that layer to put our object.
                if (myDepth > compObject._get("zDepth")):
                    layerLoc = layerLoc + 1
                else:
                    break
            layerArray[layerIndex].insert(layerLoc, object)
        newArray = [
        ]  #We now want to compress our scattered 2d-array into a 1d-array.
        for subArray in layerArray:  #It's called Radix sorting.
            newArray.extend(subArray)
#screenObjects = newArray #Turns out you can't actually do this, and I have no idea why.
        for object in newArray:  #Instead of going through screenObjects, we go through newArray, which is sorted by layer.
            object._draw(
                g
            )  #Now calls a _draw method on each object, instead of just having a bunch of lambdas in screenObjects.

# Add an external event on a mouse click

    def myclick(self, x, y):
        externalEvents['LeftMouseButton'] = SP2(
            x, y)  #SP2 inherited from pythonfrp StaticNumerics.py

    def mykey(self, k):
        externalEvents['KeyTyped'] = string(k)
#        print("Key Pressed: " + string(k))

    def my_move(self, x, y):
        mouse_pos[0] = SP2(x, y)

    def initUI(self):
        self.addKeyListener(KA(lambda k: self.mykey(k)))
        self.xp = 0
        self.yp = 0
        self.canvas = Canvas(lambda g: self.mypaint(g),
                             lambda x, y: self.myclick(x, y),
                             lambda x, y: self.my_move(x, y))
        self.canvas.setBackground(JavaColor(200, 200, 100))
        self.getContentPane().add(self.canvas)
        self.setTitle("Test")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.xSize = 500
        self.ySize = 500
        self.setSize(self.xSize, self.ySize)
        self.setLocationRelativeTo(None)
        self.setBackground(JavaColor(255, 255, 255))
        self.setVisible(True)

        #self.button = JButton("This is a button")
        #self.add(self.button, BorderLayout.SOUTH)
        #self.button.addActionListener(self)

        self.timer = Timer(50, self)
        self.timer.start()


# This is the heartbeat handling code - this is attached to a timer in the frame

    def actionPerformed(self, e):
        #if(e.getSource() == self.button):
        #self.addSlider()
        #else:
        currentTime = System.currentTimeMillis()
        #if ((currentTime-startTime[0]) % 75 == 0):
        #    balls.append(circle(p2(random.randrange(50,250),270-localTime*100), 10))
        del screenObjects[:]
        #        print(currentTime-startTime[0])
        #        print('Objects: ' + str(Globals.worldObjects))
        heartbeat((currentTime - startTime[0]) / 1000.0, externalEvents)
        externalEvents.clear()
        self.repaint()

    def addSlider(self):  #adds a new slider at the bottom of the window.
        slider = JSlider()
        self.add(
            slider, BorderLayout.SOUTH
        )  #this is the best way I could find to make sure the slider appears somewhere consistent.
        self.ySize = self.ySize + 20  #the problem, sadly, is that all of the sliders and buttons and stuff appear at the SAME PLACE, overlapping.
        self.setSize(self.xSize, self.ySize)
Exemplo n.º 44
0
class USBThrottle(Jynstrument, PropertyChangeListener, AddressListener):
#Property listener part: USB value
    def propertyChange(self, event):
        # Customize bellow for throttles calls:
        if (event.propertyName == "Value") :  # USB
            if (event.oldValue.getController() == self.desiredController ) :
                component = event.oldValue.getComponent().toString()
                value = event.newValue
                # Uncomment bellow line to see component name and its value
                # print "Component",component,"value changed to",value
                try:
                    # Change current ThrottleFrame
                    if ((component == self.driver.componentNextThrottleFrame) and (value == self.driver.valueNextThrottleFrame)) : #NEXT
                        self.getContext().nextThrottleFrame()
                    if  ((component == self.driver.componentPreviousThrottleFrame) and (value == self.driver.valuePreviousThrottleFrame)) : #PREVIOUS
                        self.getContext().previousThrottleFrame()
                    if ((component == self.driver.componentNextRunningThrottleFrame) and (value == self.driver.valueNextRunningThrottleFrame)) : #NEXT RUNNING
                        self.getContext().nextRunningThrottleFrame()
                    if  ((component == self.driver.componentPreviousRunningThrottleFrame) and (value == self.driver.valuePreviousRunningThrottleFrame)) : #PREVIOUS RUNNING
                        self.getContext().previousRunningThrottleFrame()  
                except AttributeError:
                    pass
                
                if (self.throttle == None) :
                    try:
                        # Browse through roster
                        if ((component == self.driver.componentNextRosterBrowse) and (value == self.driver.valueNextRoster)): #NEXT
                            selectedIndex = self.addressPanel.getRosterSelectedIndex()
                            self.addressPanel.setVisible(True)
                            self.addressPanel.setIcon(False)
                            self.addressPanel.setRosterSelectedIndex(selectedIndex + 1)
                        if ((component == self.driver.componentPreviousRosterBrowse) and (value == self.driver.valuePreviousRoster)) : #PREVIOUS
                            selectedIndex = self.addressPanel.getRosterSelectedIndex()
                            self.addressPanel.setVisible(True)
                            self.addressPanel.setIcon(False)                            
                            self.addressPanel.setRosterSelectedIndex(selectedIndex - 1)
                    except AttributeError:
                        pass
                    try:
                        # Request a throttle
                        if ((component == self.driver.componentRosterSelect) and (value == self.driver.valueRosterSelect)):
                            self.addressPanel.selectRosterEntry()
                    except AttributeError:
                        pass
                        
                # From there; current throttle control, hence require a throttle
                if (self.throttle != None) :
                    # Release current throttle
                    try:
                        if ((component == self.driver.componentThrottleRelease) and (value == self.driver.valueThrottleRelease)):
                            self.addressPanel.dispatchAddress()
                    except AttributeError:
                        pass
                    
                    try:
                        # Speed - dynamic controler (joystick going back to neutral position)
                        if ((component == self.driver.componentSpeedIncrease) or (component == self.driver.componentSpeedDecrease) or (component == self.driver.componentSpeed)):
                            if ((component == self.driver.componentSpeedIncrease) and (value == self.driver.valueSpeedIncrease)) :
                                self.speedAction.setSpeedIncrement( 0.03 )
                            if ((component == self.driver.componentSpeedDecrease) and (value == self.driver.valueSpeedDecrease)) :
                                self.speedAction.setSpeedIncrement( -0.03 )
                            if (component == self.driver.componentSpeed) :
                                try:
                                    self.vsd = valueSpeedDivider * self.driver.componentSpeedMultiplier
                                except AttributeError:
                                    self.vsd = valueSpeedDivider
                                self.speedAction.setSpeedIncrement(value / self.vsd)
                            if ( abs(value) > self.driver.valueSpeedTrigger ) :
                                self.speedTimer.start()
                            else :
                                self.speedTimer.stop()
                    except AttributeError:
                        self.speedTimer.stop() # just in case, stop it, really should never get there
                    
                    try:
                        # Speed v2 - static controler (lever on RailDriver or AAR105)
                        if (component == self.driver.componentSpeedSet):
                            # negative is lever front, positive is lever back
                            # limit range to only positive side of lever
                            if (value < self.driver.valueSpeedSetMinValue) : value = self.driver.valueSpeedSetMinValue
                            if (value > self.driver.valueSpeedSetMaxValue) : value = self.driver.valueSpeedSetMaxValue
                            # convert fraction of input to speed step
                            self.throttle.setSpeedSetting((value-self.driver.valueSpeedSetMinValue)/(self.driver.valueSpeedSetMaxValue-self.driver.valueSpeedSetMinValue))
                            print "Slider Speed:", self.controlPanel.getDisplaySlider()
                    except AttributeError:
                        pass
                    # Direction
                    try:
                        if ((component == self.driver.componentDirectionForward) and (value == self.driver.valueDirectionForward)) :
                            self.throttle.setIsForward(True)
                        if ((component == self.driver.componentDirectionBackward) and (value == self.driver.valueDirectionBackward)) :
                            self.throttle.setIsForward(False)
                    except AttributeError:
                        pass                    
                    try:                    
                        if ((component == self.driver.componentDirectionSwitch) and (value == self.driver.valueDirectionSwitch)) :
                            self.throttle.setIsForward(not self.throttle.getIsForward())
                    except AttributeError:
                        pass
                    
                    # Speed presets
                    try:  # STOP
                        if ((component == self.driver.componentStopSpeed) and (value == self.driver.valueStopSpeed)) :
                            if ( Calendar.getInstance().getTimeInMillis() - self.lastTimeStopButton < delay4doubleTap ) : 
                                self.throttle.setSpeedSetting(EStopSpeed) # EStop on double tap
                            else:
                                self.throttle.setSpeedSetting(speedStopSpeed)
                            self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis()
                    except AttributeError:
                        pass
                    try:   # EStop
                        if ((component == self.driver.componentEStopSpeed) and (value == self.driver.valueEStopSpeed)):
                            self.throttle.setSpeedSetting(EStopSpeed)
                    except AttributeError:
                        pass
                    try:   # EStop
                        if ((component == self.driver.componentEStopSpeedBis) and (value == self.driver.valueEStopSpeedBis)):
                            self.throttle.setSpeedSetting(EStopSpeed)
                    except AttributeError:
                        pass
                    try:   # SLOW
                        if ((component == self.driver.componentSlowSpeed) and (value == self.driver.valueSlowSpeed)) :
                            self.throttle.setSpeedSetting(speedSlowSpeed)
                    except AttributeError:
                        pass
                    try:   # CRUISE
                        if ((component == self.driver.componentCruiseSpeed) and (value == self.driver.valueCruiseSpeed)) :
                            if ( Calendar.getInstance().getTimeInMillis() - self.lastTimeCruiseButton < delay4doubleTap ) : # EStop on double tap
                                self.throttle.setSpeedSetting(speedMaxSpeed) # Max speed on double tap
                            else:
                                self.throttle.setSpeedSetting(speedCruiseSpeed)
                            self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis()
                    except AttributeError:
                        pass
                    try:   # MAX
                        if ((component == self.driver.componentMaxSpeed) and (value == self.driver.valueMaxSpeed)) :
                            self.throttle.setSpeedSetting(speedMaxSpeed)
                    except AttributeError:
                        pass
                        
                    # Functions
                    try:
                        if ((component == self.driver.componentF0) and (value == self.driver.valueF0)) :
                            self.throttle.setF0( not self.throttle.getF0() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(0)) and (component == self.driver.componentF0) and (value == self.driver.valueF0Off)) :
                            self.throttle.setF0( not self.throttle.getF0() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF1) and (value == self.driver.valueF1)) :
                            self.throttle.setF1( not self.throttle.getF1() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(1)) and (component == self.driver.componentF1) and (value == self.driver.valueF1Off)) :
                            self.throttle.setF1( not self.throttle.getF1() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF2) and (value == self.driver.valueF2)) :
                            self.throttle.setF2( not self.throttle.getF2() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(2)) and (component == self.driver.componentF2) and (value == self.driver.valueF2Off)) :
                            self.throttle.setF2( not self.throttle.getF2() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF3) and (value == self.driver.valueF3)) :
                            self.throttle.setF3( not self.throttle.getF3() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(3)) and (component == self.driver.componentF3) and (value == self.driver.valueF3Off)) :
                            self.throttle.setF3( not self.throttle.getF3() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF4) and (value == self.driver.valueF4)) :
                            self.throttle.setF4( not self.throttle.getF4() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(4)) and (component == self.driver.componentF4) and (value == self.driver.valueF4Off)) :
                            self.throttle.setF4( not self.throttle.getF4() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF5) and (value == self.driver.valueF5)) :
                            self.throttle.setF5( not self.throttle.getF5() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(5)) and (component == self.driver.componentF5) and (value == self.driver.valueF5Off)) :
                            self.throttle.setF5( not self.throttle.getF5() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF6) and (value == self.driver.valueF6)) :
                            self.throttle.setF6( not self.throttle.getF6() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(6)) and (component == self.driver.componentF6) and (value == self.driver.valueF6Off)) :
                            self.throttle.setF6( not self.throttle.getF6() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF7) and (value == self.driver.valueF7)) :
                            self.throttle.setF7( not self.throttle.getF7() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(7)) and (component == self.driver.componentF7) and (value == self.driver.valueF7Off)) :
                            self.throttle.setF7( not self.throttle.getF7() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF8) and (value == self.driver.valueF8)) :
                            self.throttle.setF8( not self.throttle.getF8() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(8)) and (component == self.driver.componentF8) and (value == self.driver.valueF8Off)) :
                            self.throttle.setF8( not self.throttle.getF8() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF9) and (value == self.driver.valueF9)) :
                            self.throttle.setF9( not self.throttle.getF9() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(9)) and (component == self.driver.componentF9) and (value == self.driver.valueF9Off)) :
                            self.throttle.setF9( not self.throttle.getF9() )
                    except AttributeError:
                        pass  
                    try:
                        if ((component == self.driver.componentF10) and (value == self.driver.valueF10)) :
                            self.throttle.setF10( not self.throttle.getF10() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(10)) and (component == self.driver.componentF10) and (value == self.driver.valueF10Off)) :
                            self.throttle.setF10( not self.throttle.getF10() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF11) and (value == self.driver.valueF11)) :
                            self.throttle.setF11( not self.throttle.getF11() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(11)) and (component == self.driver.componentF11) and (value == self.driver.valueF11Off)) :
                            self.throttle.setF11( not self.throttle.getF11() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF12) and (value == self.driver.valueF12)) :
                            self.throttle.setF12( not self.throttle.getF12() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(12)) and (component == self.driver.componentF12) and (value == self.driver.valueF12Off)) :
                            self.throttle.setF12( not self.throttle.getF12() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF13) and (value == self.driver.valueF13)) :
                            self.throttle.setF13( not self.throttle.getF13() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(13)) and (component == self.driver.componentF13) and (value == self.driver.valueF13Off)) :
                            self.throttle.setF13( not self.throttle.getF13() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF14) and (value == self.driver.valueF14)) :
                            self.throttle.setF14( not self.throttle.getF14() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(14)) and (component == self.driver.componentF14) and (value == self.driver.valueF14Off)) :
                            self.throttle.setF14( not self.throttle.getF14() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF15) and (value == self.driver.valueF15)) :
                            self.throttle.setF15( not self.throttle.getF15() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(15)) and (component == self.driver.componentF15) and (value == self.driver.valueF15Off)) :
                            self.throttle.setF15( not self.throttle.getF15() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF16) and (value == self.driver.valueF16)) :
                            self.throttle.setF16( not self.throttle.getF16() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(16)) and (component == self.driver.componentF16) and (value == self.driver.valueF16Off)) :
                            self.throttle.setF16( not self.throttle.getF16() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF17) and (value == self.driver.valueF17)) :
                            self.throttle.setF17( not self.throttle.getF17() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(17)) and (component == self.driver.componentF17) and (value == self.driver.valueF17Off)) :
                            self.throttle.setF17( not self.throttle.getF17() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF18) and (value == self.driver.valueF18)) :
                            self.throttle.setF18( not self.throttle.getF18() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(18)) and (component == self.driver.componentF18) and (value == self.driver.valueF18Off)) :
                            self.throttle.setF18( not self.throttle.getF18() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF19) and (value == self.driver.valueF19)) :
                            self.throttle.setF19( not self.throttle.getF19() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(19)) and (component == self.driver.componentF19) and (value == self.driver.valueF19Off)) :
                            self.throttle.setF19( not self.throttle.getF19() )
                    except AttributeError:
                        pass   
                    
                    try:
                        if ((component == self.driver.componentF20) and (value == self.driver.valueF20)) :
                            self.throttle.setF20( not self.throttle.getF20() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(20)) and (component == self.driver.componentF20) and (value == self.driver.valueF20Off)) :
                            self.throttle.setF20( not self.throttle.getF20() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF21) and (value == self.driver.valueF21)) :
                            self.throttle.setF21( not self.throttle.getF21() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(21)) and (component == self.driver.componentF21) and (value == self.driver.valueF21Off)) :
                            self.throttle.setF21( not self.throttle.getF21() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF22) and (value == self.driver.valueF22)) :
                            self.throttle.setF22( not self.throttle.getF22() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(22)) and (component == self.driver.componentF22) and (value == self.driver.valueF22Off)) :
                            self.throttle.setF22( not self.throttle.getF22() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF23) and (value == self.driver.valueF23)) :
                            self.throttle.setF23( not self.throttle.getF23() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(23)) and (component == self.driver.componentF23) and (value == self.driver.valueF23Off)) :
                            self.throttle.setF23( not self.throttle.getF23() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF24) and (value == self.driver.valueF24)) :
                            self.throttle.setF24( not self.throttle.getF24() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(24)) and (component == self.driver.componentF24) and (value == self.driver.valueF24Off)) :
                            self.throttle.setF24( not self.throttle.getF24() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF25) and (value == self.driver.valueF25)) :
                            self.throttle.setF25( not self.throttle.getF25() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(25)) and (component == self.driver.componentF25) and (value == self.driver.valueF25Off)) :
                            self.throttle.setF25( not self.throttle.getF25() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF26) and (value == self.driver.valueF26)) :
                            self.throttle.setF26( not self.throttle.getF26() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(26)) and (component == self.driver.componentF26) and (value == self.driver.valueF26Off)) :
                            self.throttle.setF26( not self.throttle.getF26() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF27) and (value == self.driver.valueF27)) :
                            self.throttle.setF27( not self.throttle.getF27() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(27)) and (component == self.driver.componentF27) and (value == self.driver.valueF27Off)) :
                            self.throttle.setF27( not self.throttle.getF27() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF28) and (value == self.driver.valueF28)) :
                            self.throttle.setF28( not self.throttle.getF28() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(28)) and (component == self.driver.componentF28) and (value == self.driver.valueF28Off)) :
                            self.throttle.setF28( not self.throttle.getF28() )
                    except AttributeError:
                        pass
                    try:
                        if ((component == self.driver.componentF29) and (value == self.driver.valueF29)) :
                            self.throttle.setF29( not self.throttle.getF29() )
                        if ((self.roster != None) and (not self.roster.getFunctionLockable(29)) and (component == self.driver.componentF29) and (value == self.driver.valueF29Off)) :
                            self.throttle.setF29( not self.throttle.getF29() )
                    except AttributeError:
                        pass
                        
        # Nothing to customize bellow this point
        if (event.propertyName == "ThrottleFrame") :  # Current throttle frame changed
            self.speedTimer.stop()
            event.oldValue.getAddressPanel().removeAddressListener(self)
            self.addressPanel = event.newValue.getAddressPanel()
            self.throttle = self.addressPanel.getThrottle()
            self.roster = self.addressPanel.getRosterEntry()
            self.speedAction.setThrottle( self.throttle )
            event.newValue.getAddressPanel().addAddressListener(self)

#Jynstrument main and mandatory methods
    def getExpectedContextClassName(self):
        return "jmri.jmrit.throttle.ThrottleWindow"
    
    def init(self):
        self.getContext().addPropertyChangeListener(self) #ThrottleFrame change
        self.getContext().getCurrentThrottleFrame().getAddressPanel().addAddressListener(self) # change of throttle in Current frame
        self.addressPanel = self.getContext().getCurrentThrottleFrame().getAddressPanel()
        self.throttle = self.addressPanel.getThrottle() # the throttle
        self.roster = self.addressPanel.getRosterEntry() # roster entry if any
        self.speedAction =  SpeedAction()  #Speed increase thread
        self.speedAction.setThrottle( self.throttle )
        self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc)
        self.speedTimer.setRepeats(True)
        self.label = JButton(ImageIcon(self.getFolder() + "/USBControl.png","USBThrottle")) #label
        self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too
        self.add(self.label)
        self.model = jmri.jmrix.jinput.TreeModel.instance() # USB
        self.desiredController = None
        self.ctrlMenuItem = []
        self.USBDriver = None
        self.driver = None
        mi = JCheckBoxMenuItem ("None")
        self.getPopUpMenu().add( mi )
        mi.addItemListener( ControllerItemListener(None, self) )
        self.ctrlMenuItem.append(mi)
        for ctrl in self.model.controllers(): 
            mi = JCheckBoxMenuItem (ctrl.getName())
            self.getPopUpMenu().add( mi )
            mi.addItemListener( ControllerItemListener(ctrl, self) )
            self.ctrlMenuItem.append(mi)
        if ( len(self.ctrlMenuItem) == 0 ):
            print "No matching USB device found"
        else:
            self.ctrlMenuItem[0].setSelected(True)  # by default connect to the first one
        self.model.addPropertyChangeListener(self)
        self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis()
        self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis()

# On quit clean up resources       
    def quit(self):
        self.speedTimer.stop()
        for mi in self.ctrlMenuItem :
            self.getPopUpMenu().remove( mi )
        self.ctrlMenuItem = None
        self.speedAction = None
        self.speedTimer = None
        self.throttle = None
        self.addressPanel = None
        self.driver = None
        self.USBDriver = None
        self.getContext().removePropertyChangeListener(self)
        self.model.removePropertyChangeListener(self)
        self.getContext().getCurrentThrottleFrame().getAddressPanel().removeAddressListener(self)

# Menu entry changed for Current controller and update driver
    def setSelectedController(self, ctrl, item):
        for mi in self.ctrlMenuItem :
            if ( mi != item ):  # Force deselection of other ones
                mi.setSelected(False)
        self.desiredController = ctrl
        if (ctrl != None) :
            sys.path.append(self.getFolder()) # Load a driver
            try:
                del self.driver
                del self.USBDriver
                dd=ctrl.getName()
                dd=dd.replace(" ", "")
                dd=dd.replace(".", "")
                dd=dd.replace("(", "")
                dd=dd.replace(")", "")
                dd=dd.replace("{", "")
                dd=dd.replace("}", "")
                dd=dd.replace("[", "")
                dd=dd.replace("]", "")              
                self.USBDriver = __import__(dd)           
            except ImportError:  # On error load a default one
                print "Driver \""+ dd +"\" not found in \""+self.getFolder()+"\", loading default one"
                self.USBDriver =  __import__("Default")
            reload(self.USBDriver)
            sys.path.remove(self.getFolder())
            self.driver = self.USBDriver.USBDriver()
    
    def setXml(self, elt):
        if (elt.getChildren("USBThrottle") == None):
            return
        ctrl = elt.getChildren("USBThrottle")[0].getAttributeValue("DesiredController")
        if (ctrl == None):
            return
        for mi in self.ctrlMenuItem :
            if ( mi.getText() == ctrl ):
                mi.setSelected(True)
                break
    
    def getXml(self):
       elt = Element("USBThrottle")
       for mi in self.ctrlMenuItem :
           if (mi.isSelected()) :
               elt.setAttribute("DesiredController", mi.getText())
               break
       return elt

#AddressListener part: to listen for address changes in address panel (release, acquired)
    def notifyAddressChosen(self, address):
        pass
        
    def notifyAddressThrottleFound(self, throttle):
        self.speedTimer.stop() 
        self.throttle = throttle
        self.speedAction.setThrottle( self.throttle )
            
    def notifyAddressReleased(self, address):
        self.speedTimer.stop()
        self.throttle = None
        self.speedAction.setThrottle( self.throttle )

    def notifyConsistAddressChosen(self, address, isLong):
        self.notifyAddressChosen(address)

    def notifyConsistAddressThrottleFound(self, throttle):
        self.notifyAddressThrottleFound(throttle)

    def notifyConsistAddressReleased(self, address, isLong):
        self.notifyAddressReleased(address)
Exemplo n.º 45
0
class Browser:
    def __init__(self, repository):
        self.repository = repository
        # want a better solution, with domains, perhaps user specifies
        self.currentUserReference = System.getProperty("user.name")
        
        self.currentRecord = None
                
        self.window = JFrame("Pointrel browser", windowClosing=self.exit)
        self.window.contentPane.layout = BorderLayout() # redundant as the default
        self.window.bounds = (100, 100, 800, 600)
        
        self.menuBar = JMenuBar()
        self.window.JMenuBar = self.menuBar
        fileMenu = JMenu("File")
        fileMenu.add(JMenuItem("Open...", actionPerformed=self.open))
        fileMenu.add(JMenuItem("Reload", actionPerformed=self.reloadPressed))
        fileMenu.addSeparator()
        fileMenu.add(JMenuItem("Import from other repository...", actionPerformed=self.importFromOtherRepository))
        fileMenu.addSeparator()
        fileMenu.add(JMenuItem("Close", actionPerformed=self.close))
        self.menuBar.add(fileMenu)

        exportMenu = JMenu("Export")
        exportMenu.add(JMenuItem("Choose current export file...", actionPerformed=self.exportChooseCurrentFile))
        exportMenu.addSeparator()        
        exportMenu.add(JMenuItem("Export selected record", actionPerformed=self.exportSelectedRecord))
        exportMenu.add(JMenuItem("Export record history for selected attribute", actionPerformed=self.exportAllRecordsForSelectedAttribute))
        exportMenu.addSeparator()
        exportMenu.add(JMenuItem("Export current records for all attributes of selected entity", actionPerformed=self.exportLatestRecordsForSelectedEntity))
        exportMenu.add(JMenuItem("Export entire record history for all attributes of selected entity", actionPerformed=self.exportAllRecordsForSelectedEntity))
        self.menuBar.add(exportMenu)
        
        self.exportFileName = "export.pointrel"

        #self.reloadButton = JButton("Reload Repository", actionPerformed=self.reloadPressed)
                        
        self.entitiesList = JList(DefaultListModel(), mouseClicked=self.entitiesListClicked)
        self.entitiesList.model.addElement("root")
        self.entitiesList.mousePressed = self.entitiesListMousePressed
        self.entitiesList.mouseReleased = self.entitiesListMousePressed
        
        self.attributesList = JList(DefaultListModel(), mouseClicked=self.attributesListClicked)
        
        self.versionsList = JList(DefaultListModel(), mouseClicked=self.versionsListClicked)
        
        self.listPanel = JPanel(layout=GridLayout(1, 2))
        self.listPanel.add(JScrollPane(self.entitiesList))
        self.listPanel.add(JScrollPane(self.attributesList))
        self.listPanel.add(JScrollPane(self.versionsList))
        
        self.navigationPanel = JPanel(layout=BorderLayout())
        #self.navigationPanel.add(self.reloadButton, BorderLayout.NORTH)
        self.navigationPanel.add(self.listPanel, BorderLayout.CENTER)
                
        self.entityTextField = JTextField(preferredSize=(200,20))
        self.attributeTextField = JTextField(preferredSize=(200,20))
        self.deletedButton = JCheckBox("Deleted", actionPerformed=self.deletedPressed)
        
        # only one right now -- and no support for switching editor panels yet
        examples = ["pointrel:text/utf-8", ]
        self.valueTypeComboBox = JComboBox(examples, preferredSize=(200,20), editable=True)

        self.attributePanel = Box(BoxLayout.X_AXIS) 
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(JLabel("Entity:"))
        self.attributePanel.add(Box.createRigidArea(Dimension(2,0)))
        self.attributePanel.add(self.entityTextField)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(JLabel("Attribute:"))
        self.attributePanel.add(Box.createRigidArea(Dimension(2,0)))
        self.attributePanel.add(self.attributeTextField)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(JLabel("Value type:"))
        self.attributePanel.add(Box.createRigidArea(Dimension(2,0)))
        self.attributePanel.add(self.valueTypeComboBox)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(self.deletedButton)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        
        self.showAllDeletedButton = JCheckBox("Show all deleted", actionPerformed=self.showAllDeletedPressed)
        self.statusText = JTextField(preferredSize=(100,20))
        self.saveButton = JButton("Save", actionPerformed=self.savePressed)
        self.normalSaveButtonColor = self.saveButton.background
        self.changedSaveButtonColor = Color.YELLOW

        self.statusPanel = Box(BoxLayout.X_AXIS)
        self.statusPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.statusPanel.add(self.showAllDeletedButton)
        self.statusPanel.add(Box.createRigidArea(Dimension(25,0)))
        self.statusPanel.add(JLabel("Message:") )
        self.statusPanel.add(Box.createRigidArea(Dimension(2,0)))
        self.statusPanel.add(self.statusText) 
        self.statusPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.statusPanel.add(self.saveButton)
        self.statusPanel.add(Box.createRigidArea(Dimension(1,0)))       
        
        self.currentEditorPanel = EditorPanel_text_utf_8(self, "pointrel:text/utf-8")
        
        self.topPanel = Box(BoxLayout.Y_AXIS)
        self.topPanel.add(Box.createRigidArea(Dimension(0,5))) 
        self.topPanel.add(self.attributePanel)
        self.topPanel.add(Box.createRigidArea(Dimension(0,5))) 
        
        self.editorPanel = JPanel(layout=BorderLayout())
        self.editorPanel.add(self.topPanel, BorderLayout.NORTH)
        self.editorPanel.add(self.currentEditorPanel, BorderLayout.CENTER)
        self.editorPanel.add(self.statusPanel, BorderLayout.SOUTH)
        
        self.browserPanel = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.browserPanel.add(self.navigationPanel)
        self.browserPanel.add(self.editorPanel)
        
        self.window.contentPane.add(self.browserPanel, BorderLayout.CENTER)
        
        self.setTitleForRepository()
        self.window.show()
        
        # background timer for updating save button color
        self.timer = Timer(1000, CallbackActionListener(self.timerEvent))
        self.timer.initialDelay = 1000
        self.timer.start()
        
    def close(self, event):
        System.exit(0)
        
    def open(self, event):
        dialog = FileDialog(self.window)
        fileName = dialog.go(PointrelFileTypes)
        if not fileName:
            return
        repository = Repository(fileName)
        self.repository = repository
        self.currentRecord = None
        self.clearAllEntityNames()
        self.refreshBrowser()
        self.setTitleForRepository()
        
    def setTitleForRepository(self):
        self.window.title = "Pointrel browser on %s" % self.repository.fileName

    def setStatus(self, messageText):
        self.statusText.text = messageText
        
    def getCurrentEntityName(self):
        return self.entityTextField.text

    def setCurrentEntityName(self, newAttributeName):
        self.entityTextField.text = newAttributeName
           
    def getCurrentAttributeName(self):
        return self.attributeTextField.text

    def setCurrentAttributeName(self, newAttributeName):
        self.attributeTextField.text = newAttributeName
           
    def getCurrentValueType(self):
        #return self.valueTypeComboBox.selectedItem
        return self.valueTypeComboBox.editor.editorComponent.text
    
    def setCurrentValueType(self, newValueType):
        self.valueTypeComboBox.selectedItem = newValueType
        # PDF FIX __ NEED TO CHANGE EDITOR TYPE
            
    def reportStatistics(self):
        contents = self.currentEditorPanel.getCurrentValueBytes()
        words = len(contents.split())
        lines = contents.count('\n')
        characters = len(contents)
        report = "%d lines; %d words; %d characters" % (lines, words, characters)
        self.setStatus(report)
        
    def timerEvent(self, event):
        self.manageSaveButtonColor()
        self.reportStatistics()
        
    def exit(self, event=None):
        System.exit(0)
        
    def reloadPressed(self, event):
        print "reloading repository; ", 
        self.repository.reload()
        self.refreshBrowser()
        print "done"
        
    def importCodeFromRepository(self, name, globals=None, locals=None, fromlist=None):
        # seems to fail with stack overflow if print while importing while trying jconsole (it reassigns stdio)
        debug = 0
        self.importLevel += 1
        if debug: print "  " * self.importLevel,
        if debug: print "importCodeFromRepository", name
        try:
            if debug: print "  " * self.importLevel,
            if debug: print "  globals: ", globals
            if debug: print "  " * self.importLevel,
            if debug: print "  locals", locals
            if debug: print "  " * self.importLevel,
            if debug: print "  fromlist", fromlist
        except UnboundLocalError:
            if debug: print "  " * self.importLevel,
            if debug: print "unbound error"
        # Fast path: see if the module has already been imported.
        # though this is wrong -- as need to check repository if code has been changed
        # broken as does not consider fromlist
        #try:
        #    return sys.modules[name]
        #except KeyError:
        #    pass
        # check if local module
        record = self.repository.findLatestRecordForEntityAttribute(self.contextUUID, name + ".py")
        if record:
            if debug: print "  " * self.importLevel,
            if debug: print "  Loading from repository"
            #file = StringIO.StringIO(record.valueBytes)
            #try:
            #module = imp.load_source(name, name, file)
            #print module
            modifiedName = self.contextUUID[7:] + "." + name
            modifiedName = modifiedName.replace("-", "_")
            if debug: print "modifiedName", modifiedName
            if debug: print "sys.module.items", sys.modules.items()
            try:
                module = sys.modules[modifiedName]
            except KeyError:
                module = None
            # use the latest if this one is not
            if module:
                if module.__pointrelIdentifier__ != record.identifierString:
                    module = None
            if not module:
                file = ByteArrayInputStream(record.valueBytes)
                module = imp.load_module(modifiedName, file, modifiedName + ".py", (".py", "r", imp.PY_SOURCE))
                module.__pointrelIdentifier__ = record.identifierString
            if fromlist:
                if debug: print "  " * self.importLevel,
                if debug: print "processing fromlist"
                for fromItemName in fromlist:
                    if debug: print "  " * self.importLevel,
                    if debug: print "fromitemname", fromItemName
                    if fromItemName == "*":
                        for moduleItemName in dir(module):
                            if debug: print "  " * self.importLevel,
                            if debug: print "moduleItemName", moduleItemName
                            if moduleItemName[1] != '_':
                                result = getattr(module, moduleItemName)
                                #print "  " * self.importLevel,
                                #print "result", result
                                #print "  " * self.importLevel,
                                #print "globals", globals
                                globals[moduleItemName] = result
                    else:
                        result = getattr(module, fromItemName)
                        globals[fromItemName] = result
                        if debug: print "finished set", fromItemName
                
            #finally:
            #    file.close()
            if debug: print "  " * self.importLevel,
            if debug: print "  Done loading"
            self.importLevel -= 1
            result = module
        else:
            if debug: print "  " * self.importLevel,
            if debug: print "default loading", name, fromlist
            try:
                result = self.oldimport(name, globals, locals, fromlist)
            except UnboundLocalError:
                # deal with strange Jython error
                result = self.oldimport(name)
            self.importLevel -= 1
        return result
    
    def importFromOtherRepository(self, event):
        dialog = FileDialog(self.window, loadOrSave="load")
        fileName = dialog.go(PointrelFileTypes)
        if not fileName:
            return
        
        print "Importing from: ", fileName
        self.repository.importRecordsFromAnotherRepository(fileName)
        print "Done with import"
        
        self.refreshBrowser()
    
    def exportChooseCurrentFile(self, event):
        dialog = FileDialog(self.window, loadOrSave="save")
        fileName = dialog.go(PointrelFileTypes)
        if not fileName:
            return
        self.exportFileName = fileName
        print "File selected for exports:", self.exportFileName
             
    def exportSelectedRecord(self, event):
        if not self.currentRecord:
            print "No record selected"
            return
        oldRecords = [self.currentRecord]
        print "Exporting current record to repository %s" % self.exportFileName
        repository = Repository(self.exportFileName)
        repository.addRecordsFromAnotherRepository(oldRecords)
        print "Done"
    
    def exportAllRecordsForSelectedAttribute(self, event):
        entityName = self.getCurrentEntityName()
        if not entityName:
           print "No entity selected" 
           return
        attributeName = self.getCurrentAttributeName()
        if not attributeName:
           print "No attribute selected"   
           return   
        print "Exporting all records for entity '%s' attribute '%s' to repository %s" % (entityName, attributeName, self.exportFileName)
        oldRecords = self.repository.findAllRecordsForEntityAttribute(entityName, attributeName)
        oldRecords.reverse()
        repository = Repository(self.exportFileName)
        repository.addRecordsFromAnotherRepository(oldRecords)
        print "Done"
            
    def exportLatestRecordsForSelectedEntity(self, event):
        entityName = self.getCurrentEntityName()
        if not entityName:
           print "No entity selected" 
           return
        print "Exporting latest records for all entity '%s' attributes to repository %s" % (entityName, self.exportFileName)
        oldRecords = self.repository.findLatestRecordsForAllEntityAttributes(entityName)
        oldRecords.reverse()
        repository = Repository(self.exportFileName)
        repository.addRecordsFromAnotherRepository(oldRecords)
        print "Done"
        
    def exportAllRecordsForSelectedEntity(self, event):
        entityName = self.getCurrentEntityName()
        if not entityName:
           print "No entity selected" 
           return
        print "Exporting all records for entity '%s' to repository %s" % (entityName, self.exportFileName)
        oldRecords = self.repository.findAllRecordsForEntity(entityName)
        oldRecords.reverse()
        repository = Repository(self.exportFileName)
        repository.addRecordsFromAnotherRepository(oldRecords)
        print "Done"
               
    def setCurrentRecord(self, aRecord):
        self.currentRecord = aRecord
        if aRecord:
            self.setCurrentEntityName(aRecord.entity)
            self.entityTextField.caretPosition = 0
            self.setCurrentAttributeName(aRecord.attribute)
            self.attributeTextField.caretPosition = 0
            self.setCurrentValueType(aRecord.valueType)
            self.currentEditorPanel.setCurrentValueBytes(aRecord.valueBytes)
            self.deletedButton.model.setSelected(aRecord.deleted)
        else:
            entityName = self.entitiesList.selectedValue
            if entityName == None:
                entityName = ""
            self.setCurrentEntityName(entityName)
            self.entityTextField.caretPosition = 0
            self.setCurrentAttributeName("")
            self.setCurrentValueType(DefaultValueType)
            self.currentEditorPanel.setCurrentValueBytes("") 
            self.deletedButton.model.selected = False
                
    def manageSaveButtonColor(self):
        if self.isCurrentRecordChanged():
            self.saveButton.background = self.changedSaveButtonColor
        else:
            self.saveButton.background = self.normalSaveButtonColor
            
    def isCurrentRecordChanged(self):
        if not self.currentRecord:
            if self.getCurrentAttributeName() or self.currentEditorPanel.getCurrentValueBytes():
                return True
            return False
        if self.getCurrentEntityName() != self.currentRecord.entity:
            return True
        if self.getCurrentAttributeName() != self.currentRecord.attribute:
            return True
        if self.getCurrentValueType() != self.currentRecord.valueType:
            return True
        if self.currentEditorPanel.isChangedFromOriginal():
             return True
        # funky comparison because may be booleans and integers?
        # decided not to test as not really linked to save button
        #if (self.deletedButton.model.selected and not self.currentRecord.deleted) or (not self.deletedButton.model.selected and self.currentRecord.deleted):
        #    return True
        return False

    def deletedPressed(self, event):
        deleteFlag = self.deletedButton.model.selected
        if self.currentRecord == None:
            return 
        self.repository.deleteOrUndelete(self.currentRecord, self.currentUserReference, deleteFlag=deleteFlag)
        if not self.isDeletedViewable():
            self.refreshBrowser()
            
    def refreshBrowser(self):
        entityName = self.entitiesList.selectedValue
        attributeName = self.attributesList.selectedValue
        versionName = self.versionsList.selectedValue
        self.entitiesListClicked(None, entityName, attributeName, versionName)
                    
    def showAllDeletedPressed(self, event):
        self.refreshBrowser()
        
    def isDeletedViewable(self):
        return self.showAllDeletedButton.model.selected
                  
    def savePressed(self, event):
        #entityName = self.entitiesList.selectedValue
        entityName = self.getCurrentEntityName()
        if entityName:
            attributeName = self.getCurrentAttributeName()
            if attributeName:
                attributeValue = self.currentEditorPanel.getCurrentValueBytes()
                attributeType = self.getCurrentValueType()
                newRecord = self.repository.add(entityName, attributeName, attributeValue, attributeType, self.currentUserReference)
                self.setCurrentRecord(newRecord)
                self.entitiesListClicked(None, self.entitiesList.selectedValue, attributeName)
                # refresh list if changed
                if attributeName != self.attributesList.selectedValue:
                    # ? self.attributesList.model.addElement(attributeName)
                    # need to select new version
                    self.entitiesListClicked(None)
                        
    def test(self):
        print "test OK"

    def clearAllEntityNames(self):
        self.entitiesList.model.clear()
        self.addEntityNameToEntitiesList("root")
            
    def deleteEntityNameFromList(self):
        entityName = self.entitiesList.selectedValue
        if entityName:
           self.entitiesList.model.removeElement(entityName)
            
    def addEntitytNameToList(self):
        entityName = JOptionPane.showInputDialog("Enter an entity name: ")
        if entityName:
            self.addEntityNameToEntitiesList(entityName)
            
    def addAllEntityNamesToList(self, addMeta):
        entityNames = self.repository.lastUser.keys()
        entityNames.sort()
        for entityName in entityNames:
            if addMeta or entityName.find("pointrel://tripleID/") != 0:
                self.addEntityNameToEntitiesList(entityName)
           
    def entitiesListMousePressed(self, event):
        if event.isPopupTrigger():
            # options should be a list of (name, function, [arg1, [arg2]]) tuples
            options = [
                       ("add to list..", self.addEntitytNameToList),
                       ("delete from list", self.deleteEntityNameFromList), 
                       (None),
                       ("clear", self.clearAllEntityNames), 
                       (None),
                       ("add all except meta", self.addAllEntityNamesToList, False), 
                       ("add all", self.addAllEntityNamesToList, True), 
                       ]
            menu = OptionsCallbackPopupMenu(event.component, event.x, event.y, options)

    def entitiesListClicked(self, event, entityName=None, attributeName=None, versionName=None):
        if event:
            self.setCurrentRecord(None)
        if entityName:
            self.entitiesList.setSelectedValue(entityName, True)
        else:
            entityName = self.entitiesList.selectedValue
        if entityName:
            self.versionsList.model.clear()
            model = self.attributesList.model 
            model.clear()
            attributes = self.repository.allAttributesForEntity(entityName, self.isDeletedViewable())
            attributes.sort()
            for attribute in attributes:
                model.addElement(attribute)
            if attributeName:
                self.attributesList.setSelectedValue(attributeName, True)
                self.attributesListClicked(None, versionName)
        
    def attributesListClicked(self, event, versionName=None):
        if event:
            self.setCurrentRecord(None)
        entityName = self.entitiesList.selectedValue
        if entityName:
            attributeName = self.attributesList.selectedValue
            if event:
                self.setCurrentAttributeName(attributeName)
            if attributeName:
                model = self.versionsList.model 
                model.clear()
                versions = self.repository.findAllRecordsForEntityAttribute(entityName, attributeName, self.isDeletedViewable())
                for version in versions:
                    versionDescription = "%s %s" % (version.timestamp, version.userReference)
                    model.addElement(versionDescription)
                selectedRecord = None
                if versions:
                    if versionName == None or not model.contains(versionName):
                        self.versionsList.selectedIndex = 0
                        selectedRecord = versions[0]
                    else:
                        versionIndex = model.indexOf(versionName)
                        self.versionsList.selectedIndex = versionIndex
                        selectedRecord = versions[versionIndex]
                self.setCurrentRecord(selectedRecord)
        
                if event and event.clickCount == 2:
                    self.followResource(self.currentRecord)
            else:
                self.setCurrentRecord(None)
        else:
            self.setCurrentRecord(None)
                    
    def versionsListClicked(self, event):
        entityName = self.entitiesList.selectedValue
        if entityName:
            attributeName = self.attributesList.selectedValue
            if event:
                self.setCurrentAttributeName(attributeName)
            if attributeName:
                index = self.versionsList.selectedIndex
                versions = self.repository.findAllRecordsForEntityAttribute(entityName, attributeName, self.isDeletedViewable())
                if versions:
                    versionRecord = versions[index]
                    self.setCurrentRecord(versionRecord)

                    if event and event.clickCount == 2:
                        self.followResource(versionRecord)
                else:
                    self.setCurrentRecord(None)
                    
    def followResource(self, record):
        if not record:
            return
        if '\n' in record.valueBytes:
            print "not following a resource with a newline"
            return
        self.addEntityNameToEntitiesList(record.valueBytes)

    def addEntityNameToEntitiesList(self, entityName):
        self.entitiesList.model.addElement(entityName)
        self.entitiesList.selectedIndex = self.entitiesList.model.size() - 1
        self.entitiesListClicked(None)
        self.setCurrentRecord(None)
Exemplo n.º 46
0
class ProfelisPanel(JPanel):
    def __init__(self, frame, name):
        self.frame = frame
        self.exception = None
        self.name = name
        self.searchTerm = None
        self.searchIndex = -1

        self.searchField = JTextField("")
        self.searchField.addActionListener(SearchListener(self))

        self.newGeneFrom = JTextField("")
        self.newGeneTo = JTextField("")
        self.newGeneButton = JButton("New Gene")
        newGeneActionListener = NewGeneActionListener(self)
        self.newGeneFrom.addActionListener(newGeneActionListener)
        self.newGeneTo.addActionListener(newGeneActionListener)
        self.newGeneButton.addActionListener(newGeneActionListener)

        self.markForRemovalButton = JButton("Mark For Removal")
        self.markForRemovalButton.addActionListener(MarkForRemovalListener(self))
        
        self.inGenes = JList(DefaultListModel())
        self.inGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.inGenes.cellRenderer = ProfelisCellRenderer()
        self.markButtonLabelerTimer = Timer(100, MarkButtonLabeler(self))
        self.markButtonLabelerTimer.start()
        self.loadFile()

        self.outGenes = JList(DefaultListModel())
        self.outGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.outGenes.cellRenderer = ProfelisCellRenderer()
                
        constraints = GridBagConstraints()
        self.layout = GridBagLayout()
        
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes In Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        self.add(JButton(RemoveAction(self)), constraints)
        constraints.gridx, constraints.gridy = 1, 1
        self.add(self.markForRemovalButton, constraints)
        constraints.gridx, constraints.gridy = 2, 1
        self.add(JLabel("Search"), constraints)
        constraints.gridx, constraints.gridy = 3, 1
        constraints.fill = GridBagConstraints.HORIZONTAL
        self.add(self.searchField, constraints)
        constraints.gridx, constraints.gridy = 0, 2
        constraints.gridwidth, constraints.gridheight = 4, 2
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.inGenes), constraints)

        constraints.gridx, constraints.gridy = 4, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes To Add To Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 4, 1
        self.add(self.newGeneButton, constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 5, 1
        self.add(self.newGeneFrom, constraints)
        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 6, 1
        self.add(JLabel("To"), constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 7, 1
        self.add(self.newGeneTo, constraints)

        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 4, 2
        self.add(JButton(AddGenesAction(self)), constraints)
        constraints.gridx, constraints.gridy = 4, 3
        constraints.gridwidth, constraints.gridheight = 4, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.outGenes), constraints)

    def loadFile(self):
        self.inGenes.model.clear()
        self.database, self.evalue, genes = utils.parseBlast(self.name + ".blastp.xml")
        [self.inGenes.model.addElement(gene) for gene in genes]

        artemisInput = open(self.name + ".art", "r")
        lines = artemisInput.readlines()
        artemisInput.close()
        self.restOfFile = self.genome = []
        while lines:
            if re.match("\s+CDS\s+(complement\()?\d+\.\.\d+\)?\n", lines[0]):
                lines = lines[4:]
            elif lines[0].find("ORIGIN") == 0:
                self.genome = map(lambda x: re.sub("\s+", "", x), lines[1:])
                lines = []
            else:
                if lines[0].strip():
                    self.restOfFile.append(lines[0])
                lines = lines[1:]
                
        self.genome = "".join(self.genome)
        self.restOfFile = "".join(self.restOfFile)

    def writeArtemisFile(self):
        output = open(self.name + ".art", "w")
        output.write(self.restOfFile)
        for element in self.inGenes.model.elements():
            output.write(element.toArtemis())
        output.write("\nORIGIN\n\n")
        for i in range(0, len(self.genome), 50):
            output.write(self.genome[i:min(i+50, len(self.genome))] + "\n")
        output.close()
Exemplo n.º 47
0
Arquivo: time.py Projeto: jggatc/pyj2d
 def __init__(self, event):
     self.event = event
     self.timer = Timer(0, self)
     self.repeat = True
Exemplo n.º 48
0
class Example(JFrame, ActionListener):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

# Paint all of the objects in screenObjects
    def mypaint(self, g):
        layerArray = [[] for i in range (100)] #Creating a 100-item array for us to work with.
	for object in screenObjects:
            layerIndex = int(min(object._zLayer, 99)) #This specifies the layer that the object will be headed for...
            layerLoc = 0
            myDepth = object._get("zDepth")
            for compObject in layerArray[layerIndex]: #but first, we need to find the right place in that layer to put our object.
                if (myDepth > compObject._get("zDepth")):
                    layerLoc = layerLoc + 1
                else:
                    break
            layerArray[layerIndex].insert(layerLoc ,object)
        newArray = [] #We now want to compress our scattered 2d-array into a 1d-array.
	for subArray in layerArray: #It's called Radix sorting.
            newArray.extend(subArray)
	#screenObjects = newArray #Turns out you can't actually do this, and I have no idea why.
        for object in newArray: #Instead of going through screenObjects, we go through newArray, which is sorted by layer.
            object._draw(g) #Now calls a _draw method on each object, instead of just having a bunch of lambdas in screenObjects.
            
        
            
# Add an external event on a mouse click
    def myclick(self, x, y):
        externalEvents['LeftMouseButton'] = SP2(x, y)   #SP2 inherited from pythonfrp StaticNumerics.py 
    
    def mykey(self, k):
        externalEvents['KeyTyped']=string(k)
#        print("Key Pressed: " + string(k))

    def my_move(self, x, y):
        mouse_pos[0]= SP2(x,y)

    def initUI(self):
        self.addKeyListener(KA(lambda k: self.mykey(k)))
        self.xp=0
        self.yp=0
        self.canvas=Canvas(lambda g:self.mypaint(g), lambda x, y: self.myclick(x, y), lambda x, y: self.my_move(x, y))
        self.canvas.setBackground(JavaColor(200, 200, 100))
        self.getContentPane().add(self.canvas)
        self.setTitle("Test")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.xSize = 500
        self.ySize = 500
        self.setSize(self.xSize, self.ySize)
        self.setLocationRelativeTo(None)
        self.setBackground(JavaColor(255, 255, 255))
        self.setVisible(True)
        
        #self.button = JButton("This is a button")
        #self.add(self.button, BorderLayout.SOUTH)
        #self.button.addActionListener(self)
        
        self.timer=Timer(50, self)
        self.timer.start()

# This is the heartbeat handling code - this is attached to a timer in the frame      

    def actionPerformed(self, e):
        #if(e.getSource() == self.button):
            #self.addSlider()
        #else:
            currentTime=System.currentTimeMillis()
            #if ((currentTime-startTime[0]) % 75 == 0):
            #    balls.append(circle(p2(random.randrange(50,250),270-localTime*100), 10))
            del screenObjects[:]
    #        print(currentTime-startTime[0])
    #        print('Objects: ' + str(Globals.worldObjects))
            heartbeat((currentTime - startTime[0]) / 1000.0, externalEvents)
            externalEvents.clear()
            self.repaint() 
    def addSlider(self): #adds a new slider at the bottom of the window.
        slider = JSlider()
        self.add(slider, BorderLayout.SOUTH) #this is the best way I could find to make sure the slider appears somewhere consistent.
        self.ySize = self.ySize + 20 #the problem, sadly, is that all of the sliders and buttons and stuff appear at the SAME PLACE, overlapping.
        self.setSize(self.xSize, self.ySize)
Exemplo n.º 49
0
class FunctionControl(core.DataViewComponent, ComponentListener):
    def __init__(self, view, name, func, label=None):
        core.DataViewComponent.__init__(self, label)
        self.view = view
        self.name = name
        self.func = func
        self.label_height = 18
        self.resize_border = 2

        self.popup_hide_limit = JCheckBoxMenuItem('auto-hide limits', True, actionPerformed=self.toggle_autohide)
        self.popup.add(self.popup_hide_limit)
        self.show_limits = False
        self.auto_hide_limits = True
        self.limits_font = Font("Dialog", Font.PLAIN, 10)
        self.limit_width = 0
        self.limit_hide_delay = 1000
        self.limit_color_def = 0.3
        self.limit_color_val = self.limit_color_def
        self.limit_color_step = (1 - self.limit_color_def) / 10
        self.limit_hide_timer = Timer(self.limit_hide_delay / 10, None, actionPerformed=self.hide_limits)
        self.limit_hide_timer.setRepeats(False)

        self.popup.add(JPopupMenu.Separator())
        self.popup.add(JMenuItem('zero', actionPerformed=self.zero))
        self.popup.add(JMenuItem('set value', actionPerformed=self.set_value))

        self.filename = None
        self.popup.add(JMenuItem('set from file...', actionPerformed=self.set_from_file))

        self.popup.add(JPopupMenu.Separator())
        self.popup.add(JMenuItem('increase range', actionPerformed=self.increase_range))
        self.popup.add(JMenuItem('decrease range', actionPerformed=self.decrease_range))
        self.scale_factor = 0.01
        self.range = 1.0

        self.data = self.view.watcher.watch(name, func)

        values = self.data.get_first()
        self.sliders = []
        self.labels = []
        for i, v in enumerate(values):
            vv = int(v * 100 / self.range)
            if vv > 100:
                vv = 100
            if vv < -100:
                vv = -100
            slider = JSlider(JSlider.VERTICAL, -100, 100, vv, stateChanged=lambda event, index=i: self.slider_moved(index))
            slider.background = Color.white
            self.add(slider)
            self.sliders.append(slider)
            label = JLabel('0.00')
            self.add(label)
            self.labels.append(label)
            slider.addMouseListener(self)

        self.setSize(len(values) * 40 + 40, 200)
        self.addComponentListener(self)
        self.componentResized(None)

    def increase_range(self, event):
        self.range *= 2.0
        self.check_label_size()
        self.repaint()

    def decrease_range(self, event):
        self.range *= 0.5
        self.check_label_size()
        self.repaint()

    def check_label_size(self):
        if(self.show_limits):
            limit_label = JLabel(("-%1.2f" % (self.range)))
            limit_width = limit_label.getPreferredSize().width - self.sliders[0].width / 2

            if(limit_width != self.limit_width):
                self.setSize(self.size.width + limit_width - self.limit_width, self.size.height)
                self.setLocation(self.x - limit_width + self.limit_width, self.y)
                self.limit_width = limit_width

    def zero(self, event):
        for i in range(len(self.sliders)):
            self.set_slider_value(i, 0)

    def set_value(self, event):
        try:
            example = ','.join(['%1.1f' % random.uniform(-5, 5) for i in range(len(self.sliders))])
            text = JOptionPane.showInputDialog(self.view.frame, 'Enter input value. \nExample: %s' % example, "Set value", JOptionPane.PLAIN_MESSAGE, None, None, None)
            v = eval(text)
            if isinstance(v, (int, float)):
                v = [v]
            if len(v) > len(self.sliders):
                v = v[:len(self.sliders)]
            for i, vv in enumerate(v):
                self.set_slider_value(i, vv)
        except:
            self.release_value(event)

    def set_from_file(self, event):
        fileChooser = JFileChooser()
        if self.filename is not None:
            fileChooser.setSelectedFile(java.io.File(self.filename))

        if fileChooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION:
            self.filename = fileChooser.selectedFile.absolutePath

            #TODO: this doesn't for for nested FunctionInputs
            input = self.view.network.getNode(self.name)

            from nef.functions import Interpolator
            interp = Interpolator(self.filename)
            interp.load_into_function(input)

    def set_slider_value(self, index, value):
        sv = value / (self.scale_factor * self.range)
        self.sliders[index].value = int(sv)
        self.labels[index].text = '%1.2f' % value
        self.check_label_size()
        self.repaint()
        if self.view.paused:  # change immediately, bypassing filter
            self.data.data[-1][index] = value
            self.view.forced_origins_prev[(self.name, 'origin', index)] = value
        self.view.forced_origins[(self.name, 'origin', index)] = value

    def slider_moved(self, index):
        if self.sliders[index].valueIsAdjusting:   # if I moved it
            v = self.sliders[index].value * self.scale_factor * self.range
            self.labels[index].text = '%1.2f' % v
            if self.view.paused:  # change immediately, bypassing filter
                self.data.data[-1][index] = v
                self.view.forced_origins_prev[(self.name, 'origin', index)] = v

            self.view.forced_origins[(self.name, 'origin', index)] = v

    def paintComponent(self, g):
        temp = self.show_label
        self.show_label = False
        core.DataViewComponent.paintComponent(self, g)
        self.show_label = temp

        if self.show_label:
            g.color = Color(0.3, 0.3, 0.3)
            bounds = g.font.getStringBounds(self.label, g.fontRenderContext)
            g.drawString(self.label, (self.size.width - self.limit_width) / 2 - bounds.width / 2 + self.limit_width, bounds.height)

        self.active = self.view.current_tick >= self.view.timelog.tick_count - 1

        data = self.data.get(start=self.view.current_tick, count=1)[0]
        if data is None:
            data = self.data.get_first()

        if(self.show_limits):
            g.color = Color(self.limit_color_val, self.limit_color_val, self.limit_color_val)
            txt_min = "%1.2f" % (-self.range)
            txt_max = "%1.2f" % (self.range)

            temp_font = g.font
            g.font = self.limits_font

            bounds_min = g.font.getStringBounds(txt_min, g.fontRenderContext)
            bounds_max = g.font.getStringBounds(txt_max, g.fontRenderContext)
            g.drawString(txt_max, 10 + bounds_min.width - bounds_max.width, self.resize_border + self.label_offset + bounds_max.height)
            g.drawString(txt_min, 10, self.height - self.resize_border - self.labels[0].getPreferredSize().height - bounds_min.height)

            g.font = temp_font

        for i, v in enumerate(data):
            while v > self.range * 1.1:
                self.range *= 2
            while v < -self.range * 1.1:
                self.range *= 2

        for i, v in enumerate(data):
            sv = int(v * 100.0 / self.range)
            if sv > 100:
                sv = 100
            if sv < -100:
                sv = -100
            if not self.sliders[i].valueIsAdjusting:
                self.sliders[i].value = sv
            self.labels[i].text = '%1.2f' % v
            self.sliders[i].enabled = self.active

        self.componentResized(None)

    def componentResized(self, e):
        w = self.width - self.resize_border * 2 - self.limit_width
        dw = w / len(self.sliders)
        x = (dw - self.sliders[0].minimumSize.width) / 2
        for i, slider in enumerate(self.sliders):
            slider.setLocation(self.limit_width + self.resize_border + x + i * dw, self.resize_border + self.label_offset)
            slider.setSize(slider.minimumSize.width, self.height - self.resize_border * 2 - 20 - self.label_offset)
            self.labels[i].setLocation(slider.x + slider.width / 2 - self.labels[i].width / 2, slider.y + slider.height)

    def componentHidden(self, e):
        pass

    def componentMoved(self, e):
        pass

    def componentShown(self, e):
        pass

    def save(self):
        info = core.DataViewComponent.save(self)

        if(self.auto_hide_limits):
            self.hide_limits(None)

        info['x'] = self.x            # Overwrite x and width to account for removed limits
        info['width'] = self.width
        info['range'] = self.range
        info['limits'] = self.auto_hide_limits
        info['limits_w'] = self.limit_width
        return info

    def restore(self, d):
        core.DataViewComponent.restore(self, d)
        self.range = d.get('range', 1.0)
        self.auto_hide_limits = d.get('limits', True)
        self.limit_width = d.get('limits_w', 0)
        self.popup_hide_limit.state = self.auto_hide_limits
        self.show_limits = not self.auto_hide_limits

    def mouseEntered(self, event):
        if(self.auto_hide_limits):
            self.disp_limits()
        core.DataViewComponent.mouseEntered(self, event)

    def mouseExited(self, event):
        if(self.auto_hide_limits):
            self.limit_hide_timer.start()
        core.DataViewComponent.mouseExited(self, event)

    def toggle_autohide(self, event):
        self.auto_hide_limits = event.source.state
        if(self.auto_hide_limits):
            self.limit_hide_timer.start()
        else:
            self.disp_limits()

    def disp_limits(self):
        if(not self.show_limits):
            limit_label = JLabel(("-%1.2f" % (self.range)))
            self.limit_width = limit_label.getPreferredSize().width - self.sliders[0].width / 2
            self.setSize(self.size.width + self.limit_width, self.size.height)
            self.setLocation(self.x - self.limit_width, self.y)

        self.limit_hide_timer.stop()
        self.limit_color_val = self.limit_color_def
        self.show_limits = True
        self.repaint()

    def hide_limits(self, event):
        if(self.show_limits):
            if(self.limit_color_val >= 1 - self.limit_color_step):
                self.limit_hide_timer.stop()
                self.setSize(self.size.width - self.limit_width, self.size.height)
                self.setLocation(self.x + self.limit_width, self.y)
                self.limit_width = 0
                self.show_limits = False
            else:
                self.limit_color_val += self.limit_color_step
                self.limit_color_val = min(self.limit_color_val, 1.0)
                self.limit_hide_timer.start()
        self.repaint()
Exemplo n.º 50
0
    class TrackDevice(java.beans.PropertyChangeListener):
        import java
        import javax.swing
        import javax.swing.Timer

        delayTimer = None
        relayClicks = None

        # TrackDevice.init - Initialize a TrackDevice instance for a particular device
        #
        # aName          : Device name
        # aDevice        : JMRI device instance
        # aAllowedStates : Array of states we want to track, other states are ignored
        #
        def init(self, aName, aDevice, aAllowedStates, aLogFile, aParent):
            from javax.swing import Timer
            #print ('TrackDevice.init ' + aName )
            self.DeviceName = aName
            self.Device = aDevice
            self.DeviceValue = self.Device.getValue()
            self.AllowedStates = aAllowedStates
            self.parent = aParent
            self.LogFile = aLogFile

            self.timeoutListener = self.TimeoutReceiver()
            self.timeoutListener.setCallBack(self.receiveTimeoutHandler)
            self.receiveTimer = Timer(1, self.timeoutListener)
            self.receiveTimer.stop()
            self.receiveTimer.setRepeats(False)

            self.sendTimeoutListener = self.TimeoutReceiver()
            self.sendTimeoutListener.setCallBack(self.sendTimeoutHandler)
            self.sendTimer = Timer(1, self.sendTimeoutListener)
            self.sendTimer.stop()
            self.sendTimer.setRepeats(False)

            self.pauseTimeoutListener = self.TimeoutReceiver()
            self.pauseTimeoutListener.setCallBack(self.pauseTimeoutHandler)
            self.pauseTimer = Timer(1, self.pauseTimeoutListener)
            self.pauseTimer.stop()
            self.pauseTimer.setRepeats(False)

            self.relayClicks = jmri.jmrit.Sound(
                "resources/sounds/Code-receive.wav")
            #self.relayClicks = jmri.jmrit.Sound(jmri.util.FileUtil.getExternalFilename("preference:resources/sounds/EnhancedCTCRelay.wav"))
            self.relaySend = jmri.jmrit.Sound("resources/sounds/Code-send.wav")

            return

        # TrackDevice.updateState - Track the device state while reading the old log
        #                           file.  Note the state but don't change the device
        #                           itself and don't log the changes to the new log file
        #                           (yet).
        #
        # aNewState : New device state.
        #
        def updateState(self, aNewState):
            #print 'updateState ' + self.DeviceName
            for i in range(len(self.AllowedStates)):
                if (aNewState == self.AllowedStates[i]):
                    self.DeviceValue = aNewState
                    break

        # TrackDevice.propertyChange - Record state changes as a result of activities
        #                              elsewhere in JMRI
        #
        # aEvent : Event triggering the change (we don't actually look at the event...)
        #
        def propertyChange(self, aEvent):
            #print "Property change " + self.DeviceName
            newValue = self.Device.getValue()

            codeSendSensor = sensors.getSensor("IS16:CCK")
            codeSendSensor.setState(ACTIVE)

            self.relaySend.loop()
            ccdl = 5 + java.util.Random().nextInt(1)  # Code transmission delay
            self.sendTimer.setInitialDelay(ccdl * 10)
            self.sendTimer.start()

            if (newValue == self.DeviceValue):
                return

            for i in range(len(self.AllowedStates)):
                if (newValue == self.AllowedStates[i]):
                    self.DeviceValue = newValue
                    #logStateChange2(self.DeviceName, self.DeviceValue, True)
                    #print "state change " + self.DeviceName + " " + str(self.DeviceValue)
                    self.LogFile.write(self.DeviceName + " " +
                                       self.DeviceValue + "\n")
                    self.LogFile.flush()
                    break
            return

        # TrackDevice.setInitialDeviceState - After reading all of the old tracking file we
        #                                     now initialize the actual devices to their last
        #                                     known states and log these states into the new
        #                                     log file.
        #
        def setInitialDeviceState(self, logFile):
            #       Uncomment the following print statement to display the list of devices being tracked.
            #print "In setInitDeviceState, name = " + self.DeviceName + " value = " + self.DeviceValue
            self.LogFile = logFile
            self.Device.setValue(self.DeviceValue)
            self.Device.addPropertyChangeListener(self)
            #logStateChange2(self.DeviceName, self.DeviceState, False)
            logFile.write(self.DeviceName + " " + self.DeviceValue + "\n")

            signalId = "IS" + self.DeviceName[2:3]
            ctcId = "CTC:TO" + self.DeviceName[2:3]
            # Move the switch lever to the correct position
            if (self.DeviceValue == "P"):

                #print " ctcId = " + ctcId + " state = green"
                turnouts.provideTurnout("NT" +
                                        self.DeviceName[2:3]).setState(CLOSED)
                sensors.getSensor(signalId + ":WLL").setState(INACTIVE)
                sensors.getSensor(signalId + ":WLR").setState(INACTIVE)
                sensors.getSensor(signalId + ":WLC").setState(ACTIVE)

                sensors.getSensor(signalId + ":WKR").setState(INACTIVE)
                sensors.getSensor(signalId + ":WKL").setState(INACTIVE)
                sensors.getSensor(signalId + ":WKC").setState(ACTIVE)

                sensors.getSensor(ctcId + "GK").setState(ACTIVE)
                sensors.getSensor(ctcId + "YK").setState(INACTIVE)
                sensors.getSensor(ctcId + "RK").setState(INACTIVE)

                sensors.getSensor(ctcId + "GS").setState(ACTIVE)
                sensors.getSensor(ctcId + "YS").setState(INACTIVE)
                sensors.getSensor(ctcId + "RS").setState(INACTIVE)

                sensors.getSensor(signalId + ":TOC").setState(INACTIVE)
                sensors.getSensor(signalId + ":TOS").setState(INACTIVE)
                sensors.getSensor(signalId + ":TOP").setState(ACTIVE)
            elif (self.DeviceValue == "C"):
                #print " ctcId = " + ctcId + " state = yellow"
                sensors.getSensor(signalId + ":WLL").setState(ACTIVE)
                sensors.getSensor(signalId + ":WLR").setState(INACTIVE)
                sensors.getSensor(signalId + ":WLC").setState(INACTIVE)
                sensors.getSensor(signalId + ":WKR").setState(INACTIVE)
                sensors.getSensor(signalId + ":WKL").setState(ACTIVE)
                sensors.getSensor(signalId + ":WKC").setState(INACTIVE)

                sensors.getSensor(ctcId + "GK").setState(INACTIVE)
                sensors.getSensor(ctcId + "YK").setState(ACTIVE)
                sensors.getSensor(ctcId + "RK").setState(INACTIVE)

                sensors.getSensor(ctcId + "GS").setState(INACTIVE)
                sensors.getSensor(ctcId + "YS").setState(ACTIVE)
                sensors.getSensor(ctcId + "RS").setState(INACTIVE)

                sensors.getSensor(signalId + ":TOC").setState(ACTIVE)
                sensors.getSensor(signalId + ":TOS").setState(INACTIVE)
                sensors.getSensor(signalId + ":TOP").setState(INACTIVE)

            else:
                #print " ctcId = " + ctcId + " state = red"
                turnouts.provideTurnout("NT" +
                                        self.DeviceName[2:3]).setState(THROWN)
                sensors.getSensor(signalId + ":WLL").setState(INACTIVE)
                sensors.getSensor(signalId + ":WLR").setState(ACTIVE)
                sensors.getSensor(signalId + ":WLC").setState(INACTIVE)
                sensors.getSensor(signalId + ":WKR").setState(ACTIVE)
                sensors.getSensor(signalId + ":WKL").setState(INACTIVE)
                sensors.getSensor(signalId + ":WKC").setState(INACTIVE)

                sensors.getSensor(ctcId + "GK").setState(INACTIVE)
                sensors.getSensor(ctcId + "YK").setState(INACTIVE)
                sensors.getSensor(ctcId + "RK").setState(ACTIVE)

                sensors.getSensor(ctcId + "GS").setState(INACTIVE)
                sensors.getSensor(ctcId + "YS").setState(INACTIVE)
                sensors.getSensor(ctcId + "RS").setState(ACTIVE)

                sensors.getSensor(signalId + ":TOC").setState(INACTIVE)
                sensors.getSensor(signalId + ":TOS").setState(ACTIVE)
                sensors.getSensor(signalId + ":TOP").setState(INACTIVE)

        class TimeoutReceiver(java.awt.event.ActionListener):
            cb = None

            def actionPerformed(self, event):
                if (self.cb != None):
                    self.cb(event)
                return

            def setCallBack(self, cbf):
                self.cb = cbf
                return

        class TimeoutReceiver2(java.awt.event.ActionListener):
            cb = None

            def actionPerformed(self, event):
                if (self.cb != None):
                    self.cb(event)
                return

            def setCallBack(self, cbf):
                self.cb = cbf
                return

        class TimeoutReceiver3(java.awt.event.ActionListener):
            cb = None

            def actionPerformed(self, event):
                if (self.cb != None):
                    self.cb(event)
                return

            def setCallBack(self, cbf):
                self.cb = cbf
                return

        def sendTimeoutHandler(self, event):
            #print "In send timeout handler"
            self.sendTimer.stop()
            self.relaySend.stop()
            sensors.getSensor("IS16:CCK").setState(INACTIVE)

            #sleep(2)

            signalNumber = self.DeviceName[2:3]
            if (self.Device.getValue() == "P"):
                turnouts.provideTurnout("NT" + signalNumber).setState(CLOSED)
            elif (self.Device.getValue() == "S"):
                turnouts.provideTurnout("NT" + signalNumber).setState(THROWN)

            smdl = 5 + java.util.Random().nextInt(2)  # Switch motor delay -

            self.pauseTimer.setInitialDelay(smdl * 10)
            self.pauseTimer.start()
            return

        def pauseTimeoutHandler(self, event):
            #print "In pause timeout handler"
            self.pauseTimer.stop()

            sensors.getSensor("IS17:ICK").setState(ACTIVE)
            #print "Turning on IC light"

            self.relayClicks.loop()
            newName = "IS" + self.DeviceName[2:3]
            sensors.getSensor(newName + ":WKC").setState(INACTIVE)
            sensors.getSensor(newName + ":WKL").setState(INACTIVE)
            sensors.getSensor(newName + ":WKR").setState(INACTIVE)

            ctcName = "CTC:TO" + self.DeviceName[2:3]
            if (sensors.getSensor(ctcName + "YK").getState() == ACTIVE):
                sensors.getSensor(ctcName + "YK").setState(INACTIVE)
            if (sensors.getSensor(ctcName + "GK").getState() == ACTIVE):
                sensors.getSensor(ctcName + "GK").setState(INACTIVE)
            if (sensors.getSensor(ctcName + "RK").getState() == ACTIVE):
                sensors.getSensor(ctcName + "RK").setState(INACTIVE)

            icdl = 5 + java.util.Random().nextInt(3)  # Indicator code delay

            self.receiveTimer.setInitialDelay(icdl * 10)
            self.receiveTimer.start()
            return

        def receiveTimeoutHandler(self, event):
            # see which phase we think we are in
            #print "In receive timeout Handler"
            self.receiveTimer.stop()

            signalNumber = self.DeviceName[2:3]
            #print " Signal number = " + str(signalNumber) + " signal state = " + self.Device.getValue()
            if (self.Device.getValue() == "P"):
                sensors.getSensor("IS" + signalNumber +
                                  ":WKC").setState(ACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":WKR").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":WKL").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOC").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOS").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOP").setState(ACTIVE)

                #sensors.getSensor("CTC:TO" + signalNumber + "YK").setState(INACTIVE)
                sensors.getSensor("CTC:TO" + signalNumber +
                                  "GK").setState(ACTIVE)
                #sensors.getSensor("CTC:TO" + signalNumber + "RK").setState(INACTIVE)

            elif (self.Device.getValue() == "C"):
                sensors.getSensor("IS" + signalNumber +
                                  ":WKC").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":WKR").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":WKL").setState(ACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOS").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOP").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOC").setState(ACTIVE)

                sensors.getSensor("CTC:TO" + signalNumber +
                                  "YK").setState(ACTIVE)
                #sensors.getSensor("CTC:TO" + signalNumber + "GK").setState(INACTIVE)
                #sensors.getSensor("CTC:TO" + signalNumber + "RK").setState(INACTIVE)
                jmri.jmrit.Sound("resources/sounds/Bell.wav").play()
            elif (self.Device.getValue() == "S"):
                sensors.getSensor("IS" + signalNumber +
                                  ":WKC").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":WKR").setState(ACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":WKL").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOC").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOP").setState(INACTIVE)
                sensors.getSensor("IS" + signalNumber +
                                  ":TOS").setState(ACTIVE)

                #sensors.getSensor("CTC:TO" + signalNumber + "YK").setState(INACTIVE)
                #sensors.getSensor("CTC:TO" + signalNumber + "GK").setState(INACTIVE)
                sensors.getSensor("CTC:TO" + signalNumber +
                                  "RK").setState(ACTIVE)

            self.relayClicks.stop()
            self.parent.waitMsec(1000)
            sensors.getSensor("IS17:ICK").setState(INACTIVE)

            return
Exemplo n.º 51
0
    private final int DELAY = 10;

    public Board() {

        initBoard();
    }

    private void initBoard() {

        addKeyListener(new TAdapter());
        setBackground(Color.black);
	setFocusable(true);

        spaceShip = new SpaceShip();

        timer = new Timer(DELAY, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        doDrawing(g);
        
        Toolkit.getDefaultToolkit().sync();
    }
    
    private void doDrawing(Graphics g) {
        
        Graphics2D g2d = (Graphics2D) g;
Exemplo n.º 52
0
    def __init__(self, repository):
        self.repository = repository
        # want a better solution, with domains, perhaps user specifies
        self.currentUserReference = System.getProperty("user.name")
        
        self.currentRecord = None
                
        self.window = JFrame("Pointrel browser", windowClosing=self.exit)
        self.window.contentPane.layout = BorderLayout() # redundant as the default
        self.window.bounds = (100, 100, 800, 600)
        
        self.menuBar = JMenuBar()
        self.window.JMenuBar = self.menuBar
        fileMenu = JMenu("File")
        fileMenu.add(JMenuItem("Open...", actionPerformed=self.open))
        fileMenu.add(JMenuItem("Reload", actionPerformed=self.reloadPressed))
        fileMenu.addSeparator()
        fileMenu.add(JMenuItem("Import from other repository...", actionPerformed=self.importFromOtherRepository))
        fileMenu.addSeparator()
        fileMenu.add(JMenuItem("Close", actionPerformed=self.close))
        self.menuBar.add(fileMenu)

        exportMenu = JMenu("Export")
        exportMenu.add(JMenuItem("Choose current export file...", actionPerformed=self.exportChooseCurrentFile))
        exportMenu.addSeparator()        
        exportMenu.add(JMenuItem("Export selected record", actionPerformed=self.exportSelectedRecord))
        exportMenu.add(JMenuItem("Export record history for selected attribute", actionPerformed=self.exportAllRecordsForSelectedAttribute))
        exportMenu.addSeparator()
        exportMenu.add(JMenuItem("Export current records for all attributes of selected entity", actionPerformed=self.exportLatestRecordsForSelectedEntity))
        exportMenu.add(JMenuItem("Export entire record history for all attributes of selected entity", actionPerformed=self.exportAllRecordsForSelectedEntity))
        self.menuBar.add(exportMenu)
        
        self.exportFileName = "export.pointrel"

        #self.reloadButton = JButton("Reload Repository", actionPerformed=self.reloadPressed)
                        
        self.entitiesList = JList(DefaultListModel(), mouseClicked=self.entitiesListClicked)
        self.entitiesList.model.addElement("root")
        self.entitiesList.mousePressed = self.entitiesListMousePressed
        self.entitiesList.mouseReleased = self.entitiesListMousePressed
        
        self.attributesList = JList(DefaultListModel(), mouseClicked=self.attributesListClicked)
        
        self.versionsList = JList(DefaultListModel(), mouseClicked=self.versionsListClicked)
        
        self.listPanel = JPanel(layout=GridLayout(1, 2))
        self.listPanel.add(JScrollPane(self.entitiesList))
        self.listPanel.add(JScrollPane(self.attributesList))
        self.listPanel.add(JScrollPane(self.versionsList))
        
        self.navigationPanel = JPanel(layout=BorderLayout())
        #self.navigationPanel.add(self.reloadButton, BorderLayout.NORTH)
        self.navigationPanel.add(self.listPanel, BorderLayout.CENTER)
                
        self.entityTextField = JTextField(preferredSize=(200,20))
        self.attributeTextField = JTextField(preferredSize=(200,20))
        self.deletedButton = JCheckBox("Deleted", actionPerformed=self.deletedPressed)
        
        # only one right now -- and no support for switching editor panels yet
        examples = ["pointrel:text/utf-8", ]
        self.valueTypeComboBox = JComboBox(examples, preferredSize=(200,20), editable=True)

        self.attributePanel = Box(BoxLayout.X_AXIS) 
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(JLabel("Entity:"))
        self.attributePanel.add(Box.createRigidArea(Dimension(2,0)))
        self.attributePanel.add(self.entityTextField)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(JLabel("Attribute:"))
        self.attributePanel.add(Box.createRigidArea(Dimension(2,0)))
        self.attributePanel.add(self.attributeTextField)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(JLabel("Value type:"))
        self.attributePanel.add(Box.createRigidArea(Dimension(2,0)))
        self.attributePanel.add(self.valueTypeComboBox)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        self.attributePanel.add(self.deletedButton)
        self.attributePanel.add(Box.createRigidArea(Dimension(5,0)))
        
        self.showAllDeletedButton = JCheckBox("Show all deleted", actionPerformed=self.showAllDeletedPressed)
        self.statusText = JTextField(preferredSize=(100,20))
        self.saveButton = JButton("Save", actionPerformed=self.savePressed)
        self.normalSaveButtonColor = self.saveButton.background
        self.changedSaveButtonColor = Color.YELLOW

        self.statusPanel = Box(BoxLayout.X_AXIS)
        self.statusPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.statusPanel.add(self.showAllDeletedButton)
        self.statusPanel.add(Box.createRigidArea(Dimension(25,0)))
        self.statusPanel.add(JLabel("Message:") )
        self.statusPanel.add(Box.createRigidArea(Dimension(2,0)))
        self.statusPanel.add(self.statusText) 
        self.statusPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.statusPanel.add(self.saveButton)
        self.statusPanel.add(Box.createRigidArea(Dimension(1,0)))       
        
        self.currentEditorPanel = EditorPanel_text_utf_8(self, "pointrel:text/utf-8")
        
        self.topPanel = Box(BoxLayout.Y_AXIS)
        self.topPanel.add(Box.createRigidArea(Dimension(0,5))) 
        self.topPanel.add(self.attributePanel)
        self.topPanel.add(Box.createRigidArea(Dimension(0,5))) 
        
        self.editorPanel = JPanel(layout=BorderLayout())
        self.editorPanel.add(self.topPanel, BorderLayout.NORTH)
        self.editorPanel.add(self.currentEditorPanel, BorderLayout.CENTER)
        self.editorPanel.add(self.statusPanel, BorderLayout.SOUTH)
        
        self.browserPanel = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.browserPanel.add(self.navigationPanel)
        self.browserPanel.add(self.editorPanel)
        
        self.window.contentPane.add(self.browserPanel, BorderLayout.CENTER)
        
        self.setTitleForRepository()
        self.window.show()
        
        # background timer for updating save button color
        self.timer = Timer(1000, CallbackActionListener(self.timerEvent))
        self.timer.initialDelay = 1000
        self.timer.start()
Exemplo n.º 53
0
class XYPlot(core.DataViewComponent):
    def __init__(self, view, name, func, args=(), filter=None, label=None):
        core.DataViewComponent.__init__(self, label)
        self.view = view
        self.name = name
        self.func = func
        self.indices = None
        self.data = self.view.watcher.watch(name, func, args=args)
        self.margin = 10

        self.autozoom = True
        self.last_maxy = None
        self.popup_zoom = JCheckBoxMenuItem('auto-zoom', self.autozoom, stateChanged=self.toggle_autozoom)
        self.popup.add(self.popup_zoom)

        self.autohide = True
        self.show_axes_labels = True
        self.popup_hide = JCheckBoxMenuItem('auto-hide axis labels', True, actionPerformed=self.toggle_autohide)
        self.popup.add(self.popup_hide)

        self.axes_label_init_clr = 0.3
        self.axes_label_clr_val = self.axes_label_init_clr
        self.axes_label_clr_step = (1 - self.axes_label_init_clr) / 10

        self.axes_label_hide_dly = 1000
        self.axes_label_hide_tmr = Timer(self.axes_label_hide_dly / 10, None, actionPerformed=self.fade_axes_labels)

        self.filter = filter
        self.setSize(200, 200)

    def save(self):
        save_info = core.DataViewComponent.save(self)
        save_info['sel_dim'] = self.indices
        save_info['autozoom'] = self.autozoom
        save_info['last_maxy'] = self.last_maxy
        save_info['autohide'] = self.autohide
        return save_info

    def restore(self, d):
        core.DataViewComponent.restore(self, d)
        self.indices = d.get('sel_dim', [0, 1])

        self.autozoom = d.get('autozoom', True)
        self.popup_zoom.state = self.autozoom
        self.last_maxy = d.get('last_maxy', None)

        self.autohide = d.get('autohide', True)
        self.popup_hide.state = self.autohide
        self.show_axes_labels = not self.autohide

        self.fix_popup()

    def toggle_autozoom(self, event):
        self.autozoom = event.source.state
        self.repaint()

    def toggle_autohide(self, event):
        self.autohide = event.source.state
        if(self.autohide):
            self.axes_label_hide_tmr.start()
        else:
            self.disp_axes_labels()

    def fix_popup(self):
        self.popup.add(JPopupMenu.Separator())

        # Add submenus for x and y axes
        x_menu = JMenu("X Axis")
        y_menu = JMenu("Y Axis")
        self.popup.add(x_menu)
        self.popup.add(y_menu)

        x_btngrp = ButtonGroup()
        y_btngrp = ButtonGroup()

        # Calculate number of submenu layers needed
        max_ind = len(self.data.get_first())
        num_sub = max(1, int(ceil(log(max_ind) / log(self.max_show_dim))))
        max_sub = [self.max_show_dim ** (num_sub - i) for i in range(num_sub)]

        x_subs = [x_menu] * num_sub
        y_subs = [y_menu] * num_sub

        for i in range(max_ind):
            if(i % self.max_show_dim == 0):
                for n in range(num_sub - 1):
                    if(i % max_sub[n + 1] == 0):
                        new_xmenu = JMenu("%s[%d:%d]" % ('v', i, min(max_ind, i + max_sub[n + 1]) - 1))
                        new_ymenu = JMenu("%s[%d:%d]" % ('v', i, min(max_ind, i + max_sub[n + 1]) - 1))
                        x_subs[n].add(new_xmenu)
                        x_subs[n + 1] = new_xmenu
                        y_subs[n].add(new_ymenu)
                        y_subs[n + 1] = new_ymenu
            x_radio = JRadioButtonMenuItem('%s[%d]' % ('v', i), i == self.indices[0], actionPerformed=lambda x, index=i, self=self: self.indices.__setitem__(0, index))
            y_radio = JRadioButtonMenuItem('%s[%d]' % ('v', i), i == self.indices[1], actionPerformed=lambda x, index=i, self=self: self.indices.__setitem__(1, index))

            x_btngrp.add(x_radio)
            y_btngrp.add(y_radio)

            x_subs[num_sub - 1].add(x_radio)
            y_subs[num_sub - 1].add(y_radio)

    def mouseEntered(self, event):
        if(self.autohide):
            self.disp_axes_labels()
        core.DataViewComponent.mouseEntered(self, event)

    def mouseExited(self, event):
        if(self.autohide):
            self.axes_label_hide_tmr.start()
        core.DataViewComponent.mouseExited(self, event)

    def disp_axes_labels(self):
        self.axes_label_clr_val = self.axes_label_init_clr
        self.show_axes_labels = True
        self.axes_label_hide_tmr.stop()
        self.repaint()

    def fade_axes_labels(self, event):
        if(self.show_axes_labels):
            if(self.axes_label_clr_val >= 1 - self.axes_label_clr_step):
                self.axes_label_hide_tmr.stop()
                self.show_axes_labels = False
            else:
                self.axes_label_clr_val += self.axes_label_clr_step
                self.axes_label_clr_val = min(1, self.axes_label_clr_val)
                self.axes_label_hide_tmr.start()
        self.repaint()

    def paintComponent(self, g):
        core.DataViewComponent.paintComponent(self, g)

        xc = self.width / 2
        yc = (self.height - self.label_offset) / 2
        x0 = self.margin / 2.0
        y0 = self.margin / 2.0
        g.color = Color(0.8, 0.8, 0.8)
        g.drawRect(int(x0) - 1, int(y0 + self.label_offset) - 1, int(self.size.width - self.margin) + 1, int(self.size.height - self.label_offset - self.margin) + 1)
        g.drawLine(xc, self.margin + self.label_offset, xc, self.height - self.margin)
        g.drawLine(self.margin, yc + self.label_offset, self.width - self.margin, yc + self.label_offset)

        dt_tau = None
        if self.filter and self.view.tau_filter > 0:
            dt_tau = self.view.dt / self.view.tau_filter

        pts = int(self.view.time_shown / self.view.dt)
        try:
            data = self.data.get(start=self.view.current_tick - pts + 1, count=pts, dt_tau=dt_tau)
        except:
            return

        if data is None:
            return

        if(self.indices is None):
            self.indices = [0, 1]
            self.fix_popup()

        xs = [d[self.indices[0]] for d in data if d is not None]
        ys = [d[self.indices[1]] for d in data if d is not None]
        if len(xs) > 0:
            mx = max(max(xs), max(ys), -min(xs), -min(ys))
            mx = round(mx)[1]
            if mx < 1.0:
                mx = 1.0
        else:
            mx = 1.0

        if(not self.autozoom and self.last_maxy is not None and mx < self.last_maxy):
            mx = self.last_maxy

        self.last_maxy = mx

        g.color = Color.black

        txt = '%g' % mx
        bounds = g.font.getStringBounds(txt, g.fontRenderContext)
        #g.drawString(txt,xc+self.margin,bounds.height)
        g.drawString(txt, xc + x0, bounds.height + self.margin + self.label_offset)
        g.drawString(txt, self.width - self.margin - bounds.width, yc + bounds.height + self.label_offset)

        txt = '%g' % (-mx)
        #g.drawString(txt,xc+self.margin,self.height-self.margin)
        g.drawString(txt, xc + x0, self.height - self.margin)
        g.drawString(txt, self.margin, yc + bounds.height + self.label_offset)

        if(self.show_axes_labels):
            g.color = Color(self.axes_label_clr_val, self.axes_label_clr_val, self.axes_label_clr_val)
            txt = '%s[%d]' % ('v', self.indices[0])
            boundsl = g.font.getStringBounds(txt, g.fontRenderContext)
            g.drawString(txt, self.width - self.margin - boundsl.width, yc - y0 + self.label_offset)

            txt = '%s[%d]' % ('v', self.indices[1])
            boundsl = g.font.getStringBounds(txt, g.fontRenderContext)
            g.drawString(txt, xc - x0 - boundsl.width, bounds.height + self.margin + self.label_offset)

        g.color = Color.black

        pdftemplate = getattr(self.view.area, 'pdftemplate', None)
        if pdftemplate is not None:
            pdf, scale = pdftemplate
            pdf.setLineWidth(0.5)
            last_color = None

        sx = (self.width / 2 - self.margin) / mx
        sy = (yc - self.margin) / mx
        for i in range(pts - 1):
            if data[i] is not None and data[i + 1] is not None:
                x0 = data[i][self.indices[0]]
                y0 = data[i][self.indices[1]]
                x1 = data[i + 1][self.indices[0]]
                y1 = data[i + 1][self.indices[1]]

                c = 1.0 - i / float(pts - 1)
                g.color = Color(c, c, c)

                if pdftemplate is None:
                    g.drawLine(int(xc + x0 * sx), int(yc - y0 * sy + self.label_offset), int(xc + x1 * sx), int(yc - y1 * sy + self.label_offset))
                else:
                    c = int(c * 32) * 8
                    if c > 255:
                        c = 255
                    if c != last_color:
                        if last_color is not None:
                            pdf.setRGBColorStroke(last_color, last_color, last_color)
                            pdf.stroke()
                        pdf.moveTo(((xc + x0 * sx) + self.x) * scale, 800 - (self.y + yc - y0 * sy + self.label_offset) * scale)
                        last_color = c
                    pdf.lineTo(((xc + x1 * sx) + self.x) * scale, 800 - (self.y + yc - y1 * sy + self.label_offset) * scale)

        if pdftemplate is not None:
            pdf.setRGBColorStroke(last_color, last_color, last_color)
            pdf.stroke()
Exemplo n.º 54
0
Arquivo: time.py Projeto: jggatc/pyj2d
class _EventTimer(ActionListener):
    def __init__(self, event):
        self.event = event
        self.timer = Timer(0, self)
        self.repeat = True

    def set_timer(self, time, repeat):
        if self.timer.isRunning():
            self.timer.stop()
        if time:
            self.repeat = repeat
            self.timer.setInitialDelay(time)
            self.timer.setDelay(time)
            self.timer.start()

    def actionPerformed(self, evt):
        env.event.post(self.event)
        if not self.repeat:
            self.timer.stop()
Exemplo n.º 55
0
class Board(JPanel, KeyListener, ActionListener):
    def __init__(self):
        super(Board, self).__init__()

        self.initUI()


    def initUI(self):
        
        self.setBackground(Color.black)

        iid = ImageIcon("dot.png")
        self.ball = iid.getImage()

        iia = ImageIcon("apple.png")
        self.apple = iia.getImage()

        iih = ImageIcon("head.png")
        self.head = iih.getImage()

        self.setFocusable(True)
        self.addKeyListener(self)
        self.initGame()


    def initGame(self):

        self.left = False
        self.right = True
        self.up = False
        self.down = False
        self.inGame = True
        self.dots = 3

        for i in range(self.dots):
            x[i] = 50 - i * 10
            y[i] = 50


        self.locateApple()

        self.timer = Timer(DELAY, self)
        self.timer.start()
    


    def paint(self, g):

        # due to bug, cannot call super()
        JPanel.paint(self, g)

        if self.inGame:
            self.drawObjects(g)

        else:
            self.gameOver(g)

    def drawObjects(self, g):
        
        g.drawImage(self.apple, self.apple_x, self.apple_y, self)

        for z in range(self.dots):
            if (z == 0):
                g.drawImage(self.head, x[z], y[z], self)
            else:
                g.drawImage(self.ball, x[z], y[z], self)

        Toolkit.getDefaultToolkit().sync()
        g.dispose()

    def gameOver(self, g):

        msg = "Game Over"
        small = Font("Helvetica", Font.BOLD, 14)
        metr = self.getFontMetrics(small)

        g.setColor(Color.white)
        g.setFont(small)
        g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2,
                     HEIGHT / 2)


    def checkApple(self):

        if x[0] == self.apple_x and y[0] == self.apple_y:
            self.dots = self.dots + 1
            self.locateApple()


    def move(self):

        z = self.dots

        while z > 0:
            x[z] = x[(z - 1)]
            y[z] = y[(z - 1)]
            z = z - 1

        if self.left:
            x[0] -= DOT_SIZE

        if self.right:
            x[0] += DOT_SIZE

        if self.up:
            y[0] -= DOT_SIZE

        if self.down:
            y[0] += DOT_SIZE


    def checkCollision(self):

        z = self.dots

        while z > 0:
            if z > 4 and x[0] == x[z] and y[0] == y[z]:
                self.inGame = False
            z = z - 1

        if y[0] > HEIGHT - DOT_SIZE:
            self.inGame = False

        if y[0] < 0:
            self.inGame = False

        if x[0] > WIDTH - DOT_SIZE:
            self.inGame = False

        if x[0] < 0:
            self.inGame = False

    def locateApple(self):

        r = random.randint(0, RAND_POS)
        self.apple_x = r * DOT_SIZE
        r = random.randint(0, RAND_POS)
        self.apple_y = r * DOT_SIZE

#    public void actionPerformed(ActionEvent e) {

    def actionPerformed(self, e):

        if self.inGame:
            self.checkApple()
            self.checkCollision()
            self.move()
        else:
            self.timer.stop()
        
        self.repaint()
    

    def keyPressed(self, e):

        key = e.getKeyCode()

        if key == KeyEvent.VK_LEFT and not self.right:
            self.left = True
            self.up = False
            self.down = False


        if key == KeyEvent.VK_RIGHT and not self.left:
            self.right = True
            self.up = False
            self.down = False

        if key == KeyEvent.VK_UP and not self.down:
            self.up = True
            self.right = False
            self.left = False

        if key == KeyEvent.VK_DOWN and not self.up:
            self.down = True
            self.right = False
            self.left = False
 def __init__(self):
     from javax.swing import Timer
     self.timer = Timer(5000, self)
     self.timer.start()
Exemplo n.º 57
0
 def __init__(self, numRows, numCols):
     self.numRows = numRows
     self.numCols = numCols
     self.timer = Timer(250, None, actionPerformed=self._step)
Exemplo n.º 58
0
 def __init__(self, numRows, numCols):
     self.numRows = numRows
     self.numCols = numCols
     self.timer = Timer(250, None, actionPerformed=self._step)
Exemplo n.º 59
0
class CommandClient():
    def __init__(self, extender):
        self._syncTimer = Timer(1000, None)
        self._syncTimer.setRepeats(True)
        self._syncTimer.actionPerformed = self._sendCommandSync
        self._syncTimer.stop()

        self.commandListenPort = 8089;

        self._startTimer = Timer(1000, None)
        self._startTimer.setInitialDelay(1500)
        self._startTimer.setRepeats(False)
        self._startTimer.actionPerformed = self._sendCommandStart
        self._startTimer.stop()

        self._extender = extender

    def startCrawling(self):
        self._startTimer.start()
    def startSync(self):
        self._syncTimer.start()

    def stopCrawling(self):
        self._sendCommandStop(None)
        self._syncTimer.stop()

    def _sendCommandStart(self, ev):
        self._sendCommand("start")
        self.startSync()

    def _sendCommandStop(self, ev):
        self._sendCommand("stop")

    def _sendCommandSync(self, ev):
        result = self._sendCommand("sync")
        self._extender.syncCrawlingState(result)

    def _sendCommand(self, command):
        url = 'http://127.0.0.1:' + str(self.commandListenPort) + '/?command={0}'.format(command)
        # TODO: iterate through parameters

        response =  urllib2.urlopen(url)
        data = json.load(response)
        return data