Ejemplo n.º 1
0
def run_example(network, runner):
    """Used to conveniently create a NengoGraphics instance
    with an existing Network model.

    """
    if isinstance(network, UINetwork):
        model = network
        model_ui = network
    elif isinstance(network, NetworkImpl):
        model = network
        nengo = NengoGraphics()

        task = TrackedStatusMsg("Creating Model UI")
        model_ui = UINetwork(model)
        nengo.world.ground.addChild(model_ui)
        model_ui.openViewer()
        task.finished()

    print "Running example: " + network.name

    # All UI functions and constructors must be invoked from the Swing
    # Event Thread

    if not isinstance(runner, Runnable):
        runner = make_runnable(runner)
    SwingUtilities.invokeLater(runner)
Ejemplo n.º 2
0
 def clearList(self, event):
     self._extender._lock.acquire()
     oldSize = self._extender._log.size()
     self._extender._log.clear()
     SwingUtilities.invokeLater(
         UpdateTableEDT(self._extender, "delete", 0, oldSize - 1))
     self._extender._lock.release()
Ejemplo n.º 3
0
    def updateComboboxList(self, serv_dict):
        # Update the combobox items after location urls have been found
        def updateComboboxList_run(serv_dict):
            # Reinitialize the two comboboxes
            try:
                self.upnpcombo_targets.removeAllItems()
                self.upnpcombo_services.removeAllItems()
                self.upnpcombo_actions.removeAllItems()
            except BaseException as e:
                print(e)
            # First check if any UPnP service was found
            if not serv_dict:
                self.upnpcombo_targets.addItem("No UPnP services found")
                return
            # Build a dict of found IPs and location urls
            for scdp_url in serv_dict:
                parsed_scdp_url = urlparse(scdp_url)
                scdp_ip = parsed_scdp_url.netloc.split(":")[0]
                if scdp_ip in self.ip_service_dict:
                    # Append the new number to the existing array at this slot
                    self.ip_service_dict[scdp_ip].append(scdp_url)
                else:
                    # Create a new array in this slot
                    self.ip_service_dict[scdp_ip] = [scdp_url]

            # Add all the found IPs to the targets combo box
            for ip in self.ip_service_dict:
                self.upnpcombo_targets.addItem(ip)

            # Select the first element in the combobox by default - this will trigger the other comoboboxes to update
            self.upnpcombo_targets.setSelectedIndex(0)

        # Call the runnable method to update the plugin UI with results
        SwingUtilities.invokeLater(
            PyRunnable(updateComboboxList_run, serv_dict))
    def run(self):
        """ Execute the in-place scaling of the ImagePlus,
        here playing the role of a costly operation. """
        if self.getState("restore"):
            print "Restoring original"
            ip = self.original_ip
            self.putState("restore", False)
        else:
            requested, last = self.getState("requested_scaling_factor",
                                            "last_scaling_factor")
            if requested == last:
                return  # nothing to do
            print "Scaling to", requested
            new_width = int(self.original_ip.getWidth() * requested)
            ip = self.original_ip.resize(new_width)
            self.putState("last_scaling_factor", requested)

        # Request updating the ImageProcessor in the event dispatch thread,
        # given that the "setProcessor" method call will trigger
        # a change in the dimensions of the image window
        SwingUtilities.invokeAndWait(lambda: self.imp.setProcessor(ip))

        # Terminate recurrent execution if so requested
        if self.getState("shutdown"):
            self.scheduled_executor.shutdown()
