Exemplo n.º 1
0
    def __init__(self, w=600, h=480, stage=document.body):
        """Crafty game engine constructor.

        :param w, h: The width and height of crafty window
        :param stage: An element to which this window will be attached
        :returns: An instance of Crafty
        """
        self.__crafty = JSObject(JSCrafty)
        self.__crafty.init(w, h, stage)
        Base.__init__(self, self.__crafty)
        ViewPort.__init__(self, self.__crafty)
def draw_markdown():
    # mk, scripts = markdown.mark(get_md())
    mk = window.marked(get_md())
    browser.document["markdown-result"].html = mk
    encodeURIComponent = JSObject(window.encodeURIComponent)
    browser.document.cookie = "markdown={md}".format(
        md=encodeURIComponent(get_md()))
Exemplo n.º 3
0
    def find_module(self):
        if not self._path.startswith('/pyschool'):
            raise ImportError

        fs = JSObject(window._FS)

        for _ext in ('.py', '/__init__.py'):
            self._modpath = '%s/%s%s' % (self._path, self._fullname, _ext)
            _msg = fs._read_file(self._modpath)

            if _msg['status'] == 'Okay':
                self._module = _msg['fileobj'].get_attribute('contents')
                return self

        #if we got here, we couldn't find the module
        raise ImportError
  def find_module(self):
      if not self._path.startswith('/pyschool'):
         raise ImportError

      fs=JSObject(window._FS)

      for _ext in ('.py', '/__init__.py'):
          self._modpath='%s/%s%s' % (self._path, self._fullname, _ext)
          _msg=fs._read_file(self._modpath)

          if _msg['status'] == 'Okay':
             self._module=_msg['fileobj'].get_attribute('contents')
             return self
    
      #if we got here, we couldn't find the module
      raise ImportError
    def _reset_modal(self):
        try:
            self._content.remove(doc["graphics-modal-footer"])
        except:
            pass

        self._window.remove(self._canvas)
        _svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
        JSObject(_svg).setAttribute("width", self._width)
        JSObject(_svg).setAttribute("height", self._height)
        JSObject(_svg).setAttribute("id", "svg")
        self._window <= _svg
        self._canvas = doc["svg"]
        try:
            clog("X:" + str(JSObject(self._canvas).getAttribute("width")))
        except Exception as e:
            clog("Exception: " + str(e))
    def add_editor(self, filename=None, content=""):
        if filename is None:
            filename = "Untitled-%s" % self._tabcount
            self._tabcount += 1
        _content = '<div id="%s" class="editclass" style="width:100%%;height:100%%">%s</div>'
        self._jquery(self._tab_container).tabs(
            'add', {
                'title': filename,
                'content': _content % (filename, content),
                'closable': True
            })
        #add ace editor to filename pre tag
        _editor = JSObject(ace).edit(filename)
        _session = _editor.getSession()
        _session.setMode("ace/mode/python")
        #_editor.setTheme("ace/theme/crimson_editor")
        #_session.setMode("ace/mode/python")
        #_session.setUseWrapMode(true)
        #_session.setTabSize(4)
        _editor.setOptions({
            'enableLiveAutocompletion': True,
            'enableSnippets': True,
            'highlightActiveLine': False,
            'highlightSelectedWord': True
        })
        _editor.focus()

        self._editors[filename] = _editor
        #set resize
        document[filename].bind('resize',
                                lambda x: self._editors[filename].resize(True))
Exemplo n.º 7
0
    def __init__(self, w=600, h=480, stage=document.body):
        """Crafty game engine constructor.

        :param w, h: The width and height of crafty window
        :param stage: An element to which this window will be attached
        :returns: An instance of Crafty
        """
        self.__crafty = JSObject(JSCrafty)
        self.__crafty.init(w, h, stage)
        Base.__init__(self, self.__crafty)
