How to use pscript - 10 common examples

To help you get started, we’ve selected a few pscript examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flexxui / flexx / flexx / app / _clientcore.py View on Github external
window.flexx.spin()
            address = window.location.protocol + '//' + self.ws_url.split('/')[2]
            code += '\n//# sourceURL=%s/flexx/assets/shared/%s\n' % (address, name)
            if kind == 'JS-EVAL':
                eval(code)
            elif kind == 'JS':
                # With this method, sourceURL does not work on Firefox,
                # but eval might not work for assets that don't "use strict"
                # (e.g. Bokeh). Note, btw, that creating links to assets does
                # not work because these won't be loaded on time.
                el = window.document.createElement("script")
                el.id = name
                el.innerHTML = code
                window.flexx.asset_node.appendChild(el)
            elif kind == 'CSS':
                el = window.document.createElement("style")
                el.type = "text/css"
                el.id = name
                el.innerHTML = code
                window.flexx.asset_node.appendChild(el)
            else:
                window.console.error('Dont know how to DEFINE ' +
                                     name + ' with "' + kind + '".')
        elif cmd == 'OPEN':
            window.win1 = window.open(command[1], 'new', 'chrome')
        else:
            window.console.error('Invalid command: "' + cmd + '"')
        return command
github flexxui / flexx / flexx / app / _clientcore.py View on Github external
elif cmd == 'DISPOSE_ACK':
            self.instances.pop(command[1], None)  # Drop reference
        elif cmd == 'DEFINE':
            #and command[1] == 'JS' or command[1] == 'DEFINE-JS-EVAL '):
            kind, name, code = command[1:]
            window.flexx.spin()
            address = window.location.protocol + '//' + self.ws_url.split('/')[2]
            code += '\n//# sourceURL=%s/flexx/assets/shared/%s\n' % (address, name)
            if kind == 'JS-EVAL':
                eval(code)
            elif kind == 'JS':
                # With this method, sourceURL does not work on Firefox,
                # but eval might not work for assets that don't "use strict"
                # (e.g. Bokeh). Note, btw, that creating links to assets does
                # not work because these won't be loaded on time.
                el = window.document.createElement("script")
                el.id = name
                el.innerHTML = code
                window.flexx.asset_node.appendChild(el)
            elif kind == 'CSS':
                el = window.document.createElement("style")
                el.type = "text/css"
                el.id = name
                el.innerHTML = code
                window.flexx.asset_node.appendChild(el)
            else:
                window.console.error('Dont know how to DEFINE ' +
                                     name + ' with "' + kind + '".')
        elif cmd == 'OPEN':
            window.win1 = window.open(command[1], 'new', 'chrome')
        else:
            window.console.error('Invalid command: "' + cmd + '"')
github flexxui / flexx / flexx / app / _clientcore.py View on Github external
#and command[1] == 'JS' or command[1] == 'DEFINE-JS-EVAL '):
            kind, name, code = command[1:]
            window.flexx.spin()
            address = window.location.protocol + '//' + self.ws_url.split('/')[2]
            code += '\n//# sourceURL=%s/flexx/assets/shared/%s\n' % (address, name)
            if kind == 'JS-EVAL':
                eval(code)
            elif kind == 'JS':
                # With this method, sourceURL does not work on Firefox,
                # but eval might not work for assets that don't "use strict"
                # (e.g. Bokeh). Note, btw, that creating links to assets does
                # not work because these won't be loaded on time.
                el = window.document.createElement("script")
                el.id = name
                el.innerHTML = code
                window.flexx.asset_node.appendChild(el)
            elif kind == 'CSS':
                el = window.document.createElement("style")
                el.type = "text/css"
                el.id = name
                el.innerHTML = code
                window.flexx.asset_node.appendChild(el)
            else:
                window.console.error('Dont know how to DEFINE ' +
                                     name + ' with "' + kind + '".')
        elif cmd == 'OPEN':
            window.win1 = window.open(command[1], 'new', 'chrome')
        else:
            window.console.error('Invalid command: "' + cmd + '"')
        return command
github flexxui / flexx / flexxamples / demos / d3_collision.py View on Github external
color = d3.scale.category10()

        force = d3.layout.force().gravity(0.05).charge(lambda d, i: 0 if i else -2000)\
            .nodes(nodes).size([w, h])

        root = nodes[0]
        root.radius = 0
        root.fixed = True

        force.start()

        x = d3.select('#' + self.id)
        print(x, self.id)
        svg = RawJS('x.append("svg").attr("width", w).attr("height", h)')

        x = RawJS(
            'svg.selectAll("circle").data(nodes.slice(1)).enter().append("circle")')
        x.attr("r", lambda d: d.radius).style("fill", lambda d, i: color(i % 3))

        def on_tick(e):
            q = d3.geom.quadtree(nodes)
            i = 0
            n = nodes.length
            while i < n-1:
                i += 1
                q.visit(collide(nodes[i]))
            svg.selectAll("circle").attr("cx", lambda d: d.x).attr("cy", lambda d: d.y)

        force.on("tick", on_tick)

        def on_mousemove():
            p1 = d3.mouse(self.node)