Ejemplo n.º 5
0
def invokeThreadsafe(fn, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return fn(*args, **kwargs)
    else:
        task = FunctionCall(fn, args, kwargs)
        SwingUtilities.invokeAndWait(task)
        return task.getResult()
Ejemplo n.º 6
0
    def keyPressed(self, event):
        if event.isControlDown() and event.isShiftDown(
        ):  # like in e.g. a web browser
            sign = {
                KeyEvent.VK_MINUS: -1,
                KeyEvent.VK_PLUS: 1,
                KeyEvent.VK_EQUALS: 1
            }.get(event.getKeyCode(), 0)
            if 0 == sign: return
            # Adjust font size of all UI components
            for component in components:
                font = component.getFont()
                if not font: continue
                size = max(8.0, font.getSize2D() + sign * 0.5)
                if size != font.getSize2D():
                    component.setFont(font.deriveFont(size))

            def repaint():
                # Adjust the height of a JTable's rows (why it doesn't do so automatically is absurd)
                for table in tables:
                    if table.getRowCount() > 0:
                        r = table.prepareRenderer(table.getCellRenderer(0, 0),
                                                  0, 0)
                        table.setRowHeight(
                            max(table.getRowHeight(),
                                r.getPreferredSize().height))
                for frame in frames:
                    if frame.isVisible():
                        frame.pack()
                        frame.repaint()

            SwingUtilities.invokeLater(repaint)
Ejemplo n.º 7
0
        def matchRegex(baseURL, res):
            toRet = []
            for (name, regStr, ret) in self.regexTableModel.data:
                matchObj = re.findall(regStr, res, re.M | re.I)
                for i in matchObj:
                    try:
                        if i.find('http://') == 0 or i.find('https://') == 0:
                            url = i
                        elif i[0] == '/':
                            url = host + i
                        else:
                            url = host + '/' + i

                        if url not in pageType:
                            pageType[url] = name
                            SwingUtilities.invokeLater(
                                CrawlerRunnable(self.resultTableModel.addRow,
                                                ([name, url], )))

                            if ret:
                                toRet.append(url)
                    except:
                        print("Error when trying to save result ", i,
                              sys.exc_info()[0],
                              sys.exc_info()[1])
            return toRet
Ejemplo n.º 8
0
    def addVulnerability(self, issueKey, additionalInfo=None):
        print "TEST FOUND: [%s] - %s" % (issueKey, additionalInfo)

        # Add issue to summary list
        issue = SSLIssue(issueKey, self.url, self.helpers)
        if not (additionalInfo is None):
            issue.setIssueDetail(additionalInfo)

        self.issueList.append(issue)

        # Add to Burp issue
        if self.addToSitemap:
            scanIssues = self.callbacks.getScanIssues(self.url.getProtocol() +
                                                      "://" +
                                                      self.url.getHost())
            # Check if the issue already exists
            for oldIssue in scanIssues:
                try:
                    if oldIssue.getIssueName() == issue.getIssueName():
                        # exists
                        break
                except BaseException as e:
                    pass
            else:
                # Not exists, add new issue
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.callbacks.addScanIssue, (issue, )))
Ejemplo n.º 9
0
def invokeThreadsafe(fn, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return fn(*args, **kwargs)
    else:
        task = FunctionCall(fn, args, kwargs)
        SwingUtilities.invokeAndWait(task)
        return task.getResult()
Ejemplo n.º 10
0
def isRightMouseButton(*args):
   isGPanelValid()
   if len(args) == 1:
      return SwingUtilities.isRightMouseButton(args[0])
   if __event != None and SwingUtilities.isRightMouseButton(__event):
      return True
   return False
Ejemplo n.º 11
0
 def mouseClicked(self, event):
     if SwingUtilities.isLeftMouseButton(event) and event.clickCount == 2:
         if not self.isEditing:
             self.setEditing(True)
     elif SwingUtilities.isLeftMouseButton(event) and event.clickCount == 1:
         idx = self.tabbed_pane.indexOfTabComponent(self)
         self.tabbed_pane.selectedIndex = idx
Ejemplo n.º 12
0
 def action(self):
     node = ModelFactory.constructModel(constructable)
     if node is None:
         raise Exception("No model was created")
     elif isinstance(node, Node):
         SwingUtilities.invokeAndWait(make_runnable(self.add_and_open))
     else:
         raise Exception("Can not add model of the type: " + node.class.simpleName)
Ejemplo n.º 13
0
def _swingWaitForResult(func, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
        
    wrappedCode = _JythonCallable(func, args, kwargs)
    task = FutureTask(wrappedCode)
    SwingUtilities.invokeAndWait(task)
    return task.get()
Ejemplo n.º 14
0
def isRightMouseButton(*args):
   if len(args) == 1:
      return SwingUtilities.isRightMouseButton(args[0])
   if __event == None and  _turtleFrame.getMouseHitButton() == 3:
      return True
   if __event != None and SwingUtilities.isRightMouseButton(__event):
      return True
   return False
Ejemplo n.º 15
0
	def addToLog(self, messageInfo, XSSimp, SQLiimp, SSTIimp, parameters, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description, req_time):
		requestInfo = self._helpers.analyzeRequest(messageInfo)
		method = requestInfo.getMethod()
		self._lock.acquire()
		row = self._log.size()
		self._log.add(LogEntry(self._callbacks.saveBuffersToTempFiles(messageInfo), requestInfo.getUrl(),method,XSSimp,SQLiimp,SSTIimp,req_time, parameters,resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description)) # same requests not include again.
		SwingUtilities.invokeLater(UpdateTableEDT(self,"insert",row,row))
		self._lock.release()
Ejemplo n.º 16
0
 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)
Ejemplo n.º 17
0
def _swingRunner(func, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
    else:
        wrappedCode = _JythonCallable(func, args, kwargs)
        task = FutureTask(wrappedCode)
        SwingUtilities.invokeLater(task)
        return task.get()
Ejemplo n.º 18
0
def _swingWaitForResult(func, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)

    wrappedCode = _JythonCallable(func, args, kwargs)
    task = FutureTask(wrappedCode)
    SwingUtilities.invokeAndWait(task)
    return task.get()
Ejemplo n.º 19
0
def runSwingLater(func, *args, **kwargs):
    """
    Queues the given task to be run in the Event Dispatch Thread, regardless
    of whether the calling thread is the EDT itself.

    """
    runnable = RunnableWrapper(func, args, kwargs)
    SwingUtilities.invokeLater(runnable)
Ejemplo n.º 20
0
    def getButtonIdentifier(self):
        intFrame = SwingUtilities.getAncestorOfClass(JInternalFrame, self.widget.widget)
        if intFrame:
            return intFrame.getTitle()

        icon = SwingUtilities.getAncestorOfClass(JInternalFrame.JDesktopIcon, self.widget.widget)  # @UndefinedVariable
        if icon:
            return self.widget.widget.getLabel()
Ejemplo n.º 21
0
def _swingRunner(func, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
    else:
        wrappedCode = _JythonCallable(func, args, kwargs)
        task = FutureTask(wrappedCode)
        SwingUtilities.invokeLater(task)
        return task.get()
Ejemplo n.º 22
0
def runSwingLater(func, *args, **kwargs):
    """
    Queues the given task to be run in the Event Dispatch Thread, regardless
    of whether the calling thread is the EDT itself.

    """
    runnable = RunnableWrapper(func, args, kwargs)
    SwingUtilities.invokeLater(runnable)
Ejemplo n.º 23
0
 def __timer_noswing(self, *args):
     #print "#### >>>>>>>>>>> timer noswing enter."
     if self.timer != None:
         self.timer.cancel()
     self.__previous_cursor = self.tree.getCursor()
     SwingUtilities.invokeLater(self.__set_wait_cursor)
     self.exp = getExpansionState(self.tree)
     self.model = createTreeModel(self.mapContext)
     SwingUtilities.invokeLater(self.__timer_swing)
 def valueChanged(self, event):
   if event.getValueIsAdjusting():
     return
   # Must run later, when the event dispatch thread
   # has updated the selection
   def after():
     rowIndex = table.getSelectionModel().getLeadSelectionIndex()
     textarea.setText(applicants[rowIndex][2])
   SwingUtilities.invokeLater(after)
Ejemplo n.º 25
0
 def flip(self):
     """
     Repaint display.
     """
     self._rect_list = self._surface_rect
     try:
         SwingUtilities.invokeAndWait(self)
     except InterruptedException:
         Thread.currentThread().interrupt()
Ejemplo n.º 26
0
 def flip(self):
     """
     Repaint display.
     """
     self._rect_list = self._surface_rect
     try:
         SwingUtilities.invokeAndWait(self)
     except InterruptedException:
         Thread.currentThread().interrupt()
Ejemplo n.º 27
0
def runOnEventDispatchThread(method, *args):
    class EDTRunnable(Runnable):
        def run(self):
            method(*args)
    
    if SwingUtilities.isEventDispatchThread():
        method(*args)
    else:
        SwingUtilities.invokeAndWait(EDTRunnable())
Ejemplo n.º 28
0
        def selectWhenRightClickEvent(event):
            def select(e):
                rowAtPoint = self.resultTable.rowAtPoint(
                    SwingUtilities.convertPoint(self.resultTablePopupMenu,
                                                Point(0, 0), self.resultTable))
                if rowAtPoint > -1:
                    self.resultTable.setRowSelectionInterval(
                        rowAtPoint, rowAtPoint)

            SwingUtilities.invokeLater(CrawlerRunnable(select, (event, )))
Ejemplo n.º 29
0
 def __timer_swing(self, *args):
     #print "#### >>>>>>>>>>> timer swing1 enter."
     if self.model != None:
         #print "#### >>>>>>>>>>> timer swing2."
         self.tree.setModel(self.model)
         self.tree.getModel().reload()
         setExpansionState(self.tree, self.exp)
         self.tree.revalidate()
         self.tree.repaint()
     SwingUtilities.invokeLater(self.__restore_cursor)
Ejemplo n.º 30
0
def hasComplexAncestors(widget):
    if any((SwingUtilities.getAncestorOfClass(widgetClass, widget) is not None
            for widgetClass in [ JTable, JScrollBar, JComboBox, JSpinner ])):
        return True
    
    # If we're in a popup menu that's attached to something with complex ancestors, that's clearly even more complex :)
    popup = SwingUtilities.getAncestorOfClass(JPopupMenu, widget)
    if popup and isinstance(popup.getInvoker(), JComboBox):
        return True
    return popup is not None and hasComplexAncestors(popup.getInvoker())
Ejemplo n.º 31
0
def saveTable():
    def after():
        # UI elements to alter under the event dispatch thread
        note_status.setText("Saved.")
        edit_note.setEnabled(True)
        save_note.setEnabled(False)

    # Repeatedly attempt to write the CSV until there are no more updates,
    # in which case the scheduled thread (see below) will pause for a bit before retrying.
    while requested_save_csv.getAndSet(False):
        writeCSV(csv_image_notes, header, entries)
        SwingUtilities.invokeLater(after)
Ejemplo n.º 32
0
def showTable(rows,
              title="Table",
              column_names=None,
              dataType=Number,
              width=400,
              height=500,
              showTable=True,
              windowClosing=None,
              onCellClickFn=None,
              onRowClickFn=None):
    """
     rows: list of lists of numbers.
     title: for the JFrame
     column_names: list of strings, or None
     width: defaults to 400 px
     height: defaults to 500 px
     showTable: whether to show the JFrame.
     windowClosing: an optional function to execute when the table's JFrame is closed.
     onClickCellFn: an optional function to execute when a table's cell is clicked, and receiving 3 args: row index, col index, cell value.
     onRowCellFn: an optinal function to execute when a table's row is clicked, and receiving as args the whole row.
     
     return: a tuple with the JTable and the JFrame
  """
    table_data = DataTable(rows,
                           column_names=column_names,
                           onCellClickFn=onCellClickFn,
                           onRowClickFn=onRowClickFn)
    table = JTable(table_data)
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
    #table.setAutoCreateRowSorter(True) # to sort the view only, not the data in the underlying TableModel
    sorter = TableRowSorter(table_data)
    sorter.setComparator(0, Comparator.naturalOrder())
    sorter.setComparator(1, Comparator.naturalOrder())
    sorter.setComparator(2, Comparator.naturalOrder())
    table.setRowSorter(sorter)

    frame = JFrame(title) if windowClosing is None else JFrame(
        title, windowClosing=windowClosing)
    jsp = JScrollPane(table)
    jsp.setMinimumSize(Dimension(width, height))
    frame.getContentPane().add(jsp)

    def show():
        frame.pack()
        frame.setVisible(True)

    if showTable:
        SwingUtilities.invokeLater(show)

    return table, frame
Ejemplo n.º 33
0
def snapshot(frame, box):
    bi = BufferedImage(box.width, box.height, BufferedImage.TYPE_INT_RGB)
    g = bi.createGraphics()
    g.translate(-box.x, -box.y)
    # all black! # frame.paintAll(g)
    # only swing components! # frame.paint(g)
    # only swing components! # frame.update(g)
    # together, also only swing and with errors
    ##frame.update(g)
    ##frame.paint(g)
    # locks the entire graphics machinery # frame.printAll(g)
    # Finally, the right one:
    SwingUtilities.invokeAndWait(PrintAll(frame, g))
    return bi
Ejemplo n.º 34
0
def runSwing(func, *args, **kwargs):
    """
    Runs the given function in the Event Dispatch Thread.
    If this is invoked inside the EDT, the given function will be run normally.
    Otherwise, it'll be queued to be run later.
    
    :return: None

    """
    if SwingUtilities.isEventDispatchThread():
        func(*args, **kwargs)
    else:
        runnable = RunnableWrapper(func, args, kwargs)
        SwingUtilities.invokeLater(runnable)
Ejemplo n.º 35
0
    def undoAction(self):
        """Undo the action."""
        if not self.finished:
            messages.showError("Action was never done, so it can't be undone")
            return

        """Does the action layer, starts an appropriate thread"""
        if self.spawn_thread and SwingUtilities.isEventDispatchThread():
            threading.Thread(target=self.undoInternal).start()
        elif self.spawn_thread or SwingUtilities.isEventDispatchThread():
            # In the thread we want to be
            self.undoInternal()
        else:
            SwingUtilities.invokeLater(RunWrapper(self.undoInternal))
Ejemplo n.º 36
0
    def buildNetwork(self, network):
        network.name = "Integrator"

        # Util.debugMsg("Network building started")

        f = ConstantFunction(1, 1.0)
        input = FunctionInput("input", [f], Units.UNK)

        # uiViewer.addNeoNode(uiInput);

        ef = NEFEnsembleFactoryImpl()
        integrator = ef.make("integrator", 500, 1, "integrator1", False)
        interm = integrator.addDecodedTermination("input", [[tau]], tau, False)
        fbterm = integrator.addDecodedTermination("feedback", [[1.0]], tau, False)

        network.addNode(integrator)
        time.sleep(1)
        network.addNode(input)
        time.sleep(1)
        # UINEFEnsemble uiIntegrator = new UINEFEnsemble(integrator);
        # uiViewer.addNeoNode(uiIntegrator);
        # uiIntegrator.collectSpikes(true);

        # UITermination uiInterm =
        # uiIntegrator.showTermination(interm.getName());
        # UITermination uiFbterm =
        # uiIntegrator.showTermination(fbterm.getName());

        network.addProjection(input.getOrigin(FunctionInput.ORIGIN_NAME), interm)
        time.sleep(0.5)
        network.addProjection(integrator.getOrigin(NEFEnsemble.X), fbterm)
        time.sleep(0.5)

        # Test removing projections
        network.removeProjection(interm)
        time.sleep(0.5)
        # add the projection back
        network.addProjection(input.getOrigin(FunctionInput.ORIGIN_NAME), interm)
        time.sleep(0.5)
        # Add probes
        integratorXProbe = network.simulator.addProbe("integrator", NEFEnsemble.X, True)
        time.sleep(0.5)
        # Test adding removing probes
        network.simulator.removeProbe(integratorXProbe)
        time.sleep(0.5)
        # add the probe back
        network.simulator.addProbe("integrator", NEFEnsemble.X, True)
        time.sleep(0.5)

        SwingUtilities.invokeLater(make_runnable(self.doPostUIStuff))
Ejemplo n.º 37
0
def snapshot(frame, box):
    bi = BufferedImage(box.width, box.height, BufferedImage.TYPE_INT_RGB)
    g = bi.createGraphics()
    g.translate(-box.x, -box.y)
    #all black! # frame.paintAll(g)
    #only swing components! # frame.paint(g)
    #only swing components! # frame.update(g)
    #together, also only swing and with errors
    ##frame.update(g)
    ##frame.paint(g)
    # locks the entire graphics machinery # frame.printAll(g)
    # Finally, the right one:
    SwingUtilities.invokeAndWait(PrintAll(frame, g))
    return bi
Ejemplo n.º 38
0
 def update(self, rect_list=None):
     """
     Repaint display.
     Optional rect or rect list to specify regions to repaint.
     """
     if isinstance(rect_list, list):
         self._rect_list = rect_list
     elif rect_list:
         self._rect_list = [rect_list]
     else:
         self._rect_list = self._surface_rect
     try:
         SwingUtilities.invokeAndWait(self)
     except InterruptedException:
         Thread.currentThread().interrupt()
Ejemplo n.º 39
0
def runSwing(func, *args, **kwargs):
    """
    Runs the given function in the Event Dispatch Thread.
    If this is invoked inside the EDT, the given function will be run normally.
    Otherwise, it'll be queued to be run later.
    The return value from the target function will not be available.

    :return: None

    """
    if SwingUtilities.isEventDispatchThread():
        func(*args, **kwargs)
    else:
        runnable = RunnableWrapper(func, args, kwargs)
        SwingUtilities.invokeLater(runnable)
Ejemplo n.º 40
0
 def update(self, rect_list=None):
     """
     Repaint display.
     Optional rect or rect list to specify regions to repaint.
     """
     if isinstance(rect_list, list):
         self._rect_list = rect_list
     elif rect_list:
         self._rect_list = [rect_list]
     else:
         self._rect_list = self._surface_rect
     try:
         SwingUtilities.invokeAndWait(self)
     except InterruptedException:
         Thread.currentThread().interrupt()
Ejemplo n.º 41
0
 def select(e):
     rowAtPoint = self.resultTable.rowAtPoint(
         SwingUtilities.convertPoint(self.resultTablePopupMenu,
                                     Point(0, 0), self.resultTable))
     if rowAtPoint > -1:
         self.resultTable.setRowSelectionInterval(
             rowAtPoint, rowAtPoint)
Ejemplo n.º 42
0
def selectWindow(widget):
    w = checkWidget(widget)
    window = SwingUtilities.getWindowAncestor(w)
    if isinstance(window, JFrame):
        runKeyword("selectWindow", window.getTitle())
    elif isinstance(window, JDialog):
        runKeyword("selectDialog", window.getTitle())
Ejemplo n.º 43
0
			def mouseDragged(ms, m):
				window = SwingUtilities.getWindowAncestor(self)
				x = window.getLocation().x
				y = window.getLocation().y
				xm = (x + m.getX()) - (x + self.initialClick.x)
				ym = (y + m.getY()) - (y + self.initialClick.y)
				window.setLocation(x + xm, y + ym)
Ejemplo n.º 44
0
def _swingWaitForResult(func, *args, **kwargs):
    # the naming of this function, along with _swingRunner, is kinda
    # misleading; both functions will "wait" for the result (due to the get()).
    # the difference between the two is that this function "wraps"
    # invokeAndWait,  while _swingRunner "wraps" invokeLater.
    #
    # the real world difference is that this function puts its Task at the
    # beginning of the event dispatch thread, while _swingRunner appends to the
    # end of the queue.
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)

    wrappedCode = _JythonCallable(func, args, kwargs)
    task = FutureTask(wrappedCode)
    SwingUtilities.invokeAndWait(task)
    return task.get()
Ejemplo n.º 45
0
def _swingWaitForResult(func, *args, **kwargs):
    # the naming of this function, along with _swingRunner, is kinda
    # misleading; both functions will "wait" for the result (due to the get()).
    # the difference between the two is that this function "wraps" 
    # invokeAndWait,  while _swingRunner "wraps" invokeLater.
    #
    # the real world difference is that this function puts its Task at the
    # beginning of the event dispatch thread, while _swingRunner appends to the 
    # end of the queue.
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
        
    wrappedCode = _JythonCallable(func, args, kwargs)
    task = FutureTask(wrappedCode)
    SwingUtilities.invokeAndWait(task)
    return task.get()
Ejemplo n.º 46
0
 def mouseDragged(ms, m):
     window = SwingUtilities.getWindowAncestor(self)
     x = window.getLocation().x
     y = window.getLocation().y
     xm = (x + m.getX()) - (x + self.initialClick.x)
     ym = (y + m.getY()) - (y + self.initialClick.y)
     window.setLocation(x + xm, y + ym)
Ejemplo n.º 47
0
def callSwing(func, *args, **kwargs):
    """
    Runs the given function in the Event Dispatch Thread.
    If this is invoked inside the EDT, the given function will be run normally.
    Otherwise, it'll be queued to be run and the calling thread will block
    until the function has been executed.

    :return: func's return value

    """
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)

    callable = CallableWrapper(func, args, kwargs)
    task = FutureTask(callable)
    SwingUtilities.invokeAndWait(task)
    return task.get()
Ejemplo n.º 48
0
def callSwing(func, *args, **kwargs):
    """
    Runs the given function in the Event Dispatch Thread.
    If this is invoked inside the EDT, the given function will be run normally.
    Otherwise, it'll be queued to be run and the calling thread will block
    until the function has been executed.
    
    :return: func's return value

    """
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)

    callable = CallableWrapper(func, args, kwargs)
    task = FutureTask(callable)
    SwingUtilities.invokeAndWait(task)
    return task.get()