Exemplo n.º 8
0
  def add_editor(self, filename=None, content=""):
      if filename is None:
         filename = "Untitled-%s" % self._tabcount
         self._tabcount+=1

      #_content='<pre id="%s" class="editclass">%s</pre>'
      _content='<pre id="%s" class="editclass" style="width:100%%;height:100%%">%s</pre>'
      self._jquery(self._tab_container).tabs('add',
        {'title': filename,
         'content': _content % (filename, content), 
         'closable': True
        })

      #add ace editor to filename pre tag
      _editor=JSObject(ace).edit(filename)
      _session=_editor.getSession()
      _session.setMode("ace/mode/python")
      _editor.setTheme("ace/theme/crimson_editor")
      _session.setMode("ace/mode/python")
      #_session.setUseWrapMode(true)
      _session.setTabSize(4)

      _editor.focus()

      self._editors[filename]=_editor

      #set resize
      document[filename].bind('resize', lambda x: self._editors[filename].resize(True))
    def add_editor(self, filename=None, content=""):
        if filename is None:
            filename = "Untitled-%s" % self._tabcount
            self._tabcount += 1
        _content = '<div id="%s" class="editclass" style="width:100%%;height:100%%">%s</div>'
        self._jquery(self._tab_container).tabs('add', {
            'title': filename,
            'content': _content % (filename, content),
            'closable': True
        })
        #add ace editor to filename pre tag
        _editor = JSObject(window.ace).edit(filename)
        _session = _editor.getSession()
        _session.setMode("ace/mode/python")
        #_editor.setTheme("ace/theme/crimson_editor")
        #_session.setMode("ace/mode/python")
        #_session.setUseWrapMode(true)
        #_session.setTabSize(4)
        _editor.setOptions({
            'enableLiveAutocompletion': True,
            'enableSnippets': True,
            'highlightActiveLine': False,
            'highlightSelectedWord': True
        })
        _editor.focus()

        self._editors[filename] = _editor
        #set resize
        document[filename].bind('resize', lambda x: self._editors[filename].resize(True))
    def setHeight(self, height):
        """
        Sets the height of the window.
        @param height int: the height of the window
        @return None
        """
        # set svg container height
        JSObject(self._canvas).setAttribute("height", height)

        # set window height
        if APP_DEPLOYED:
            self._window.style.height = height+15
        else:
            self._window.style.height = height+2
    def setWidth(self, width):
        """
        Sets the width of the window.

        @param width int: the width of the window
        @return None
        """
        # set content width
        self._dialog.style.width = width+34

        # set svg container width
        JSObject(self._canvas).setAttribute("width", width)

        # set body width
        self._window.style.width = width+2
Exemplo n.º 12
0
 def crafty():
     from javascript import JSObject
     crafty = JSObject(Crafty)
     crafty.init(500, 350, document['game'])
     crafty.e('2D, DOM, Color').attr(dict(x=0, y=0, w=100, h=100)).color('#F00')  # .fourway(4)
     crafty.e('Floor, 2D, Canvas, Color').attr(dict(x=0, y=250, w=250, h=10)).color('green')
     crafty.canvas.init()
     #turn the sprite map into usable components
     cft.sprite(16, "sprite.png", {
         grass1: [0, 0],
         grass2: [1, 0],
         grass3: [2, 0],
         grass4: [3, 0],
         flower: [0, 1],
         bush1: [0, 2],
         bush2: [1, 2],
         player: [0, 3]
     })
Exemplo n.º 13
0

def getfilesystemencoding(*args, **kw):
    """getfilesystemencoding() -> string    
    Return the encoding used to convert Unicode filenames in
    operating system filenames."""
    return 'utf-8'


maxsize = 2147483647

maxunicode = 1114111

path = __BRYTHON__.path

path_hooks = list(JSObject(__BRYTHON__.path_hooks))

platform = "brython"

prefix = __BRYTHON__.brython_path

#version = '.'.join(str(x) for x in __BRYTHON__.version_info)
version = '3.0.0'
hexversion = 0x03000000  # python 3.0


class __version_info(object):
    def __init__(self, version_info):
        self.version_info = version_info
        self.major = version_info[0]
        self.minor = version_info[1]
Exemplo n.º 14
0
def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True