github flexxui / flexx / flexx / ui / _widget.py View on Github external
# Include basic support for multi-touch
            touches = {}
            for i in range(e.changedTouches.length):
                t = e.changedTouches[i]
                if t.target is not e.target:
                    continue
                touches[t.identifier] = (float(t.clientX - offset[0]),
                                         float(t.clientY - offset[1]),
                                         t.force)
        else:
            # Mouse event
            pos = float(e.clientX - offset[0]), float(e.clientY - offset[1])
            page_pos = e.pageX, e.pageY
            # Fix buttons
            if e.buttons:
                buttons_mask = RawJS(
                    "e.buttons.toString(2).split('').reverse().join('')"
                )
            else:
                # libjavascriptcoregtk-3.0-0  version 2.4.11-1 does not define
                # e.buttons
                buttons_mask = [e.button.toString(2)]
            buttons = [i+1 for i in range(5) if buttons_mask[i] == '1']
            button = {0: 1, 1: 3, 2: 2, 3: 4, 4: 5}[e.button]
            touches = {-1: (pos[0], pos[1], 1)}  # key must not clash with real touches

        # note: our button has a value as in JS "which"
        modifiers = [n for n in ('Alt', 'Shift', 'Ctrl', 'Meta')
                        if e[n.toLowerCase() + 'Key']]
        # Create event dict
        return dict(pos=pos, page_pos=page_pos, touches=touches,
                    button=button, buttons=buttons,
github flexxui / flexx / flexx / event / _js.py View on Github external
def __create_reaction_ob(self, reaction_func, name, mode, connection_strings):
        # Keep ref to the reaction function, see comment in create_action().

        # Create function that becomes our "reaction object"
        def reaction():
            return reaction_func.apply(self, arguments)  # arguments == events

        # Attach methods to the function object (this gets replaced)
        REACTION_METHODS_HOOK  # noqa

        # Init reaction
        that = self
        RawJS("Component.prototype._REACTION_COUNT += 1")
        reaction._id = RawJS("'r' + Component.prototype._REACTION_COUNT")
        reaction._name = name
        reaction._mode = mode
        reaction._ob1 = lambda : that  # no weakref in JS
        reaction._init(connection_strings, self)

        return reaction
github flexxui / flexx / flexx / event / _js.py View on Github external
elif callable(connection_strings[-1]):
            func = connection_strings[-1]
            connection_strings = connection_strings[:-1]
        else:
            raise TypeError('Component.reaction() requires a callable.')

        # Verify connection strings
        for i in range(len(connection_strings)):
            s = connection_strings[i]
            if not (isinstance(s, str) and len(s)):
                raise ValueError('Connection string must be nonempty strings.')

        # Get function name (Flexx sets __name__ on methods)
        name = RawJS("func.__name__ || func.name || 'anonymous'")
        # name = name.split(' ')[-1].split('flx_')[-1]
        nameparts = RawJS("name.split(' ')")
        nameparts = RawJS("nameparts[nameparts.length-1].split('flx_')")
        name = nameparts[-1]
        mode = 'normal'
        return self.__create_reaction_ob(func, name, mode, connection_strings)
github flexxui / flexx / flexx / event / _js.py View on Github external
def __create_reaction_ob(self, reaction_func, name, mode, connection_strings):
        # Keep ref to the reaction function, see comment in create_action().

        # Create function that becomes our "reaction object"
        def reaction():
            return reaction_func.apply(self, arguments)  # arguments == events

        # Attach methods to the function object (this gets replaced)
        REACTION_METHODS_HOOK  # noqa

        # Init reaction
        that = self
        RawJS("Component.prototype._REACTION_COUNT += 1")
        reaction._id = RawJS("'r' + Component.prototype._REACTION_COUNT")
        reaction._name = name
        reaction._mode = mode
        reaction._ob1 = lambda : that  # no weakref in JS
        reaction._init(connection_strings, self)

        return reaction
github flexxui / flexx / flexx / app / _clientcore.py View on Github external
def init_socket(self):
        """ Make the connection to Python.
        """
        # Check WebSocket support
        WebSocket = window.WebSocket
        if (WebSocket is undefined):
            window.document.body.textContent = 'Browser does not support WebSockets'
            raise "FAIL: need websocket"

        # Construct ws url
        if not self.ws_url:
            proto = 'ws'
            if window.location.protocol == 'https:':
                proto = 'wss'
            address = window.location.hostname
            if window.location.port:
                address += ':' + window.location.port
            self.ws_url = '%s://%s/flexx/ws/%s' % (proto, address, self.app_name)
        # Resolve public hostname
        self.ws_url = self.ws_url.replace('0.0.0.0', window.location.hostname)
        # Open web socket in binary mode
        self._ws = ws = WebSocket(self.ws_url)
        ws.binaryType = "arraybuffer"
        self.status = 2

        def on_ws_open(evt):
            window.console.info('Socket opened with session id ' + self.id)
            self.send_command('HI_FLEXX', self.id)
        def on_ws_message(evt):
            msg = evt.data  # bsdf-encoded command
            if not msg:
                pass  # ? drop glitchy message :/
github flexxui / flexx / flexx / app / _clientcore.py View on Github external
def _receive_command(self, command):
        """ Process a command send from the server.
        """
        cmd = command[0]
        if cmd == 'PING':
            # Used for roundtrip stuff, do at least one iter loop here ...
            window.setTimeout(self.send_command, 10, 'PONG', command[1])
        elif cmd == 'INIT_DONE':
            window.flexx.spin(None)
            while len(self._pending_commands):
                self._receive_raw_command(self._pending_commands.pop(0))
            self._pending_commands = None
            # print('init took', time() - self._init_time)
        elif cmd == 'PRINT':
            (window.console.ori_log or window.console.log)(command[1])
        elif cmd == 'EXEC':
            eval(command[1])
        elif cmd == 'EVAL':
            x = None
            if len(command) == 2:
                x = eval(command[1])
            elif len(command) == 3:
                x = eval('this.instances.' + command[1] + '.' + command[2])