Ejemplo n.º 49
0
def filterTable():
    global table_entries  # flag global variable as one to modify here
    try:
        text = search_field.getText()
        if 0 == len(text):
            table_entries = entries  # reset: show all rows
        else:
            pattern = re.compile(text)
            # Search in filepath and notes
            table_entries = [
                row for row in entries
                if pattern.search(row[-2]) or pattern.search(row[-1])
            ]
        SwingUtilities.invokeLater(
            lambda: table.updateUI())  # executed by the event dispatch thread
    except:
        print "Malformed regex pattern"
Ejemplo n.º 50
0
    def readInput(self, message):
	#to be threadsafe on this call we need this to update the command window
	class outputPromptRunner(Runnable):
	    def __init__(self, cw, m):
		self.commandWindow = cw
		self.message = m
		
	    def run(self):
		#display the message and reenable the window to editing
		self.commandWindow.showText(self.message)
		self.commandWindow.setCaretPosition(self.commandWindow.document.getLength() )
		self.commandWindow.setKeymap(self.commandWindow.my_keymap)


	#--------------The Actual work goes here------------------
	
	if not message:
	    message = ""

	#first assign value to null
	self.value = None

	#note that the this interpreter thread needs to wait now
	#until a result comes back from the command window
	self.waitingFlag = True
    
	#update the command window with the ouput
	SwingUtilities.invokeAndWait(outputPromptRunner(self.commandWindow, message))

	#Now we wait for the user to input a value and press ENTER in the command window,
	#pausing a 10th of a second between checks.
	while self.waitingFlag:
		time.sleep(0.1)

	#clean up the return value to remove the prompt since the command
	#window will give us everything
	self.value = self.value[len(message):]

	#return the value to media.py
	return self.value