if module_exists('browser') and module_exists('javascript'):

    from browser import window, document
    from javascript import JSObject, JSConstructor

    GFX = JSObject(window.PIXI)
    GFX_Rectangle = JSConstructor(GFX.Rectangle)
    GFX_Texture = JSConstructor(GFX.Texture)
    GFX_Texture_fromImage = JSConstructor(GFX.Texture.fromImage)
    GFX_Sprite = JSConstructor(GFX.Sprite)
    GFX_Graphics = JSConstructor(GFX.Graphics)()
    GFX_Text = JSConstructor(GFX.Text)
    GFX_DetectRenderer = GFX.autoDetectRenderer
    SND = JSObject(window.buzz)
    SND_Sound = JSConstructor(SND.sound)

    class GFX_Window(object):
        def __init__(self, width, height, onclose):
            self._w = window.open("", "")
            self._stage = JSConstructor(GFX.Container)()
            self._renderer = GFX.autoDetectRenderer(width, height,
                                                    {'transparent': True})
Exemplo n.º 15
0
def getfilesystemencoding(*args, **kw):
    """getfilesystemencoding() -> string    
    Return the encoding used to convert Unicode filenames in
    operating system filenames."""
    return 'utf-8'


maxsize = 2147483647

maxunicode = 1114111

path = __BRYTHON__.path

#$B.meta_path does not get updated when we do sys.meta_path.append(blah)
meta_path = list(JSObject(__BRYTHON__.meta_path))
meta_path = __BRYTHON__.meta_path

platform = "brython"

prefix = __BRYTHON__.brython_path

version = '.'.join(str(x) for x in __BRYTHON__.version_info[:3])
#todo, put in a 'real' date, etc
version += " (default, Feb 29 2013, 00:00:00) \n[Javascript 1.5]"
hexversion = 0x03000000  # python 3.0


class __version_info(object):
    def __init__(self, version_info):
        self.version_info = version_info
Exemplo n.º 16
0
 def __init__(self):
     self.store = JSObject(__BRYTHON__.local_storage)
Exemplo n.º 17
0
class LocalStorage():
    storage_type = "local_storage"

    def __init__(self):
        if not has_local_storage:
            raise EnvironmentError("LocalStorage not available")
        self.store = JSObject(window.localStorage)

    def __delitem__(self, key):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        if key not in self:
            raise KeyError(key)
        self.store.removeItem(key)

    def __getitem__(self, key):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        res = __BRYTHON__.JSObject(self.store.getItem(key))
        if res is not None:
            return res
        raise KeyError(key)

    def __setitem__(self, key, value):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        if (not isinstance(value, str)):
            raise TypeError("value must be string")
        self.store.setItem(key, value)

    # implement "in" functionality
    def __contains__(self, key):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        res = __BRYTHON__.JSObject(self.store.getItem(key))
        if res is None:
            return False
        return True

    def __iter__(self):
        keys = self.keys()
        return keys.__iter__()

    def get(self, key, default=None):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        return __BRYTHON__.JSObject(self.store.getItem(key)) or default

    def pop(self, key, default=__UnProvided()):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        if type(default) is __UnProvided:
            ret = self.get(key)
            del self[key]  # will throw key error if doesn't exist
            return ret
        else:
            if key in self:
                ret = self.get(key)
                del self[key]
                return ret
            else:
                return default

    # while a real dict provides a view, returning a generator would less helpful than simply returning a list
    # and creating a custom iterator is overkill and would likely result in slower performance
    def keys(self):
        return [__BRYTHON__.JSObject(self.store.key(i)) for i in range(self.store.length)]

    def values(self):
        return [__BRYTHON__.JSObject(self.__getitem__(k)) for k in self.keys()]

    def items(self):
        return list(zip(self.keys(), self.values()))

    def clear(self):
        self.store.clear()

    def __len__(self):
        return self.store.length
Exemplo n.º 18
0
from browser import document, window
from javascript import JSObject, JSConstructor

from .utils import create_script_tag
from .primitive import box, arrow, cone, curve, pyramid, helix, cylinder, sphere, attach_trail, compound

from .vector import vec

version = "1.0"
#
# create_script_tag('../../labase/glow/jslibs/jquery-1.6.2.min.js')
# create_script_tag('../../labase/glow/jslibs/glow.1.0.min.js')
_glowscript = JSObject(window.glowscript)
'''
#find a better way to do this..
while 1:
  _glowscript = window.glowscript  # JSObject(glowscript)

  try:
    if _glowscript.version == version:
       break
  except TypeError:
    pass
'''


#or we could make this some type of function instead of a class
class glow:
    def __init__(self, container):
        self._id = document.get(id=container)[0]
        setattr(self._id, 'id', '')
Exemplo n.º 19
0
 def __init__(self):
     self.store = JSObject(__BRYTHON__.local_storage)
Exemplo n.º 20
0
from browser import window, document
from random import randint
from javascript import JSObject, JSConstructor

w = window.open("", "")

PIXI = JSObject(window.PIXI)
Stage = JSConstructor(PIXI.Container)
Sprite = JSConstructor(PIXI.Sprite)
GRAPHICS = JSConstructor(PIXI.Graphics)

STAGE = Stage()
RENDERER = PIXI.autoDetectRenderer(1000, 650, {'transparent': True})

w.document.body.appendChild(RENDERER.view)
nloops = 0


def animate(fake):
    w.requestAnimationFrame(animate)
    for s in sprites:
        s.poll()
    RENDERER.render(STAGE)


class BunnySprite(object):
    def __init__(self, stage, x, y):
        self.sprite = Sprite(PIXI.Texture.fromImage("bunny.png", False))
        self.sprite.interactive = True
        self.sprite.anchor.x = 0.5
        self.sprite.anchor.y = 0.5
Exemplo n.º 21
0
 def load_module(self, name):
     _mod = JSObject(__BRYTHON__.run_py)(TempMod(self._fullname),
                                         self._modpath, self._module)
     _mod.is_package = '.' in self._fullname
     return _mod
Exemplo n.º 22
0
from browser import window
from javascript import JSObject
import sys

_modules = dict(JSObject(window._custom_VFS))


class TempMod:
    def __init__(self, name):
        self.name = name


#define my custom import hook (just to see if it get called etc).
class CustomVFS:
    def __init__(self, fullname, path):
        self._fullname = fullname
        self._path = path  # we don't are about this...
        self._modpath = 'CUSTOM VFS'

    def find_module(self):
        self._module = _modules.get(self._fullname, None)
        if self._module is None:
            raise ImportError

        return self

    def load_module(self, name):
        _mod = JSObject(__BRYTHON__.run_py)(TempMod(self._fullname),
                                            self._modpath, self._module)
        _mod.is_package = '.' in self._fullname
        return _mod
Exemplo n.º 23
0
 def load_module(self, name):
     return JSObject(__BRYTHON__.run_py)(TempMod(self._fullname),
                                         self._modpath, self._module)
Exemplo n.º 24
0
 def __init__(self):
     self.store = JSObject(__BRYTHON__.session_storage)
Exemplo n.º 25
0
 def __init__(self):
     if not sys.has_session_storage:
         raise EnvironmentError("SessionStorage not available")
     self.store = JSObject(__BRYTHON__.session_storage)
Exemplo n.º 26
0
from javascript import JSConstructor
from javascript import JSObject
import math
 
cango = JSConstructor(Cango2D)
shapes2d = JSObject(shapes2D)
#tweener = JSConstructor(Tweener)
#drag2d = JSConstructor(Drag2D)
#svgtocgo2d = JSConstructor(svgToCgo2D)
#involutebezcoeffs = JSConstructor(involuteBezCoeffs)
creategeartooth = JSConstructor(createGearTooth)
#createintgeartooth= JSConstructor(createIntGearTooth)

cgo = cango("plotarea")

module = 3
teeth = 180
pressureAngle = 25