Ejemplo n.º 51
0
 def redraw(self, delay=0.0):
     """
     Redraws the :py:class:`~jygsaw.graphicswindow.Canvas`.
     Only returns when done. An optional float can also be used to sleep after redrawing.
     """
     # Use non-blocking redraw because there is no one-to-one relation
     # between calling cavas.repaint() and execution of paintComponent()
     #
     if SwingUtilities.isEventDispatchThread():
         self.frame.contentPane.repaint()
     else:
         self.frame.contentPane.blocking_redraw()
     sleep(delay)
Ejemplo n.º 52
0
 def decorated(*args, **kwargs):
     if not SwingUtilities.isEventDispatchThread():
         raise RuntimeError("Not on the AWT event dispatch thread")
     return fn(*args, **kwargs)
Ejemplo n.º 53
0
def invokeLater(fn, *args, **kwargs):
    task = FunctionCall(fn, args, kwargs)
    SwingUtilities.invokeLater(task)
Ejemplo n.º 54
0
    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)
Ejemplo n.º 55
0
 def getContextName(self):
     if SwingUtilities.getAncestorOfClass(JInternalFrame, self.widget):
         return "Internal Frame"
     elif SwingUtilities.getAncestorOfClass(JInternalFrame.JDesktopIcon, self.widget):  # @UndefinedVariable
         return "Internal Frame Icon"