######################################
# 畫正齒輪輪廓
#####################################
'''
Rpitch = module*teeth/2
# base circle radius
Rb = Rpitch * math.cos(pressureAngle*math.pi/180)
print("基圓半徑:", Rb)
#generate Higuchi involute approximation
fs = 0.01  # start 1% off the base circle
fm = 0.25  # break 25% along involute
fe = 1     #end at 100%
 def __init__(self, tab_container='tt'):
     self._editors = {}
     self._tabcount = 0
     self._tab_container = '\#%s' % tab_container
     self._jquery = JSObject(jQuery)
     self._jquery(self._tab_container).tabs()
Exemplo n.º 28
0
def attach_trail(object, **kwargs):
    if isinstance(object, primitive):
        JSObject(glowscript.attach_trail)(object._prim, kwargs)
    else:
        JSObject(glowscript.attach_trail)(object, kwargs)
Exemplo n.º 29
0
 def __init__(self):
     if not sys.has_local_storage:
         raise EnvironmentError("LocalStorage not available")
     self.store = JSObject(__BRYTHON__.local_storage)
Exemplo n.º 30
0
 def __init__(self, element_or_html):
     if isinstance(element_or_html, str):
         element_or_html = dom_from_html(element_or_html)[0].elt
     self._elt = JSObject(element_or_html)
     if self._elt.nodeType == self._elt.ELEMENT_NODE:
         self.name = self._elt.tagName
Exemplo n.º 31
0
 def __init__(self):
     if not has_local_storage:
         raise EnvironmentError("LocalStorage not available")
     self.store = JSObject(window.localStorage)
Exemplo n.º 32
0
class BCrafty(Base):
    """Crafty game engine main class.  :ref:`crafty`

    :param w: The width of crafty window
    :param h: The height of crafty window
    :param stage: An element to which this window will be attached
    :returns: An instance of Crafty
    """
    def __init__(self, w=600, h=480, stage=document.body):
        """Crafty game engine constructor.

        :param w, h: The width and height of crafty window
        :param stage: An element to which this window will be attached
        :returns: An instance of Crafty
        """
        self.__crafty = JSObject(JSCrafty)
        self.__crafty.init(w, h, stage)
        Base.__init__(self, self.__crafty)

    def e(self, comp='2D, DOM, Color'):
        """Entity. :class:`crafty.core.BCrafty`

        :param comp: A string with components ex:'2D, DOM, Color'
        :returns: An Entity instance
        """
        from .entity import Entity
        return Entity(self.__crafty, comp)

    @property
    def crafty(self):
        """Crafty js core. :class:`crafty.core.BCrafty`

        :returns: A javascript crafty instance
        """
        return self.__crafty

    def canvas(self):
        """create a drawing canvas. :class:`crafty.core.BCrafty`

        :returns: A javascript crafty instance
        """
        return JSObject(JSCrafty.canvas)  # self.__crafty

    def scene(self, scene, init=None, uninit=lambda: None):
        """Crafty Scene. :class:`crafty.core.BCrafty`

        :returns: A crafty scene
        """
        if not init:
            return self.__crafty.enterScene(scene, 0)
        return self.__crafty.scene(scene, init, uninit)

    def load(self, name, init):
        """Crafty Load. :class:`crafty.core.BCrafty`

        :returns: Load a crafty scene
        """
        return self.__crafty.load(name, init)

    def randRange(self, mini, maxi):
        """Random Range. :class:`crafty.core.BCrafty`

        :returns: a number ranging from mini to maxi
        """
        return randint(mini, maxi)

    def sprites(self, tile, url, **mapper):
        """Collection of sprites. :class:`crafty.core.BCrafty`

        :param tile: Tile size of the sprite map, defaults to 1
        :param url: URL of the sprite image
        :param map: Object where the key is what becomes a new component
         and the value points to a position on the sprite map
        :param paddingX: Horizontal space in between tiles. Defaults to 0.
        :param paddingY: Vertical space in between tiles. Defaults to paddingX.
        :param paddingAroundBorder: If padding should be applied around the border of the sprite sheet.
         If enabled the first tile starts at (paddingX,paddingY) instead of (0,0). Defaults to false.        """
        return self.__crafty.sprite(tile, url, dict(**mapper))

    def sprite(self, x, y, w, h):
        """Create a Sprite. :class:`crafty.core.BCrafty`

        :param x: position x of sprite
        :param y: position y of sprite
        :param w: width w of sprite
        :param h: height h of sprite
        :returns: An instance of Sprite
        """
        return Sprite(self.__crafty).sprite(x, y, w, h)

    def c(self, name, *comp, **items):
        """Creates a component naming the ID and passing an object. :class:`crafty.core.BCrafty`

        A couple of methods are treated specially.
        They are invoked in partiular contexts, and (in those contexts) cannot be overridden by other components.
        init will be called when the component is added to an entity
        remove will be called just before a component is removed, or before an entity is destroyed.
        It is passed a single boolean parameter that is true if the entity is being destroyed.

        :param name: Name of the component
        :param comp: Object with the component's properties and methods that will be inherited by entities.
        :param items: If component is not provided each keyword argument will be attached as a member of component.
        """
        comp = {str(k): getattr(comp[0], k) for k in dir(comp[0]) if '__' not in k} if comp else dict(**items)
        return self.__crafty.c(name, comp)
Exemplo n.º 33
0
class Local_Storage():
    storage_type = "local_storage"

    def __init__(self):
        self.store = JSObject(__BRYTHON__.local_storage)

    def __delitem__(self, key):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        if key not in self:
            raise KeyError(key)
        self.store.removeItem(key)

    def __getitem__(self, key):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        res = __BRYTHON__.JSObject(self.store.getItem(key))
        if res:
            return res
        raise KeyError(key)

    def __setitem__(self, key, value):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        if (not isinstance(value, str)):
            raise TypeError("value must be string")
        self.store.setItem(key, value)

    # implement "in" functionality
    def __contains__(self, key):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        res = __BRYTHON__.JSObject(self.store.getItem(key))
        if res is None:
            return False
        return True

    def __iter__(self):
        keys = self.keys()
        return keys.__iter__()

    def get(self, key, default=None):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        return __BRYTHON__.JSObject(self.store.getItem(key)) or default

    def pop(self, key, default=__UnProvided()):
        if (not isinstance(key, str)):
            raise TypeError("key must be string")
        if type(default) is __UnProvided:
            ret = self.get(key)
            del self[key]  # will throw key error if doesn't exist
            return ret
        else:
            if key in self:
                ret = self.get(key)
                del self[key]
                return ret
            else:
                return default

    # while a real dict provides a view, returning a generator would less helpful than simply returning a list
    # and creating a custom iterator is overkill and would likely result in slower performance
    def keys(self):
        return [
            __BRYTHON__.JSObject(self.store.key(i))
            for i in range(self.store.length)
        ]

    def values(self):
        return [__BRYTHON__.JSObject(self.__getitem__(k)) for k in self.keys()]

    def items(self):
        return list(zip(self.keys(), self.values()))

    def clear(self):
        self.store.clear()

    def __len__(self):
        return self.store.length
Exemplo n.º 34
0
import math

from browser import document
from javascript import JSObject

bRaphael = JSObject(Raphael)

out = document["output"]
vr = document["vr"]
vg = document["vg"]
vb = document["vb"]
vh = document["vh"]
vh2 = document["vh2"]
vs = document["vs"]
vs2 = document["vs2"]
vv = document["vv"]
vl = document["vl"]

def update_color(ev, cp, cp2):
    cp.color(ev.target.value)
    cp2.color(ev.target.value)

def on_change(item):

    def callback(clr):
        out.value = clr
        item.color(clr)
        out.style.background = clr
        out.style.color = "#fff" if bRaphael.rgb2hsb(clr).b < .5 else "#000"
        clr = bRaphael.color(clr)
        vr.html = clr.r
Exemplo n.º 35
0
import sys
import time
import dis
import traceback

from browser import document as doc
from javascript import JSObject

# set height of container to 66% of screen
_height = doc.documentElement.clientHeight
_s = doc["container"]
_s.style.height = "%spx" % int(_height * 0.66)

has_ace = True
try:
    editor = JSObject(ace).edit("editor")
    editor.getSession().setMode("ace/mode/python")
    editor.setTheme("ace/theme/monokai")
except:
    from browser import html

    editor = html.TEXTAREA(rows=20, cols=70)
    doc["editor"] <= editor

    def get_value():
        return editor.value

    def set_value(x):
        editor.value = x

    editor.getValue = get_value
Exemplo n.º 36
0
import sys
import time
import traceback
import dis

from browser import document as doc
from javascript import JSObject

# set height of container to 66% of screen
_height = doc.documentElement.clientHeight
_s = doc['container']
_s.style.height = '%spx' % int(_height*0.66)

has_ace = True
try:
    editor=JSObject(ace).edit("editor")
    editor.getSession().setMode("ace/mode/python")
except:
    from browser import html
    editor = html.TEXTAREA(rows=20,cols=70)
    doc["editor"] <= editor
    def get_value(): return editor.value
    def set_value(x):editor.value=x
    editor.getValue = get_value
    editor.setValue = set_value
    has_ace = False

if sys.has_local_storage:
    from browser.local_storage import storage
else:
    storage = False
Exemplo n.º 37
0
 def load_module(self, name):
     if name is None:
        name=self._fullname
     window.eval('__BRYTHON__.imported["%s"]={}' % name)
     return JSObject(__BRYTHON__.run_py)(self._module,
                                         self._modpath, TempMod(name))
Exemplo n.º 38
0
from javascript import JSObject

assert (JSObject(null) == None)
assert (JSObject(null) is None)
assert (None is None)
assert (None is JSObject(null))
assert (None == JSObject(null))
assert (JSObject(null) is JSObject(null))

print("All tests passed")
Exemplo n.º 39
0
class Tag:
    def __init__(self, element_or_html):
        if isinstance(element_or_html, str):
            element_or_html = dom_from_html(element_or_html)[0].elt
        self._elt = JSObject(element_or_html)
        if self._elt.nodeType == self._elt.ELEMENT_NODE:
            self.name = self._elt.tagName

    def get(self, key):
        return self._elt.getAttribute(key)

    @property
    def parent(self):
        if self._elt.parentElement is None:
            return Document()
        else:
            return Tag(self._elt.parentNode.elt)

    @property
    def parents(self):
        parent = self.parent
        while isinstance(parent, Tag):
            yield parent
            parent = parent.parent

    @property
    def next_sibling(self):
        return Tag(self._elt.nextSibling)

    @property
    def next_siblings(self):
        sib = self.next_sibling
        while sib is not None:
            yield sib
            sib = sib.next_sibling

    @property
    def previous_sibling(self):
        return Tag(self._elt.previousSibling)

    @property
    def previous_siblings(self):
        sib = self.previous_sibling
        while sib is not None:
            yield sib
            sib = sib.previous_sibling

    @property
    def next_element(self):
        return Tag(self._elt.nextElementSibling)

    @property
    def next_elements(self):
        sib = self.next_element
        while sib is not None:
            yield sib
            sib = sib.next_element

    @property
    def previous_element(self):
        return Tag(self._elt.previousElementSibling)

    @property
    def previous_elements(self):
        sib = self.previous_element
        while sib is not None:
            yield sib
            sib = sib.previous_element

    @property
    def contents(self):
        return [Tag(ch) for ch in self._elt.children]

    @property
    def children(self):
        return iter(self.contents())

    @property
    def descendants(self):
        for ch in self._elt.children:
            t = Tag(ch)
            yield t
            for d in t.descendants:
                yield d

    def append(self, tag_or_text):
        if isinstance(tag_or_text, str):
            self._elt.appendChild(dom_from_html(tag_or_text)[0].elt)
        else:
            self._elt.appendChild(tag_or_text._elt)

    def insert(self, pos, tag_or_text):
        if isinstance(tag_or_text, str):
            self._elt.insertBefore(
                dom_from_html(tag_or_text)[0].elt, self._elt.children[pos])
        else:
            self._elt.insertBefore(tag_or_text._elt, self._elt.children[pos])

    def __getitem__(self, key):
        ret = self._elt.getAttribute(key)
        if ret is None:
            raise KeyError(key)
        else:
            if key in [
                    'class', 'rev', 'accept-charset', 'headers', 'accesskey'
            ]:
                ret = ret.split(' ')
                if len(ret) == 1:
                    ret = ret[0]
            return ret

    def __setitem__(self, key, value):
        if isinstance(value, list):
            value = ' '.join(list)
        self._elt.setAttribute(key, value)
Exemplo n.º 40
0
 def __init__(self):
     if not has_local_storage:
         raise EnvironmentError("LocalStorage not available")
     self.store = JSObject(window.localStorage)
Exemplo n.º 41
0
import sys
import time
import dis
import traceback

from browser import doc
from javascript import JSObject

# set height of container to 66% of screen
_height = doc.documentElement.clientHeight
_s = doc['container']
_s.style.height = '%spx' % int(_height * 0.66)

has_ace = True
try:
    editor = JSObject(ace).edit("editor")
    editor.getSession().setMode("ace/mode/python")
    editor.setTheme("ace/theme/monokai")
except:
    from browser import html
    editor = html.TEXTAREA(rows=20, cols=70)
    doc["editor"] <= editor

    def get_value():
        return editor.value

    def set_value(x):
        editor.value = x

    editor.getValue = get_value
    editor.setValue = set_value
 def load_module(self, name):
     _mod=JSObject(__BRYTHON__.run_py)(TempMod(self._fullname),
                                       self._modpath, self._module)
     _mod.is_package='.' in self._fullname
     return _mod