Ejemplo n.º 56
0
 def getDialogTitle(self):
     window = SwingUtilities.getWindowAncestor(self.widget)
     return window.getTitle() if window and hasattr(window, "getTitle") and window.getOwner() else ""
from   java.lang      import Runnable;
from   javax.swing    import JFrame;
from   javax.swing    import SwingUtilities;
class ToBeDetermined( Runnable ) :
    def __init__( self ) :
        self.frame = JFrame( 'ToBeDetermined' , defaultCloseOperation = JFrame.EXIT_ON_CLOSE );        
    def run( self ) :
        self.frame.setVisible( 1 );   # Have the application make itself visible

SwingUtilities.invokeLater( ToBeDetermined() );
raw_input();

Ejemplo n.º 58
0
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     jocl_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'JOCL Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
    
    def onJava(self, e): 
     self.clockLabel.setText('running')
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     java_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'Java Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
     

     
     
    
if ( __name__ == '__main__' ) or ( __name__ == 'main' ) :
    SwingUtilities.invokeLater( Demo() )
    raw_input();
    sys.exit();
else :
  print 'Error - script must be executed, not imported.\n';
  print 'Usage: jython %s.py\n' % __name__;
  print '   or: wsadmin -conntype none -f %s.py' % __name__;
Ejemplo n.º 59
0
def invokeAndWait(func, *args, **kwargs):
    """Convenience method for SwingUtilities.invokeAndWait()."""    
    SwingUtilities.invokeAndWait(ProcRunnable(func, *args, **kwargs))
    return
Ejemplo n.º 60
0
  equal = False
  while not equal and digits>0:
    almost = Almost(digits)
    equal = almost.equal(xa,xb)
    if not equal:
      digits -= 1
  return digits

def dot(u,v):
  return sum(mul(u,v))

def zfloat(n1,n2):
  return zerofloat(n1,n2)

def rfloat(n1,n2):
  r = randfloat(random,n1,n2)
  sub(r,0.5,r)
  mul(2.0,r,r)
  return r

##############################################################################
# Do everything on Swing thread.

import sys
from java.lang import Runnable
from javax.swing import SwingUtilities
class RunMain(Runnable):
  def run(self):
    main(sys.argv)
SwingUtilities.invokeLater(RunMain())